ProjectController.mjs 46 KB

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