ProjectController.mjs 47 KB

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