ProjectController.mjs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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-figure-generator',
  427. 'wf-citations-checker',
  428. 'wf-citations-checker-on-selection',
  429. 'writefull-asymetric-queue-size-per-model',
  430. 'writefull-encourage-prompt-for-paraphrase',
  431. 'editor-context-menu',
  432. 'email-notifications',
  433. 'wf-enable-freemium-super-complete',
  434. 'wf-enable-super-complete-promotion',
  435. 'wf-rebrand',
  436. 'plans-2026-phase-1',
  437. 'testing-ai-usage',
  438. 'wf-fake-non-english-suggestions',
  439. 'editor-tabs',
  440. 'overleaf-code',
  441. 'export-docx',
  442. 'sharing-updates',
  443. 'export-markdown',
  444. 'export-html',
  445. 'command-palette',
  446. 'overleaf-library',
  447. 'compile-timeout-cta',
  448. 'editor-upgrade-button-relocation',
  449. 'markdown-visual',
  450. ].filter(Boolean)
  451. const getUserValues = async userId =>
  452. pProps(
  453. _.mapValues({
  454. user: (async () => {
  455. const user = await User.findById(
  456. userId,
  457. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsExperiments completedTutorials writefull aiFeatures'
  458. ).exec()
  459. // Handle case of deleted user
  460. if (!user) {
  461. UserController.logout(req, res, next)
  462. return
  463. }
  464. logger.debug({ projectId, userId }, 'got user')
  465. return FeaturesUpdater.featuresEpochIsCurrent(user)
  466. ? user
  467. : await ProjectController._refreshFeatures(req, user)
  468. })(),
  469. learnedWords: SpellingHandler.promises.getUserDictionary(userId),
  470. projectTags: TagsHandler.promises.getTagsForProject(
  471. userId,
  472. projectId
  473. ),
  474. userHasInstitutionLicence: InstitutionsFeatures.promises
  475. .hasLicence(userId)
  476. .catch(err => {
  477. logger.error({ err, userId }, 'failed to get institution licence')
  478. return false
  479. }),
  480. affiliations: InstitutionsGetter.promises
  481. .getCurrentAffiliations(userId)
  482. .catch(err => {
  483. logger.error(
  484. { err, userId },
  485. 'failed to get current affiliations'
  486. )
  487. return false
  488. }),
  489. subscription:
  490. SubscriptionLocator.promises.getUsersSubscription(userId),
  491. isTokenMember: CollaboratorsGetter.promises.userIsTokenMember(
  492. userId,
  493. projectId
  494. ),
  495. isInvitedMember:
  496. CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  497. userId,
  498. projectId
  499. ),
  500. })
  501. )
  502. try {
  503. const responses = await pProps({
  504. userValues: userId ? getUserValues(userId) : defaultUserValues(),
  505. project: ProjectGetter.promises.getProject(projectId, {
  506. _id: 1,
  507. name: 1,
  508. active: 1,
  509. deferredTpdsFlushCounter: 1,
  510. lastUpdated: 1,
  511. track_changes: 1,
  512. owner_ref: 1,
  513. brandVariationId: 1,
  514. overleaf: 1,
  515. tokens: 1,
  516. }),
  517. userIsMemberOfGroupSubscription: sessionUser
  518. ? (async () =>
  519. (
  520. await LimitationsManager.promises.userIsMemberOfGroupSubscription(
  521. sessionUser
  522. )
  523. ).isMember)()
  524. : false,
  525. })
  526. const { project, userValues, userIsMemberOfGroupSubscription } = responses
  527. await Promise.all([
  528. InactiveProjectManager.promises.reactivateProjectIfRequired(project),
  529. TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(project),
  530. ])
  531. const {
  532. user,
  533. learnedWords,
  534. projectTags,
  535. userHasInstitutionLicence,
  536. subscription,
  537. isTokenMember,
  538. isInvitedMember,
  539. affiliations,
  540. } = userValues
  541. let inEnterpriseCommons = false
  542. for (const affiliation of affiliations || []) {
  543. inEnterpriseCommons =
  544. inEnterpriseCommons || affiliation.institution?.enterpriseCommons
  545. }
  546. const getSplitTestAssignment = async splitTest => {
  547. return await SplitTestHandler.promises.getAssignment(
  548. req,
  549. res,
  550. splitTest
  551. )
  552. }
  553. const splitTestAssignments = {}
  554. await Promise.all(
  555. splitTests.map(async splitTest => {
  556. splitTestAssignments[splitTest] =
  557. await getSplitTestAssignment(splitTest)
  558. })
  559. )
  560. // PDF caching, these tests are archived but we are keeping the frontend code unchanged for now
  561. LocalsHelper.setSplitTestVariant(
  562. res.locals,
  563. 'pdf-caching-cached-url-lookup',
  564. Settings.cachedUrlLookupEnabled ? 'enabled' : 'disabled'
  565. )
  566. LocalsHelper.setSplitTestVariant(
  567. res.locals,
  568. 'pdf-caching-mode',
  569. Settings.pdfCachingMode ? 'enabled' : 'disabled'
  570. )
  571. const brandVariation = project?.brandVariationId
  572. ? await BrandVariationsHandler.promises.getBrandVariationById(
  573. project.brandVariationId
  574. )
  575. : undefined
  576. const anonRequestToken = TokenAccessHandler.getRequestToken(
  577. req,
  578. projectId
  579. )
  580. const imageNames = await ProjectHelper.getAllowedImagesForUser(user)
  581. const privilegeLevel =
  582. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  583. userId,
  584. projectId,
  585. anonRequestToken
  586. )
  587. await Modules.promises.hooks.fire('enforceCollaboratorLimit', projectId)
  588. if (isTokenMember) {
  589. // Check explicitly that the user is in read write token refs, while this could be inferred
  590. // from the privilege level, the privilege level of token members might later be restricted
  591. const isReadWriteTokenMember =
  592. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  593. userId,
  594. projectId
  595. )
  596. if (isReadWriteTokenMember) {
  597. // Check for an edge case where a user is both in read write token access refs but also
  598. // an invited read write member. Ensure they are not redirected to the sharing updates page
  599. // We could also delete the token access ref if the user is already a member of the project
  600. const isInvitedReadWriteMember =
  601. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  602. userId,
  603. projectId
  604. )
  605. if (!isInvitedReadWriteMember) {
  606. return res.redirect(`/project/${projectId}/sharing-updates`)
  607. }
  608. }
  609. }
  610. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  611. return res.sendStatus(401)
  612. }
  613. const allowedFreeTrial =
  614. subscription == null ||
  615. isStandaloneAiAddOnPlanCode(subscription.planCode)
  616. let wsUrl = Settings.wsUrl
  617. let metricName = 'load-editor-ws'
  618. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  619. wsUrl = Settings.wsUrlBeta
  620. metricName += '-beta'
  621. } else if (
  622. Settings.wsUrlV2 &&
  623. Settings.wsUrlV2Percentage > 0 &&
  624. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  625. Settings.wsUrlV2Percentage
  626. ) {
  627. wsUrl = Settings.wsUrlV2
  628. metricName += '-v2'
  629. }
  630. if (req.query && req.query.ws === 'fallback') {
  631. // `?ws=fallback` will connect to the bare origin, and ignore
  632. // the custom wsUrl. Hence it must load the client side
  633. // javascript from there too.
  634. // Not resetting it here would possibly load a socket.io v2
  635. // client and connect to a v0 endpoint.
  636. wsUrl = undefined
  637. metricName += '-fallback'
  638. }
  639. metrics.inc(metricName)
  640. // don't need to wait for these to complete
  641. ProjectUpdateHandler.promises
  642. .markAsOpened(projectId)
  643. .catch(err =>
  644. logger.error({ err, projectId }, 'failed to mark project as opened')
  645. )
  646. SplitTestSessionHandler.promises
  647. .sessionMaintenance(req, userId ? user : null)
  648. .catch(err =>
  649. logger.error({ err }, 'failed to update split test info in session')
  650. )
  651. const ownerFeatures = await UserGetter.promises.getUserFeatures(
  652. project.owner_ref
  653. )
  654. if (userId) {
  655. const projectAccess =
  656. await CollaboratorsGetter.promises.getProjectAccess(projectId)
  657. const planLimit = ownerFeatures?.collaborators || 0
  658. const { namedEditors, pendingEditors, tokenEditors } =
  659. projectAccess.getStats()
  660. const exceedAtLimit = planLimit > -1 && namedEditors >= planLimit
  661. let mode = 'edit'
  662. if (privilegeLevel === PrivilegeLevels.READ_ONLY) {
  663. mode = 'view'
  664. } else if (
  665. project.track_changes === true ||
  666. project.track_changes?.[userId] === true
  667. ) {
  668. mode = 'review'
  669. }
  670. const projectOpenedSegmentation = {
  671. role: privilegeLevel,
  672. mode,
  673. ownerId: project.owner_ref,
  674. projectId: project._id,
  675. namedEditors,
  676. pendingEditors,
  677. tokenEditors,
  678. planLimit,
  679. exceedAtLimit,
  680. }
  681. AnalyticsManager.recordEventForUserInBackground(
  682. userId,
  683. 'project-opened',
  684. projectOpenedSegmentation
  685. )
  686. User.updateOne(
  687. { _id: new ObjectId(userId) },
  688. { $set: { lastActive: new Date() } }
  689. )
  690. .exec()
  691. .catch(err =>
  692. logger.error(
  693. { err, userId },
  694. 'failed to update lastActive for user'
  695. )
  696. )
  697. }
  698. const isAdminOrTemplateOwner =
  699. hasAdminAccess(user) || Settings.templates?.user_id === userId
  700. const showTemplatesServerPro =
  701. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  702. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  703. const detachRole = req.params.detachRole
  704. const showSymbolPalette =
  705. !Features.hasFeature('saas') ||
  706. (user.features && user.features.symbolPalette)
  707. const userInNonIndividualSub =
  708. userIsMemberOfGroupSubscription || userHasInstitutionLicence
  709. const userHasPremiumSub =
  710. subscription && !isStandaloneAiAddOnPlanCode(subscription.planCode)
  711. // Persistent upgrade prompts
  712. // in header & in share project modal
  713. const showUpgradePrompt =
  714. Features.hasFeature('saas') &&
  715. userId &&
  716. !userHasPremiumSub &&
  717. !userInNonIndividualSub
  718. let aiFeaturesAllowed = false
  719. if (userId && Features.hasFeature('saas')) {
  720. try {
  721. // exit early if the user couldnt use ai anyways, since permissions checks are expensive
  722. const canUserWriteOrReviewProjectContent =
  723. privilegeLevel === PrivilegeLevels.READ_AND_WRITE ||
  724. privilegeLevel === PrivilegeLevels.OWNER ||
  725. privilegeLevel === PrivilegeLevels.REVIEW
  726. if (canUserWriteOrReviewProjectContent) {
  727. // check permissions for user and project owner, to see if they allow AI on the project
  728. const permissionsResults = await Modules.promises.hooks.fire(
  729. 'projectAllowsCapability',
  730. project,
  731. userId,
  732. ['use-ai']
  733. )
  734. const aiAllowed = permissionsResults.every(
  735. result => result === true
  736. )
  737. aiFeaturesAllowed = aiAllowed
  738. }
  739. } catch (err) {
  740. // still allow users to access project if we cant get their permissions, but disable AI feature
  741. aiFeaturesAllowed = false
  742. }
  743. }
  744. let featureUsage = {}
  745. if (Features.hasFeature('saas') && !anonymous) {
  746. featureUsage = {
  747. ...(await AiFeatureUsageRateLimiter.getRemainingFeatureUses(userId)),
  748. ...(await WorkbenchRateLimiter.getRemainingTokens(userId)),
  749. }
  750. }
  751. await ProjectController._setWritefullTrialState(
  752. user,
  753. userValues,
  754. userId,
  755. aiFeaturesAllowed,
  756. userIsMemberOfGroupSubscription
  757. )
  758. AnalyticsManager.setUserPropertyForUserInBackground(
  759. userId,
  760. 'customer-io-integration',
  761. true
  762. )
  763. const template =
  764. detachRole === 'detached'
  765. ? 'project/ide-react-detached'
  766. : 'project/ide-react'
  767. const capabilities = [...req.capabilitySet]
  768. // make sure the capability is added to CE/SP when the feature is enabled
  769. if (!Features.hasFeature('saas') && Features.hasFeature('chat')) {
  770. capabilities.push('chat')
  771. }
  772. // Note: this is not part of the default capabilities in the backend.
  773. // See services/web/modules/group-settings/app/src/DefaultGroupPolicy.mjs.
  774. // We are only using it on the frontend at the moment.
  775. // Add !Features.hasFeature('saas') to the conditional, as for chat above
  776. // if you define the capability in the backend.
  777. if (Features.hasFeature('link-sharing')) {
  778. capabilities.push('link-sharing')
  779. }
  780. let fullFeatureSet = user?.features
  781. if (!anonymous) {
  782. fullFeatureSet = await UserGetter.promises.getUserFeatures(userId)
  783. }
  784. const hasPaidSubscription = isPaidSubscription(subscription)
  785. const aiFeaturesDisabled = user.aiFeatures?.enabled === false
  786. const showAiFeatures = aiFeaturesAllowed && !aiFeaturesDisabled
  787. // only add-on is ai based, so we only need its pricing info if ai features are usable
  788. const addonPrices =
  789. showAiFeatures && (await ProjectController._getAddonPrices(req, res))
  790. let standardPlanPricing
  791. let recommendedCurrency
  792. if (Features.hasFeature('saas')) {
  793. standardPlanPricing = await ProjectController._getPlanPricing(
  794. req,
  795. res,
  796. 'collaborator'
  797. )
  798. const { currency } =
  799. await SubscriptionController.getRecommendedCurrency(req, res)
  800. recommendedCurrency = currency
  801. }
  802. let planCode = subscription?.planCode
  803. if (!planCode && !userInNonIndividualSub) {
  804. planCode = 'personal'
  805. }
  806. const planDetails = Settings.plans.find(p => p.planCode === planCode)
  807. const shouldLoadHotjar =
  808. splitTestAssignments['compile-timeout-target-plans']?.variant ===
  809. 'enabled' &&
  810. !userHasPremiumSub &&
  811. !userInNonIndividualSub
  812. const userSettings = await UserSettingsHelper.buildUserSettings(
  813. req,
  814. res,
  815. user
  816. )
  817. const initialLoadingScreenTheme = getInitialLoadingScreenTheme(
  818. userSettings?.overallTheme
  819. )
  820. if (user.labsProgram) {
  821. await Modules.promises.hooks.fire('assignLabsSplitTests', req, res)
  822. }
  823. res.render(template, {
  824. title: project.name,
  825. priority_title: true,
  826. bodyClasses: ['editor'],
  827. project_id: project._id,
  828. projectName: project.name,
  829. canUseClsiCache:
  830. Features.hasFeature('saas') &&
  831. ownerFeatures?.compileGroup === 'priority',
  832. user: {
  833. id: userId,
  834. email: user.email,
  835. first_name: user.first_name,
  836. last_name: user.last_name,
  837. referal_id: user.referal_id,
  838. signUpDate: user.signUpDate,
  839. allowedFreeTrial,
  840. hasPaidSubscription,
  841. featureSwitches: user.featureSwitches,
  842. features: fullFeatureSet,
  843. featureUsage,
  844. refProviders: _.mapValues(user.refProviders, Boolean),
  845. writefull: {
  846. autoCreatedAccount: Boolean(user.writefull?.autoCreatedAccount),
  847. },
  848. alphaProgram: user.alphaProgram,
  849. betaProgram: user.betaProgram,
  850. labsProgram: user.labsProgram,
  851. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  852. isAdmin: hasAdminAccess(user),
  853. planCode,
  854. planName: planDetails?.name,
  855. isAnnualPlan: planCode && planDetails?.annual,
  856. isProfessionalGroupPlan: Boolean(
  857. subscription && isProfessionalGroupPlan(subscription)
  858. ),
  859. isMemberOfGroupSubscription: userIsMemberOfGroupSubscription,
  860. hasInstitutionLicence: userHasInstitutionLicence,
  861. },
  862. initialLoadingScreenTheme,
  863. userSettings,
  864. privilegeLevel,
  865. anonymous,
  866. isTokenMember,
  867. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  868. userId,
  869. privilegeLevel,
  870. isTokenMember,
  871. isInvitedMember
  872. ),
  873. capabilities,
  874. roMirrorOnClientNoLocalStorage:
  875. Settings.adminOnlyLogin || project.name.startsWith('Debug: '),
  876. defaultLatexCompiler: Settings.defaultLatexCompiler,
  877. languages: Settings.languages,
  878. learnedWords,
  879. editorThemes: THEME_LIST,
  880. legacyEditorThemes: LEGACY_THEME_LIST,
  881. maxDocLength: Settings.max_doc_length,
  882. maxReconnectGracefullyIntervalMs:
  883. Settings.maxReconnectGracefullyIntervalMs,
  884. brandVariation,
  885. imageNames,
  886. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  887. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  888. wsUrl,
  889. showSupport: Features.hasFeature('support'),
  890. showTemplatesServerPro,
  891. debugPdfDetach,
  892. showSymbolPalette,
  893. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  894. userRestrictions: Array.from(req.userRestrictions || []),
  895. showAiFeatures,
  896. // default to free tier if they dont have a quota
  897. hasAiFreeTier:
  898. fullFeatureSet?.aiUsageQuota === Settings.aiFeatures?.freeQuota ||
  899. !fullFeatureSet?.aiUsageQuota,
  900. hasUnlimitedAi:
  901. fullFeatureSet?.aiUsageQuota === Settings.aiFeatures?.unlimitedQuota,
  902. detachRole,
  903. metadata: { viewport: false },
  904. showUpgradePrompt,
  905. fixedSizeDocument: true,
  906. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  907. otMigrationStage: project.overleaf?.history?.otMigrationStage ?? 0,
  908. projectTags,
  909. isSaas: Features.hasFeature('saas'),
  910. shouldLoadHotjar,
  911. customerIoEnabled: true,
  912. addonPrices,
  913. compileSettings: {
  914. compileTimeout: ownerFeatures?.compileTimeout,
  915. },
  916. standardPlanPricing,
  917. recommendedCurrency,
  918. })
  919. timer.done()
  920. } catch (err) {
  921. OError.tag(err, 'error getting details for project page')
  922. return next(err)
  923. }
  924. },
  925. async _getPlanPricing(req, res, plan = 'collaborator') {
  926. const locale = req.i18n.language
  927. const { currency } = await SubscriptionController.getRecommendedCurrency(
  928. req,
  929. res
  930. )
  931. const pricingForCurrency = Settings.localizedPlanPricing[currency]
  932. if (!pricingForCurrency) {
  933. return null
  934. }
  935. const planPricing = pricingForCurrency[plan]
  936. if (!planPricing) {
  937. return null
  938. }
  939. return {
  940. monthly: formatCurrency(planPricing.monthly, currency, locale, true),
  941. annual: formatCurrency(planPricing.annual, currency, locale, true),
  942. monthlyTimesTwelve: formatCurrency(
  943. planPricing.monthlyTimesTwelve,
  944. currency,
  945. locale,
  946. true
  947. ),
  948. }
  949. },
  950. // todo: quota clean-up: these can be removed potentially?
  951. async _getAddonPrices(req, res, addonPlans = ['assistant']) {
  952. const plansData = {}
  953. const locale = req.i18n.language
  954. const { currency } = await SubscriptionController.getRecommendedCurrency(
  955. req,
  956. res
  957. )
  958. addonPlans.forEach(plan => {
  959. const annualPrice = Settings.localizedAddOnsPricing[currency][plan].annual
  960. const monthlyPrice =
  961. Settings.localizedAddOnsPricing[currency][plan].monthly
  962. const annualDividedByTwelve =
  963. Settings.localizedAddOnsPricing[currency][plan].annualDividedByTwelve
  964. plansData[plan] = {
  965. annual: formatCurrency(annualPrice, currency, locale, true),
  966. annualDividedByTwelve: formatCurrency(
  967. annualDividedByTwelve,
  968. currency,
  969. locale,
  970. true
  971. ),
  972. monthly: formatCurrency(monthlyPrice, currency, locale, true),
  973. }
  974. })
  975. return plansData
  976. },
  977. async _refreshFeatures(req, user) {
  978. // If the feature refresh has failed in this session, don't retry
  979. // it - require the user to log in again.
  980. if (req.session.feature_refresh_failed) {
  981. metrics.inc('features-refresh', 1, {
  982. path: 'load-editor',
  983. status: 'skipped',
  984. })
  985. return user
  986. }
  987. // If the refresh takes too long then return the current
  988. // features. Note that the user.features property may still be
  989. // updated in the background after the promise is resolved.
  990. const abortController = new AbortController()
  991. const refreshTimeoutHandler = async () => {
  992. await setTimeout(5000, { signal: abortController.signal })
  993. req.session.feature_refresh_failed = {
  994. reason: 'timeout',
  995. at: new Date(),
  996. }
  997. metrics.inc('features-refresh', 1, {
  998. path: 'load-editor',
  999. status: 'timeout',
  1000. })
  1001. return user
  1002. }
  1003. // try to refresh user features now
  1004. const timer = new metrics.Timer('features-refresh-on-load-editor')
  1005. return Promise.race([
  1006. refreshTimeoutHandler(),
  1007. (async () => {
  1008. try {
  1009. const { features } = await FeaturesUpdater.promises.refreshFeatures(
  1010. user._id,
  1011. 'load-editor'
  1012. )
  1013. user.features = features
  1014. metrics.inc('features-refresh', 1, {
  1015. path: 'load-editor',
  1016. status: 'success',
  1017. })
  1018. } catch (err) {
  1019. // keep a record to prevent unneceary retries and leave
  1020. // the original features unmodified if the refresh failed
  1021. req.session.feature_refresh_failed = {
  1022. reason: 'error',
  1023. at: new Date(),
  1024. }
  1025. metrics.inc('features-refresh', 1, {
  1026. path: 'load-editor',
  1027. status: 'error',
  1028. })
  1029. }
  1030. abortController.abort()
  1031. timer.done()
  1032. return user
  1033. })(),
  1034. ])
  1035. },
  1036. _buildProjectList(allProjects, userId) {
  1037. let project
  1038. const {
  1039. owned,
  1040. review,
  1041. readAndWrite,
  1042. readOnly,
  1043. tokenReadAndWrite,
  1044. tokenReadOnly,
  1045. } = allProjects
  1046. const projects = []
  1047. for (project of owned) {
  1048. projects.push(
  1049. ProjectController._buildProjectViewModel(
  1050. project,
  1051. 'owner',
  1052. Sources.OWNER,
  1053. userId
  1054. )
  1055. )
  1056. }
  1057. // Invite-access
  1058. for (project of readAndWrite) {
  1059. projects.push(
  1060. ProjectController._buildProjectViewModel(
  1061. project,
  1062. 'readWrite',
  1063. Sources.INVITE,
  1064. userId
  1065. )
  1066. )
  1067. }
  1068. for (project of review) {
  1069. projects.push(
  1070. ProjectController._buildProjectViewModel(
  1071. project,
  1072. 'review',
  1073. Sources.INVITE,
  1074. userId
  1075. )
  1076. )
  1077. }
  1078. for (project of readOnly) {
  1079. projects.push(
  1080. ProjectController._buildProjectViewModel(
  1081. project,
  1082. 'readOnly',
  1083. Sources.INVITE,
  1084. userId
  1085. )
  1086. )
  1087. }
  1088. // Token-access
  1089. // Only add these projects if they're not already present, this gives us cascading access
  1090. // from 'owner' => 'token-read-only'
  1091. for (project of tokenReadAndWrite) {
  1092. if (
  1093. projects.filter(p => p.id.toString() === project._id.toString())
  1094. .length === 0
  1095. ) {
  1096. projects.push(
  1097. ProjectController._buildProjectViewModel(
  1098. project,
  1099. 'readAndWrite',
  1100. Sources.TOKEN,
  1101. userId
  1102. )
  1103. )
  1104. }
  1105. }
  1106. for (project of tokenReadOnly) {
  1107. if (
  1108. projects.filter(p => p.id.toString() === project._id.toString())
  1109. .length === 0
  1110. ) {
  1111. projects.push(
  1112. ProjectController._buildProjectViewModel(
  1113. project,
  1114. 'readOnly',
  1115. Sources.TOKEN,
  1116. userId
  1117. )
  1118. )
  1119. }
  1120. }
  1121. return projects
  1122. },
  1123. _buildProjectViewModel(project, accessLevel, source, userId) {
  1124. const archived = ProjectHelper.isArchived(project, userId)
  1125. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1126. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1127. const model = {
  1128. id: project._id,
  1129. name: project.name,
  1130. lastUpdated: project.lastUpdated,
  1131. lastUpdatedBy: project.lastUpdatedBy,
  1132. publicAccessLevel: project.publicAccesLevel,
  1133. accessLevel,
  1134. source,
  1135. archived,
  1136. trashed,
  1137. owner_ref: project.owner_ref,
  1138. isV1Project: false,
  1139. }
  1140. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1141. model.owner_ref = null
  1142. model.lastUpdatedBy = null
  1143. }
  1144. return model
  1145. },
  1146. _buildPortalTemplatesList(affiliations) {
  1147. if (affiliations == null) {
  1148. affiliations = []
  1149. }
  1150. const portalTemplates = []
  1151. for (const aff of affiliations) {
  1152. if (
  1153. aff.portal &&
  1154. aff.portal.slug &&
  1155. aff.portal.templates_count &&
  1156. aff.portal.templates_count > 0
  1157. ) {
  1158. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1159. portalTemplates.push({
  1160. name: aff.institution.name,
  1161. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1162. })
  1163. }
  1164. }
  1165. return portalTemplates
  1166. },
  1167. async _setWritefullTrialState(
  1168. user,
  1169. userValues,
  1170. userId,
  1171. aiFeaturesAllowed,
  1172. userIsMemberOfGroupSubscription
  1173. ) {
  1174. if (!aiFeaturesAllowed) {
  1175. return
  1176. }
  1177. const affiliations = userValues.affiliations
  1178. const affiliateLookupFailed = affiliations === false
  1179. // if affiliations is specifically false instead of empty, we know the affiliate lookup failed, and should defer to blocking auto-loading
  1180. const inEnterpriseCommons =
  1181. affiliateLookupFailed ||
  1182. affiliations.some(
  1183. affiliation => affiliation.institution?.enterpriseCommons
  1184. )
  1185. const shouldPushWritefull =
  1186. user.writefull?.initialized === false && !userIsMemberOfGroupSubscription
  1187. // 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
  1188. const shouldAutoCreateAccount = shouldPushWritefull && !inEnterpriseCommons
  1189. const shouldAutoLoad = shouldPushWritefull && inEnterpriseCommons
  1190. if (shouldAutoCreateAccount) {
  1191. await UserUpdater.promises.updateUser(userId, {
  1192. $set: {
  1193. writefull: { autoCreatedAccount: true, initialized: true },
  1194. },
  1195. })
  1196. user.writefull.autoCreatedAccount = true
  1197. } else if (shouldAutoLoad) {
  1198. await UserUpdater.promises.updateUser(userId, {
  1199. $set: {
  1200. writefull: { autoCreatedAccount: false, initialized: true },
  1201. },
  1202. })
  1203. user.writefull.autoCreatedAccount = false
  1204. }
  1205. },
  1206. }
  1207. function getInitialLoadingScreenTheme(overallThemeSetting) {
  1208. switch (overallThemeSetting) {
  1209. case 'light-':
  1210. return 'light'
  1211. case '':
  1212. return 'dark'
  1213. case 'system':
  1214. return 'system'
  1215. default:
  1216. return 'dark'
  1217. }
  1218. }
  1219. const defaultSettingsForAnonymousUser = userId => ({
  1220. id: userId,
  1221. ace: {
  1222. mode: 'none',
  1223. theme: 'textmate',
  1224. fontSize: '12',
  1225. autoComplete: true,
  1226. spellCheckLanguage: '',
  1227. pdfViewer: '',
  1228. syntaxValidation: true,
  1229. },
  1230. subscription: {
  1231. freeTrial: {
  1232. allowed: true,
  1233. },
  1234. },
  1235. featureSwitches: {
  1236. github: false,
  1237. },
  1238. alphaProgram: false,
  1239. betaProgram: false,
  1240. writefull: {
  1241. initialized: true,
  1242. },
  1243. aiFeatures: {
  1244. enabled: false,
  1245. },
  1246. })
  1247. const defaultUserValues = () => ({
  1248. user: defaultSettingsForAnonymousUser(null),
  1249. learnedWords: [],
  1250. projectTags: [],
  1251. userHasInstitutionLicence: false,
  1252. affiliations: [],
  1253. subscription: undefined,
  1254. isTokenMember: false,
  1255. isInvitedMember: false,
  1256. })
  1257. const THEME_LIST = [
  1258. { name: 'cobalt', dark: true },
  1259. { name: 'dracula', dark: true },
  1260. { name: 'eclipse', dark: false },
  1261. { name: 'monokai', dark: true },
  1262. { name: 'overleaf', dark: false },
  1263. { name: 'overleaf_dark', dark: true },
  1264. { name: 'textmate', dark: false },
  1265. ]
  1266. const LEGACY_THEME_LIST = [
  1267. { name: 'ambiance', dark: true },
  1268. { name: 'chaos', dark: true },
  1269. { name: 'chrome', dark: false },
  1270. { name: 'clouds', dark: false },
  1271. { name: 'clouds_midnight', dark: true },
  1272. { name: 'crimson_editor', dark: false },
  1273. { name: 'dawn', dark: false },
  1274. { name: 'dreamweaver', dark: false },
  1275. { name: 'github', dark: false },
  1276. { name: 'gob', dark: true },
  1277. { name: 'gruvbox', dark: true },
  1278. { name: 'idle_fingers', dark: true },
  1279. { name: 'iplastic', dark: false },
  1280. { name: 'katzenmilch', dark: false },
  1281. { name: 'kr_theme', dark: true },
  1282. { name: 'kuroir', dark: false },
  1283. { name: 'merbivore', dark: true },
  1284. { name: 'merbivore_soft', dark: true },
  1285. { name: 'mono_industrial', dark: true },
  1286. { name: 'nord_dark', dark: true },
  1287. { name: 'pastel_on_dark', dark: true },
  1288. { name: 'solarized_dark', dark: true },
  1289. { name: 'solarized_light', dark: false },
  1290. { name: 'sqlserver', dark: false },
  1291. { name: 'terminal', dark: true },
  1292. { name: 'tomorrow', dark: false },
  1293. { name: 'tomorrow_night', dark: true },
  1294. { name: 'tomorrow_night_blue', dark: true },
  1295. { name: 'tomorrow_night_bright', dark: true },
  1296. { name: 'tomorrow_night_eighties', dark: true },
  1297. { name: 'twilight', dark: true },
  1298. { name: 'vibrant_ink', dark: true },
  1299. { name: 'xcode', dark: false },
  1300. ]
  1301. const ProjectController = {
  1302. archiveProject: expressify(_ProjectController.archiveProject),
  1303. cloneProject: expressify(_ProjectController.cloneProject),
  1304. deleteProject: expressify(_ProjectController.deleteProject),
  1305. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  1306. expireDeletedProjectsAfterDuration: expressify(
  1307. _ProjectController.expireDeletedProjectsAfterDuration
  1308. ),
  1309. loadEditor: expressify(_ProjectController.loadEditor),
  1310. newProject: expressify(_ProjectController.newProject),
  1311. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  1312. renameProject: expressify(_ProjectController.renameProject),
  1313. restoreProject: expressify(_ProjectController.restoreProject),
  1314. trashProject: expressify(_ProjectController.trashProject),
  1315. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  1316. untrashProject: expressify(_ProjectController.untrashProject),
  1317. updateProjectAdminSettings: expressify(
  1318. _ProjectController.updateProjectAdminSettings
  1319. ),
  1320. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  1321. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  1322. _buildProjectList: _ProjectController._buildProjectList,
  1323. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  1324. _injectProjectUsers: _ProjectController._injectProjectUsers,
  1325. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  1326. _refreshFeatures: _ProjectController._refreshFeatures,
  1327. _getPlanPricing: _ProjectController._getPlanPricing,
  1328. _getAddonPrices: _ProjectController._getAddonPrices,
  1329. _setWritefullTrialState: _ProjectController._setWritefullTrialState,
  1330. }
  1331. export default ProjectController