ProjectController.mjs 45 KB

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