ProjectController.mjs 46 KB

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