ProjectController.mjs 45 KB

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