ProjectController.mjs 45 KB

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