ProjectController.mjs 43 KB

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