ProjectController.mjs 45 KB

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