ProjectController.mjs 44 KB

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