ProjectController.mjs 46 KB

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