ProjectController.mjs 45 KB

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