ProjectController.mjs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. import _ from 'lodash'
  2. import OError from '@overleaf/o-error'
  3. import crypto from 'node:crypto'
  4. import { setTimeout } from 'node:timers/promises'
  5. import pProps from 'p-props'
  6. import logger from '@overleaf/logger'
  7. import { expressify } from '@overleaf/promise-utils'
  8. import mongodb from 'mongodb-legacy'
  9. import ProjectDeleter from './ProjectDeleter.mjs'
  10. import ProjectDuplicator from './ProjectDuplicator.mjs'
  11. import ProjectCreationHandler from './ProjectCreationHandler.mjs'
  12. import EditorController from '../Editor/EditorController.mjs'
  13. import ProjectHelper from './ProjectHelper.mjs'
  14. import metrics from '@overleaf/metrics'
  15. import { User } from '../../models/User.mjs'
  16. import SubscriptionLocator from '../Subscription/SubscriptionLocator.mjs'
  17. import SubscriptionHelper from '../Subscription/SubscriptionHelper.mjs'
  18. import LimitationsManager from '../Subscription/LimitationsManager.mjs'
  19. import Settings from '@overleaf/settings'
  20. import AuthorizationManager from '../Authorization/AuthorizationManager.mjs'
  21. import InactiveProjectManager from '../InactiveData/InactiveProjectManager.mjs'
  22. import ProjectUpdateHandler from './ProjectUpdateHandler.mjs'
  23. import ProjectGetter from './ProjectGetter.mjs'
  24. import PrivilegeLevels from '../Authorization/PrivilegeLevels.mjs'
  25. import SessionManager from '../Authentication/SessionManager.mjs'
  26. import Sources from '../Authorization/Sources.mjs'
  27. import TokenAccessHandler from '../TokenAccess/TokenAccessHandler.mjs'
  28. import CollaboratorsGetter from '../Collaborators/CollaboratorsGetter.mjs'
  29. import ProjectEntityHandler from './ProjectEntityHandler.mjs'
  30. import TpdsProjectFlusher from '../ThirdPartyDataStore/TpdsProjectFlusher.mjs'
  31. import Features from '../../infrastructure/Features.mjs'
  32. import BrandVariationsHandler from '../BrandVariations/BrandVariationsHandler.mjs'
  33. import UserController from '../User/UserController.mjs'
  34. import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
  35. import LocalsHelper from '../SplitTests/LocalsHelper.mjs'
  36. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  37. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.mjs'
  38. import FeaturesUpdater from '../Subscription/FeaturesUpdater.mjs'
  39. import SpellingHandler from '../Spelling/SpellingHandler.mjs'
  40. import AdminAuthorizationHelper from '../Helpers/AdminAuthorizationHelper.mjs'
  41. import InstitutionsFeatures from '../Institutions/InstitutionsFeatures.mjs'
  42. import InstitutionsGetter from '../Institutions/InstitutionsGetter.mjs'
  43. import ProjectAuditLogHandler from './ProjectAuditLogHandler.mjs'
  44. import PublicAccessLevels from '../Authorization/PublicAccessLevels.mjs'
  45. import TagsHandler from '../Tags/TagsHandler.mjs'
  46. import TutorialHandler from '../Tutorial/TutorialHandler.mjs'
  47. import UserUpdater from '../User/UserUpdater.mjs'
  48. import Modules from '../../infrastructure/Modules.mjs'
  49. import { z, zz, parseReq } from '../../infrastructure/Validation.mjs'
  50. import UserGetter from '../User/UserGetter.mjs'
  51. import { isStandaloneAiAddOnPlanCode } from '../Subscription/AiHelper.mjs'
  52. import SubscriptionController from '../Subscription/SubscriptionController.mjs'
  53. import { formatCurrency } from '../../util/currency.js'
  54. import UserSettingsHelper from './UserSettingsHelper.mjs'
  55. const { isPaidSubscription } = SubscriptionHelper
  56. const { hasAdminAccess } = AdminAuthorizationHelper
  57. const { ObjectId } = mongodb
  58. /**
  59. * @import { GetProjectsRequest, GetProjectsResponse, Project } from "./types"
  60. */
  61. const updateProjectAdminSettingsSchema = z.object({
  62. params: z.object({
  63. Project_id: zz.coercedObjectId(ObjectId),
  64. }),
  65. body: z.object({
  66. publicAccessLevel: z
  67. .enum(
  68. [PublicAccessLevels.PRIVATE, PublicAccessLevels.TOKEN_BASED],
  69. 'unexpected access level'
  70. )
  71. .optional(),
  72. }),
  73. })
  74. const updateProjectSettingsSchema = z.object({
  75. params: z.object({
  76. Project_id: zz.coercedObjectId(),
  77. }),
  78. body: z.object({
  79. compiler: z.string().optional(),
  80. imageName: z.string().optional(),
  81. mainBibliographyDocId: zz.objectId().optional(),
  82. name: z.string().optional(),
  83. rootDocId: zz.objectId().optional(),
  84. spellCheckLanguage: z.string().optional(),
  85. }),
  86. })
  87. const _ProjectController = {
  88. _isInPercentageRollout(rolloutName, objectId, percentage) {
  89. if (Settings.bypassPercentageRollouts === true) {
  90. return true
  91. }
  92. const data = `${rolloutName}:${objectId.toString()}`
  93. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  94. const counter = parseInt(md5hash.slice(26, 32), 16)
  95. return counter % 100 < percentage
  96. },
  97. async updateProjectSettings(req, res) {
  98. const { params, body } = parseReq(req, updateProjectSettingsSchema)
  99. const projectId = params.Project_id
  100. if (body.compiler != null) {
  101. await EditorController.promises.setCompiler(projectId, body.compiler)
  102. }
  103. if (body.imageName != null) {
  104. await EditorController.promises.setImageName(projectId, body.imageName)
  105. }
  106. if (body.name != null) {
  107. await EditorController.promises.renameProject(projectId, body.name)
  108. }
  109. if (body.spellCheckLanguage != null) {
  110. await EditorController.promises.setSpellCheckLanguage(
  111. projectId,
  112. body.spellCheckLanguage
  113. )
  114. }
  115. if (body.rootDocId != null) {
  116. await EditorController.promises.setRootDoc(projectId, body.rootDocId)
  117. }
  118. if (body.mainBibliographyDocId != null) {
  119. await EditorController.promises.setMainBibliographyDoc(
  120. projectId,
  121. body.mainBibliographyDocId
  122. )
  123. }
  124. res.sendStatus(204)
  125. },
  126. async updateProjectAdminSettings(req, res) {
  127. const { params, body } = parseReq(req, updateProjectAdminSettingsSchema)
  128. const projectId = params.Project_id
  129. const user = SessionManager.getSessionUser(req.session)
  130. if (!Features.hasFeature('link-sharing')) {
  131. return res.sendStatus(403) // return Forbidden if link sharing is not enabled
  132. }
  133. if (body.publicAccessLevel != null) {
  134. await EditorController.promises.setPublicAccessLevel(
  135. projectId,
  136. body.publicAccessLevel
  137. )
  138. await ProjectAuditLogHandler.promises.addEntry(
  139. projectId,
  140. 'toggle-access-level',
  141. user._id,
  142. req.ip,
  143. { publicAccessLevel: body.publicAccessLevel, status: 'OK' }
  144. )
  145. res.sendStatus(204)
  146. } else {
  147. res.sendStatus(500)
  148. }
  149. },
  150. async deleteProject(req, res) {
  151. const projectId = req.params.Project_id
  152. const user = SessionManager.getSessionUser(req.session)
  153. await ProjectDeleter.promises.deleteProject(projectId, {
  154. deleterUser: user,
  155. ipAddress: req.ip,
  156. })
  157. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  158. projectId,
  159. 'project-deleted',
  160. user._id,
  161. req.ip
  162. )
  163. res.sendStatus(200)
  164. },
  165. async archiveProject(req, res) {
  166. const projectId = req.params.Project_id
  167. const userId = SessionManager.getLoggedInUserId(req.session)
  168. await ProjectDeleter.promises.archiveProject(projectId, userId)
  169. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  170. projectId,
  171. 'project-archived',
  172. userId,
  173. req.ip
  174. )
  175. res.sendStatus(200)
  176. },
  177. async unarchiveProject(req, res) {
  178. const projectId = req.params.Project_id
  179. const userId = SessionManager.getLoggedInUserId(req.session)
  180. await ProjectDeleter.promises.unarchiveProject(projectId, userId)
  181. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  182. projectId,
  183. 'project-unarchived',
  184. userId,
  185. req.ip
  186. )
  187. res.sendStatus(200)
  188. },
  189. async trashProject(req, res) {
  190. const projectId = req.params.project_id
  191. const userId = SessionManager.getLoggedInUserId(req.session)
  192. await ProjectDeleter.promises.trashProject(projectId, userId)
  193. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  194. projectId,
  195. 'project-trashed',
  196. userId,
  197. req.ip
  198. )
  199. res.sendStatus(200)
  200. },
  201. async untrashProject(req, res) {
  202. const projectId = req.params.project_id
  203. const userId = SessionManager.getLoggedInUserId(req.session)
  204. await ProjectDeleter.promises.untrashProject(projectId, userId)
  205. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  206. projectId,
  207. 'project-untrashed',
  208. userId,
  209. req.ip
  210. )
  211. res.sendStatus(200)
  212. },
  213. async expireDeletedProjectsAfterDuration(_req, res) {
  214. await ProjectDeleter.promises.expireDeletedProjectsAfterDuration()
  215. res.sendStatus(200)
  216. },
  217. async expireDeletedProject(req, res) {
  218. const { projectId } = req.params
  219. await ProjectDeleter.promises.expireDeletedProject(projectId)
  220. res.sendStatus(200)
  221. },
  222. async restoreProject(req, res) {
  223. const user = SessionManager.getLoggedInUserId(req.session)
  224. const projectId = req.params.Project_id
  225. await ProjectDeleter.promises.restoreProject(projectId)
  226. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  227. projectId,
  228. 'project-restored',
  229. user._id,
  230. req.ip
  231. )
  232. res.sendStatus(200)
  233. },
  234. async cloneProject(req, res, next) {
  235. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  236. metrics.inc('cloned-project')
  237. const projectId = req.params.Project_id
  238. const { projectName, isDebugCopy, tags } = req.body
  239. logger.debug({ projectId, projectName, isDebugCopy }, 'cloning project')
  240. if (!SessionManager.isUserLoggedIn(req.session)) {
  241. return res.json({ redir: '/register' })
  242. }
  243. const currentUser = SessionManager.getSessionUser(req.session)
  244. const { first_name: firstName, last_name: lastName, email } = currentUser
  245. try {
  246. const project = await ProjectDuplicator.promises.duplicate(
  247. currentUser,
  248. projectId,
  249. projectName,
  250. tags,
  251. isDebugCopy
  252. )
  253. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  254. projectId,
  255. 'project-cloned',
  256. currentUser._id,
  257. req.ip
  258. )
  259. res.json({
  260. name: project.name,
  261. lastUpdated: project.lastUpdated,
  262. project_id: project._id,
  263. owner_ref: project.owner_ref,
  264. owner: {
  265. first_name: firstName,
  266. last_name: lastName,
  267. email,
  268. _id: currentUser._id,
  269. },
  270. })
  271. } catch (err) {
  272. OError.tag(err, 'error cloning project', {
  273. projectId,
  274. userId: currentUser._id,
  275. })
  276. return next(err)
  277. }
  278. },
  279. async newProject(req, res) {
  280. const currentUser = SessionManager.getSessionUser(req.session)
  281. const {
  282. first_name: firstName,
  283. last_name: lastName,
  284. email,
  285. _id: userId,
  286. } = currentUser
  287. const projectName =
  288. req.body.projectName != null ? req.body.projectName.trim() : undefined
  289. const { template } = req.body
  290. const project = await (template === 'example'
  291. ? ProjectCreationHandler.promises.createExampleProject(
  292. userId,
  293. projectName
  294. )
  295. : ProjectCreationHandler.promises.createBasicProject(userId, projectName))
  296. ProjectAuditLogHandler.addEntryIfManagedInBackground(
  297. project._id,
  298. 'project-created',
  299. project.owner_ref,
  300. req.ip
  301. )
  302. res.json({
  303. project_id: project._id,
  304. owner_ref: project.owner_ref,
  305. owner: {
  306. first_name: firstName,
  307. last_name: lastName,
  308. email,
  309. _id: userId,
  310. },
  311. })
  312. },
  313. async renameProject(req, res) {
  314. const projectId = req.params.Project_id
  315. const newName = req.body.newProjectName
  316. await EditorController.promises.renameProject(projectId, newName)
  317. res.sendStatus(200)
  318. },
  319. async userProjectsJson(req, res) {
  320. const userId = SessionManager.getLoggedInUserId(req.session)
  321. let projects = await ProjectGetter.promises.findAllUsersProjects(
  322. userId,
  323. 'name lastUpdated publicAccesLevel archived trashed owner_ref'
  324. )
  325. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  326. projects = ProjectController._buildProjectList(projects, userId)
  327. .filter(p => !(p.archived || p.trashed))
  328. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  329. res.json({ projects })
  330. },
  331. async projectEntitiesJson(req, res) {
  332. const projectId = req.params.Project_id
  333. const project = await ProjectGetter.promises.getProject(projectId)
  334. const { docs, files } =
  335. ProjectEntityHandler.getAllEntitiesFromProject(project)
  336. const entities = docs
  337. .concat(files)
  338. // Sort by path ascending
  339. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  340. .map(e => ({
  341. path: e.path,
  342. type: e.doc != null ? 'doc' : 'file',
  343. }))
  344. res.json({ project_id: projectId, entities })
  345. },
  346. async loadEditor(req, res, next) {
  347. const timer = new metrics.Timer('load-editor')
  348. if (!Settings.editorIsOpen) {
  349. return res.render('general/closed', { title: 'updating_site' })
  350. }
  351. let anonymous, userId, sessionUser
  352. if (SessionManager.isUserLoggedIn(req.session)) {
  353. sessionUser = SessionManager.getSessionUser(req.session)
  354. userId = SessionManager.getLoggedInUserId(req.session)
  355. anonymous = false
  356. } else {
  357. sessionUser = null
  358. anonymous = true
  359. userId = null
  360. }
  361. if (Features.hasFeature('saas') && userId) {
  362. const { variant: domainCaptureRedirect } =
  363. await SplitTestHandler.promises.getAssignment(
  364. req,
  365. res,
  366. 'domain-capture-redirect'
  367. )
  368. if (domainCaptureRedirect === 'enabled') {
  369. const subscription = (
  370. await Modules.promises.hooks.fire(
  371. 'findDomainCaptureGroupUserCouldBePartOf',
  372. userId
  373. )
  374. )?.[0]
  375. if (subscription) {
  376. if (subscription.managedUsersEnabled) {
  377. return res.redirect('/domain-capture')
  378. } else {
  379. // TODO show notification or anything else
  380. }
  381. }
  382. }
  383. }
  384. const projectId = req.params.Project_id
  385. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  386. function shouldDisplayFeature(name, variantFlag) {
  387. if (req.query && req.query[name]) {
  388. return req.query[name] === 'true'
  389. } else {
  390. return variantFlag === true
  391. }
  392. }
  393. const splitTests = [
  394. 'bibtex-visual-editor',
  395. 'compile-log-events',
  396. 'visual-preview',
  397. 'external-socket-heartbeat',
  398. 'null-test-share-modal',
  399. 'pdf-caching-prefetch-large',
  400. 'pdf-caching-prefetching',
  401. 'revert-file',
  402. 'revert-project',
  403. !anonymous && 'ro-mirror-on-client',
  404. 'track-pdf-download',
  405. !anonymous && 'writefull-oauth-promotion',
  406. 'hotjar',
  407. 'overleaf-assist-bundle',
  408. 'word-count-client',
  409. 'editor-popup-ux-survey',
  410. 'editor-redesign-new-users',
  411. 'writefull-frontend-migration',
  412. 'chat-edit-delete',
  413. 'ai-workbench-release',
  414. 'compile-timeout-target-plans',
  415. 'writefull-keywords-generator',
  416. 'writefull-figure-generator',
  417. 'wf-citations-checker',
  418. 'wf-citations-checker-on-selection',
  419. 'writefull-asymetric-queue-size-per-model',
  420. 'writefull-encourage-prompt-for-paraphrase',
  421. 'editor-context-menu',
  422. 'email-notifications',
  423. 'wf-enable-freemium-super-complete',
  424. 'wf-enable-super-complete-promotion',
  425. 'plans-2026-phase-1',
  426. ].filter(Boolean)
  427. const getUserValues = async userId =>
  428. pProps(
  429. _.mapValues({
  430. user: (async () => {
  431. const user = await User.findById(
  432. userId,
  433. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsExperiments completedTutorials writefull aiFeatures'
  434. ).exec()
  435. // Handle case of deleted user
  436. if (!user) {
  437. UserController.logout(req, res, next)
  438. return
  439. }
  440. logger.debug({ projectId, userId }, 'got user')
  441. return FeaturesUpdater.featuresEpochIsCurrent(user)
  442. ? user
  443. : await ProjectController._refreshFeatures(req, user)
  444. })(),
  445. learnedWords: SpellingHandler.promises.getUserDictionary(userId),
  446. projectTags: TagsHandler.promises.getTagsForProject(
  447. userId,
  448. projectId
  449. ),
  450. userHasInstitutionLicence: InstitutionsFeatures.promises
  451. .hasLicence(userId)
  452. .catch(err => {
  453. logger.error({ err, userId }, 'failed to get institution licence')
  454. return false
  455. }),
  456. affiliations: InstitutionsGetter.promises
  457. .getCurrentAffiliations(userId)
  458. .catch(err => {
  459. logger.error(
  460. { err, userId },
  461. 'failed to get current affiliations'
  462. )
  463. return false
  464. }),
  465. subscription:
  466. SubscriptionLocator.promises.getUsersSubscription(userId),
  467. isTokenMember: CollaboratorsGetter.promises.userIsTokenMember(
  468. userId,
  469. projectId
  470. ),
  471. isInvitedMember:
  472. CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  473. userId,
  474. projectId
  475. ),
  476. })
  477. )
  478. try {
  479. const responses = await pProps({
  480. userValues: userId ? getUserValues(userId) : defaultUserValues(),
  481. project: ProjectGetter.promises.getProject(projectId, {
  482. name: 1,
  483. lastUpdated: 1,
  484. track_changes: 1,
  485. owner_ref: 1,
  486. brandVariationId: 1,
  487. overleaf: 1,
  488. tokens: 1,
  489. tokenAccessReadAndWrite_refs: 1, // used for link sharing analytics
  490. collaberator_refs: 1, // used for link sharing analytics
  491. pendingEditor_refs: 1, // used for link sharing analytics
  492. reviewer_refs: 1,
  493. }),
  494. userIsMemberOfGroupSubscription: sessionUser
  495. ? (async () =>
  496. (
  497. await LimitationsManager.promises.userIsMemberOfGroupSubscription(
  498. sessionUser
  499. )
  500. ).isMember)()
  501. : false,
  502. _flushToTpds:
  503. TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(projectId),
  504. _activate:
  505. InactiveProjectManager.promises.reactivateProjectIfRequired(
  506. projectId
  507. ),
  508. })
  509. const { project, userValues, userIsMemberOfGroupSubscription } = responses
  510. const {
  511. user,
  512. learnedWords,
  513. projectTags,
  514. userHasInstitutionLicence,
  515. subscription,
  516. isTokenMember,
  517. isInvitedMember,
  518. affiliations,
  519. } = userValues
  520. let inEnterpriseCommons = false
  521. for (const affiliation of affiliations || []) {
  522. inEnterpriseCommons =
  523. inEnterpriseCommons || affiliation.institution?.enterpriseCommons
  524. }
  525. const getSplitTestAssignment = async splitTest => {
  526. return await SplitTestHandler.promises.getAssignment(
  527. req,
  528. res,
  529. splitTest
  530. )
  531. }
  532. const splitTestAssignments = {}
  533. await Promise.all(
  534. splitTests.map(async splitTest => {
  535. splitTestAssignments[splitTest] =
  536. await getSplitTestAssignment(splitTest)
  537. })
  538. )
  539. // PDF caching, these tests are archived but we are keeping the frontend code unchanged for now
  540. LocalsHelper.setSplitTestVariant(
  541. res.locals,
  542. 'pdf-caching-cached-url-lookup',
  543. Settings.cachedUrlLookupEnabled ? 'enabled' : 'disabled'
  544. )
  545. LocalsHelper.setSplitTestVariant(
  546. res.locals,
  547. 'pdf-caching-mode',
  548. Settings.pdfCachingMode ? 'enabled' : 'disabled'
  549. )
  550. const brandVariation = project?.brandVariationId
  551. ? await BrandVariationsHandler.promises.getBrandVariationById(
  552. project.brandVariationId
  553. )
  554. : undefined
  555. const anonRequestToken = TokenAccessHandler.getRequestToken(
  556. req,
  557. projectId
  558. )
  559. const imageNames = ProjectHelper.getAllowedImagesForUser(user)
  560. const privilegeLevel =
  561. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  562. userId,
  563. projectId,
  564. anonRequestToken
  565. )
  566. await Modules.promises.hooks.fire('enforceCollaboratorLimit', projectId)
  567. if (isTokenMember) {
  568. // Check explicitly that the user is in read write token refs, while this could be inferred
  569. // from the privilege level, the privilege level of token members might later be restricted
  570. const isReadWriteTokenMember =
  571. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  572. userId,
  573. projectId
  574. )
  575. if (isReadWriteTokenMember) {
  576. // Check for an edge case where a user is both in read write token access refs but also
  577. // an invited read write member. Ensure they are not redirected to the sharing updates page
  578. // We could also delete the token access ref if the user is already a member of the project
  579. const isInvitedReadWriteMember =
  580. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  581. userId,
  582. projectId
  583. )
  584. if (!isInvitedReadWriteMember) {
  585. return res.redirect(`/project/${projectId}/sharing-updates`)
  586. }
  587. }
  588. }
  589. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  590. return res.sendStatus(401)
  591. }
  592. const allowedFreeTrial =
  593. subscription == null ||
  594. isStandaloneAiAddOnPlanCode(subscription.planCode)
  595. let wsUrl = Settings.wsUrl
  596. let metricName = 'load-editor-ws'
  597. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  598. wsUrl = Settings.wsUrlBeta
  599. metricName += '-beta'
  600. } else if (
  601. Settings.wsUrlV2 &&
  602. Settings.wsUrlV2Percentage > 0 &&
  603. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  604. Settings.wsUrlV2Percentage
  605. ) {
  606. wsUrl = Settings.wsUrlV2
  607. metricName += '-v2'
  608. }
  609. if (req.query && req.query.ws === 'fallback') {
  610. // `?ws=fallback` will connect to the bare origin, and ignore
  611. // the custom wsUrl. Hence it must load the client side
  612. // javascript from there too.
  613. // Not resetting it here would possibly load a socket.io v2
  614. // client and connect to a v0 endpoint.
  615. wsUrl = undefined
  616. metricName += '-fallback'
  617. }
  618. metrics.inc(metricName)
  619. // don't need to wait for these to complete
  620. ProjectUpdateHandler.promises
  621. .markAsOpened(projectId)
  622. .catch(err =>
  623. logger.error({ err, projectId }, 'failed to mark project as opened')
  624. )
  625. SplitTestSessionHandler.promises
  626. .sessionMaintenance(req, userId ? user : null)
  627. .catch(err =>
  628. logger.error({ err }, 'failed to update split test info in session')
  629. )
  630. const ownerFeatures = await UserGetter.promises.getUserFeatures(
  631. project.owner_ref
  632. )
  633. if (userId) {
  634. const planLimit = ownerFeatures?.collaborators || 0
  635. const namedEditors = project.collaberator_refs?.length || 0
  636. const pendingEditors = project.pendingEditor_refs?.length || 0
  637. const exceedAtLimit = planLimit > -1 && namedEditors >= planLimit
  638. let mode = 'edit'
  639. if (privilegeLevel === PrivilegeLevels.READ_ONLY) {
  640. mode = 'view'
  641. } else if (
  642. project.track_changes === true ||
  643. project.track_changes?.[userId] === true
  644. ) {
  645. mode = 'review'
  646. }
  647. const projectOpenedSegmentation = {
  648. role: privilegeLevel,
  649. mode,
  650. ownerId: project.owner_ref,
  651. projectId: project._id,
  652. namedEditors,
  653. pendingEditors,
  654. tokenEditors: project.tokenAccessReadAndWrite_refs?.length || 0,
  655. planLimit,
  656. exceedAtLimit,
  657. }
  658. AnalyticsManager.recordEventForUserInBackground(
  659. userId,
  660. 'project-opened',
  661. projectOpenedSegmentation
  662. )
  663. User.updateOne(
  664. { _id: new ObjectId(userId) },
  665. { $set: { lastActive: new Date() } }
  666. )
  667. .exec()
  668. .catch(err =>
  669. logger.error(
  670. { err, userId },
  671. 'failed to update lastActive for user'
  672. )
  673. )
  674. }
  675. const isAdminOrTemplateOwner =
  676. hasAdminAccess(user) || Settings.templates?.user_id === userId
  677. const showTemplatesServerPro =
  678. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  679. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  680. const detachRole = req.params.detachRole
  681. const showSymbolPalette =
  682. !Features.hasFeature('saas') ||
  683. (user.features && user.features.symbolPalette)
  684. const userInNonIndividualSub =
  685. userIsMemberOfGroupSubscription || userHasInstitutionLicence
  686. const userHasPremiumSub =
  687. subscription && !isStandaloneAiAddOnPlanCode(subscription.planCode)
  688. // Persistent upgrade prompts
  689. // in header & in share project modal
  690. const showUpgradePrompt =
  691. Features.hasFeature('saas') &&
  692. userId &&
  693. !userHasPremiumSub &&
  694. !userInNonIndividualSub
  695. let aiFeaturesAllowed = false
  696. if (userId && Features.hasFeature('saas')) {
  697. try {
  698. // exit early if the user couldnt use ai anyways, since permissions checks are expensive
  699. const canUserWriteOrReviewProjectContent =
  700. privilegeLevel === PrivilegeLevels.READ_AND_WRITE ||
  701. privilegeLevel === PrivilegeLevels.OWNER ||
  702. privilegeLevel === PrivilegeLevels.REVIEW
  703. if (canUserWriteOrReviewProjectContent) {
  704. // check permissions for user and project owner, to see if they allow AI on the project
  705. const permissionsResults = await Modules.promises.hooks.fire(
  706. 'projectAllowsCapability',
  707. project,
  708. userId,
  709. ['use-ai']
  710. )
  711. const aiAllowed = permissionsResults.every(
  712. result => result === true
  713. )
  714. aiFeaturesAllowed = aiAllowed
  715. }
  716. } catch (err) {
  717. // still allow users to access project if we cant get their permissions, but disable AI feature
  718. aiFeaturesAllowed = false
  719. }
  720. }
  721. let featureUsage = {}
  722. if (Features.hasFeature('saas')) {
  723. const usagesLeft = await Modules.promises.hooks.fire(
  724. 'remainingFeatureAllocation',
  725. userId
  726. )
  727. usagesLeft?.forEach(usage => {
  728. featureUsage = { ...featureUsage, ...usage }
  729. })
  730. }
  731. await ProjectController._setWritefullTrialState(
  732. user,
  733. userValues,
  734. userId,
  735. aiFeaturesAllowed,
  736. userIsMemberOfGroupSubscription
  737. )
  738. AnalyticsManager.setUserPropertyForUserInBackground(
  739. userId,
  740. 'customer-io-integration',
  741. true
  742. )
  743. const template =
  744. detachRole === 'detached'
  745. ? 'project/ide-react-detached'
  746. : 'project/ide-react'
  747. const capabilities = [...req.capabilitySet]
  748. // make sure the capability is added to CE/SP when the feature is enabled
  749. if (!Features.hasFeature('saas') && Features.hasFeature('chat')) {
  750. capabilities.push('chat')
  751. }
  752. // Note: this is not part of the default capabilities in the backend.
  753. // See services/web/modules/group-settings/app/src/DefaultGroupPolicy.mjs.
  754. // We are only using it on the frontend at the moment.
  755. // Add !Features.hasFeature('saas') to the conditional, as for chat above
  756. // if you define the capability in the backend.
  757. if (Features.hasFeature('link-sharing')) {
  758. capabilities.push('link-sharing')
  759. }
  760. const isOverleafAssistBundleEnabled =
  761. splitTestAssignments['overleaf-assist-bundle']?.variant === 'enabled'
  762. let fullFeatureSet = user?.features
  763. if (!anonymous) {
  764. fullFeatureSet = await UserGetter.promises.getUserFeatures(userId)
  765. }
  766. const hasPaidSubscription = isPaidSubscription(subscription)
  767. const aiFeaturesDisabled = user.aiFeatures?.enabled === false
  768. const addonPrices =
  769. isOverleafAssistBundleEnabled &&
  770. (await ProjectController._getAddonPrices(req, res))
  771. let standardPlanPricing
  772. let recommendedCurrency
  773. if (Features.hasFeature('saas')) {
  774. standardPlanPricing = await ProjectController._getPlanPricing(
  775. req,
  776. res,
  777. 'collaborator'
  778. )
  779. const { currency } =
  780. await SubscriptionController.getRecommendedCurrency(req, res)
  781. recommendedCurrency = currency
  782. }
  783. let planCode = subscription?.planCode
  784. if (!planCode && !userInNonIndividualSub) {
  785. planCode = 'personal'
  786. }
  787. const planDetails = Settings.plans.find(p => p.planCode === planCode)
  788. const shouldLoadHotjar =
  789. splitTestAssignments['compile-timeout-target-plans']?.variant ===
  790. 'enabled' &&
  791. !userHasPremiumSub &&
  792. !userInNonIndividualSub
  793. const userSettings = await UserSettingsHelper.buildUserSettings(
  794. req,
  795. res,
  796. user
  797. )
  798. res.render(template, {
  799. title: project.name,
  800. priority_title: true,
  801. bodyClasses: ['editor'],
  802. project_id: project._id,
  803. projectName: project.name,
  804. canUseClsiCache:
  805. Features.hasFeature('saas') &&
  806. ownerFeatures?.compileGroup === 'priority',
  807. user: {
  808. id: userId,
  809. email: user.email,
  810. first_name: user.first_name,
  811. last_name: user.last_name,
  812. referal_id: user.referal_id,
  813. signUpDate: user.signUpDate,
  814. allowedFreeTrial,
  815. hasPaidSubscription,
  816. featureSwitches: user.featureSwitches,
  817. features: fullFeatureSet,
  818. featureUsage,
  819. refProviders: _.mapValues(user.refProviders, Boolean),
  820. writefull: {
  821. autoCreatedAccount: Boolean(user.writefull?.autoCreatedAccount),
  822. },
  823. alphaProgram: user.alphaProgram,
  824. betaProgram: user.betaProgram,
  825. labsProgram: user.labsProgram,
  826. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  827. isAdmin: hasAdminAccess(user),
  828. planCode,
  829. planName: planDetails?.name,
  830. isAnnualPlan: planCode && planDetails?.annual,
  831. isMemberOfGroupSubscription: userIsMemberOfGroupSubscription,
  832. hasInstitutionLicence: userHasInstitutionLicence,
  833. },
  834. userSettings,
  835. labsExperiments: user.labsExperiments ?? [],
  836. privilegeLevel,
  837. anonymous,
  838. isTokenMember,
  839. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  840. userId,
  841. privilegeLevel,
  842. isTokenMember,
  843. isInvitedMember
  844. ),
  845. capabilities,
  846. roMirrorOnClientNoLocalStorage:
  847. Settings.adminOnlyLogin || project.name.startsWith('Debug: '),
  848. languages: Settings.languages,
  849. learnedWords,
  850. editorThemes: THEME_LIST,
  851. legacyEditorThemes: LEGACY_THEME_LIST,
  852. maxDocLength: Settings.max_doc_length,
  853. maxReconnectGracefullyIntervalMs:
  854. Settings.maxReconnectGracefullyIntervalMs,
  855. brandVariation,
  856. imageNames,
  857. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  858. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  859. wsUrl,
  860. showSupport: Features.hasFeature('support'),
  861. showTemplatesServerPro,
  862. debugPdfDetach,
  863. showSymbolPalette,
  864. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  865. userRestrictions: Array.from(req.userRestrictions || []),
  866. showAiFeatures: aiFeaturesAllowed && !aiFeaturesDisabled,
  867. onAiFreeTrial:
  868. user.features?.aiUsageQuota === Settings.aiFeatures?.freeTrialQuota,
  869. detachRole,
  870. metadata: { viewport: false },
  871. showUpgradePrompt,
  872. fixedSizeDocument: true,
  873. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  874. otMigrationStage: project.overleaf?.history?.otMigrationStage ?? 0,
  875. projectTags,
  876. isSaas: Features.hasFeature('saas'),
  877. shouldLoadHotjar,
  878. isOverleafAssistBundleEnabled,
  879. customerIoEnabled: true,
  880. addonPrices,
  881. compileSettings: {
  882. compileTimeout: ownerFeatures?.compileTimeout,
  883. },
  884. standardPlanPricing,
  885. recommendedCurrency,
  886. })
  887. timer.done()
  888. } catch (err) {
  889. OError.tag(err, 'error getting details for project page')
  890. return next(err)
  891. }
  892. },
  893. async _getPlanPricing(req, res, plan = 'collaborator') {
  894. const locale = req.i18n.language
  895. const { currency } = await SubscriptionController.getRecommendedCurrency(
  896. req,
  897. res
  898. )
  899. const pricingForCurrency = Settings.localizedPlanPricing[currency]
  900. if (!pricingForCurrency) {
  901. return null
  902. }
  903. const planPricing = pricingForCurrency[plan]
  904. if (!planPricing) {
  905. return null
  906. }
  907. return {
  908. monthly: formatCurrency(planPricing.monthly, currency, locale, true),
  909. annual: formatCurrency(planPricing.annual, currency, locale, true),
  910. monthlyTimesTwelve: formatCurrency(
  911. planPricing.monthlyTimesTwelve,
  912. currency,
  913. locale,
  914. true
  915. ),
  916. }
  917. },
  918. async _getAddonPrices(req, res, addonPlans = ['assistant']) {
  919. const plansData = {}
  920. const locale = req.i18n.language
  921. const { currency } = await SubscriptionController.getRecommendedCurrency(
  922. req,
  923. res
  924. )
  925. addonPlans.forEach(plan => {
  926. const annualPrice = Settings.localizedAddOnsPricing[currency][plan].annual
  927. const monthlyPrice =
  928. Settings.localizedAddOnsPricing[currency][plan].monthly
  929. const annualDividedByTwelve =
  930. Settings.localizedAddOnsPricing[currency][plan].annualDividedByTwelve
  931. plansData[plan] = {
  932. annual: formatCurrency(annualPrice, currency, locale, true),
  933. annualDividedByTwelve: formatCurrency(
  934. annualDividedByTwelve,
  935. currency,
  936. locale,
  937. true
  938. ),
  939. monthly: formatCurrency(monthlyPrice, currency, locale, true),
  940. }
  941. })
  942. return plansData
  943. },
  944. async _refreshFeatures(req, user) {
  945. // If the feature refresh has failed in this session, don't retry
  946. // it - require the user to log in again.
  947. if (req.session.feature_refresh_failed) {
  948. metrics.inc('features-refresh', 1, {
  949. path: 'load-editor',
  950. status: 'skipped',
  951. })
  952. return user
  953. }
  954. // If the refresh takes too long then return the current
  955. // features. Note that the user.features property may still be
  956. // updated in the background after the promise is resolved.
  957. const abortController = new AbortController()
  958. const refreshTimeoutHandler = async () => {
  959. await setTimeout(5000, { signal: abortController.signal })
  960. req.session.feature_refresh_failed = {
  961. reason: 'timeout',
  962. at: new Date(),
  963. }
  964. metrics.inc('features-refresh', 1, {
  965. path: 'load-editor',
  966. status: 'timeout',
  967. })
  968. return user
  969. }
  970. // try to refresh user features now
  971. const timer = new metrics.Timer('features-refresh-on-load-editor')
  972. return Promise.race([
  973. refreshTimeoutHandler(),
  974. (async () => {
  975. try {
  976. user.features = await FeaturesUpdater.promises.refreshFeatures(
  977. user._id,
  978. 'load-editor'
  979. )
  980. metrics.inc('features-refresh', 1, {
  981. path: 'load-editor',
  982. status: 'success',
  983. })
  984. } catch (err) {
  985. // keep a record to prevent unneceary retries and leave
  986. // the original features unmodified if the refresh failed
  987. req.session.feature_refresh_failed = {
  988. reason: 'error',
  989. at: new Date(),
  990. }
  991. metrics.inc('features-refresh', 1, {
  992. path: 'load-editor',
  993. status: 'error',
  994. })
  995. }
  996. abortController.abort()
  997. timer.done()
  998. return user
  999. })(),
  1000. ])
  1001. },
  1002. _buildProjectList(allProjects, userId) {
  1003. let project
  1004. const {
  1005. owned,
  1006. review,
  1007. readAndWrite,
  1008. readOnly,
  1009. tokenReadAndWrite,
  1010. tokenReadOnly,
  1011. } = allProjects
  1012. const projects = []
  1013. for (project of owned) {
  1014. projects.push(
  1015. ProjectController._buildProjectViewModel(
  1016. project,
  1017. 'owner',
  1018. Sources.OWNER,
  1019. userId
  1020. )
  1021. )
  1022. }
  1023. // Invite-access
  1024. for (project of readAndWrite) {
  1025. projects.push(
  1026. ProjectController._buildProjectViewModel(
  1027. project,
  1028. 'readWrite',
  1029. Sources.INVITE,
  1030. userId
  1031. )
  1032. )
  1033. }
  1034. for (project of review) {
  1035. projects.push(
  1036. ProjectController._buildProjectViewModel(
  1037. project,
  1038. 'review',
  1039. Sources.INVITE,
  1040. userId
  1041. )
  1042. )
  1043. }
  1044. for (project of readOnly) {
  1045. projects.push(
  1046. ProjectController._buildProjectViewModel(
  1047. project,
  1048. 'readOnly',
  1049. Sources.INVITE,
  1050. userId
  1051. )
  1052. )
  1053. }
  1054. // Token-access
  1055. // Only add these projects if they're not already present, this gives us cascading access
  1056. // from 'owner' => 'token-read-only'
  1057. for (project of tokenReadAndWrite) {
  1058. if (
  1059. projects.filter(p => p.id.toString() === project._id.toString())
  1060. .length === 0
  1061. ) {
  1062. projects.push(
  1063. ProjectController._buildProjectViewModel(
  1064. project,
  1065. 'readAndWrite',
  1066. Sources.TOKEN,
  1067. userId
  1068. )
  1069. )
  1070. }
  1071. }
  1072. for (project of tokenReadOnly) {
  1073. if (
  1074. projects.filter(p => p.id.toString() === project._id.toString())
  1075. .length === 0
  1076. ) {
  1077. projects.push(
  1078. ProjectController._buildProjectViewModel(
  1079. project,
  1080. 'readOnly',
  1081. Sources.TOKEN,
  1082. userId
  1083. )
  1084. )
  1085. }
  1086. }
  1087. return projects
  1088. },
  1089. _buildProjectViewModel(project, accessLevel, source, userId) {
  1090. const archived = ProjectHelper.isArchived(project, userId)
  1091. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1092. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1093. const model = {
  1094. id: project._id,
  1095. name: project.name,
  1096. lastUpdated: project.lastUpdated,
  1097. lastUpdatedBy: project.lastUpdatedBy,
  1098. publicAccessLevel: project.publicAccesLevel,
  1099. accessLevel,
  1100. source,
  1101. archived,
  1102. trashed,
  1103. owner_ref: project.owner_ref,
  1104. isV1Project: false,
  1105. }
  1106. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1107. model.owner_ref = null
  1108. model.lastUpdatedBy = null
  1109. }
  1110. return model
  1111. },
  1112. _buildPortalTemplatesList(affiliations) {
  1113. if (affiliations == null) {
  1114. affiliations = []
  1115. }
  1116. const portalTemplates = []
  1117. for (const aff of affiliations) {
  1118. if (
  1119. aff.portal &&
  1120. aff.portal.slug &&
  1121. aff.portal.templates_count &&
  1122. aff.portal.templates_count > 0
  1123. ) {
  1124. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1125. portalTemplates.push({
  1126. name: aff.institution.name,
  1127. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1128. })
  1129. }
  1130. }
  1131. return portalTemplates
  1132. },
  1133. async _setWritefullTrialState(
  1134. user,
  1135. userValues,
  1136. userId,
  1137. aiFeaturesAllowed,
  1138. userIsMemberOfGroupSubscription
  1139. ) {
  1140. if (!aiFeaturesAllowed) {
  1141. return
  1142. }
  1143. const affiliations = userValues.affiliations
  1144. const affiliateLookupFailed = affiliations === false
  1145. // if affiliations is specifically false instead of empty, we know the affiliate lookup failed, and should defer to blocking auto-loading
  1146. const inEnterpriseCommons =
  1147. affiliateLookupFailed ||
  1148. affiliations.some(
  1149. affiliation => affiliation.institution?.enterpriseCommons
  1150. )
  1151. const shouldPushWritefull =
  1152. user.writefull?.initialized === false && !userIsMemberOfGroupSubscription
  1153. // we dont have legal approval to push enterprise commons into WF auto-account-create, but we are able to auto-load it into the toolbar
  1154. const shouldAutoCreateAccount = shouldPushWritefull && !inEnterpriseCommons
  1155. const shouldAutoLoad = shouldPushWritefull && inEnterpriseCommons
  1156. if (shouldAutoCreateAccount) {
  1157. await UserUpdater.promises.updateUser(userId, {
  1158. $set: {
  1159. writefull: { autoCreatedAccount: true, initialized: true },
  1160. },
  1161. })
  1162. user.writefull.autoCreatedAccount = true
  1163. } else if (shouldAutoLoad) {
  1164. await UserUpdater.promises.updateUser(userId, {
  1165. $set: {
  1166. writefull: { autoCreatedAccount: false, initialized: true },
  1167. },
  1168. })
  1169. user.writefull.autoCreatedAccount = false
  1170. }
  1171. },
  1172. }
  1173. const defaultSettingsForAnonymousUser = userId => ({
  1174. id: userId,
  1175. ace: {
  1176. mode: 'none',
  1177. theme: 'textmate',
  1178. fontSize: '12',
  1179. autoComplete: true,
  1180. spellCheckLanguage: '',
  1181. pdfViewer: '',
  1182. syntaxValidation: true,
  1183. },
  1184. subscription: {
  1185. freeTrial: {
  1186. allowed: true,
  1187. },
  1188. },
  1189. featureSwitches: {
  1190. github: false,
  1191. },
  1192. alphaProgram: false,
  1193. betaProgram: false,
  1194. writefull: {
  1195. initialized: true,
  1196. },
  1197. aiFeatures: {
  1198. enabled: false,
  1199. },
  1200. })
  1201. const defaultUserValues = () => ({
  1202. user: defaultSettingsForAnonymousUser(null),
  1203. learnedWords: [],
  1204. projectTags: [],
  1205. userHasInstitutionLicence: false,
  1206. affiliations: [],
  1207. subscription: undefined,
  1208. isTokenMember: false,
  1209. isInvitedMember: false,
  1210. })
  1211. const THEME_LIST = [
  1212. { name: 'cobalt', dark: true },
  1213. { name: 'dracula', dark: true },
  1214. { name: 'eclipse', dark: false },
  1215. { name: 'monokai', dark: true },
  1216. { name: 'overleaf', dark: false },
  1217. { name: 'overleaf_dark', dark: true },
  1218. { name: 'textmate', dark: false },
  1219. ]
  1220. const LEGACY_THEME_LIST = [
  1221. { name: 'ambiance', dark: true },
  1222. { name: 'chaos', dark: true },
  1223. { name: 'chrome', dark: false },
  1224. { name: 'clouds', dark: false },
  1225. { name: 'clouds_midnight', dark: true },
  1226. { name: 'crimson_editor', dark: false },
  1227. { name: 'dawn', dark: false },
  1228. { name: 'dreamweaver', dark: false },
  1229. { name: 'github', dark: false },
  1230. { name: 'gob', dark: true },
  1231. { name: 'gruvbox', dark: true },
  1232. { name: 'idle_fingers', dark: true },
  1233. { name: 'iplastic', dark: false },
  1234. { name: 'katzenmilch', dark: false },
  1235. { name: 'kr_theme', dark: true },
  1236. { name: 'kuroir', dark: false },
  1237. { name: 'merbivore', dark: true },
  1238. { name: 'merbivore_soft', dark: true },
  1239. { name: 'mono_industrial', dark: true },
  1240. { name: 'nord_dark', dark: true },
  1241. { name: 'pastel_on_dark', dark: true },
  1242. { name: 'solarized_dark', dark: true },
  1243. { name: 'solarized_light', dark: false },
  1244. { name: 'sqlserver', dark: false },
  1245. { name: 'terminal', dark: true },
  1246. { name: 'tomorrow', dark: false },
  1247. { name: 'tomorrow_night', dark: true },
  1248. { name: 'tomorrow_night_blue', dark: true },
  1249. { name: 'tomorrow_night_bright', dark: true },
  1250. { name: 'tomorrow_night_eighties', dark: true },
  1251. { name: 'twilight', dark: true },
  1252. { name: 'vibrant_ink', dark: true },
  1253. { name: 'xcode', dark: false },
  1254. ]
  1255. const ProjectController = {
  1256. archiveProject: expressify(_ProjectController.archiveProject),
  1257. cloneProject: expressify(_ProjectController.cloneProject),
  1258. deleteProject: expressify(_ProjectController.deleteProject),
  1259. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  1260. expireDeletedProjectsAfterDuration: expressify(
  1261. _ProjectController.expireDeletedProjectsAfterDuration
  1262. ),
  1263. loadEditor: expressify(_ProjectController.loadEditor),
  1264. newProject: expressify(_ProjectController.newProject),
  1265. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  1266. renameProject: expressify(_ProjectController.renameProject),
  1267. restoreProject: expressify(_ProjectController.restoreProject),
  1268. trashProject: expressify(_ProjectController.trashProject),
  1269. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  1270. untrashProject: expressify(_ProjectController.untrashProject),
  1271. updateProjectAdminSettings: expressify(
  1272. _ProjectController.updateProjectAdminSettings
  1273. ),
  1274. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  1275. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  1276. _buildProjectList: _ProjectController._buildProjectList,
  1277. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  1278. _injectProjectUsers: _ProjectController._injectProjectUsers,
  1279. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  1280. _refreshFeatures: _ProjectController._refreshFeatures,
  1281. _getPlanPricing: _ProjectController._getPlanPricing,
  1282. _getAddonPrices: _ProjectController._getAddonPrices,
  1283. _setWritefullTrialState: _ProjectController._setWritefullTrialState,
  1284. }
  1285. export default ProjectController