ProjectController.js 40 KB

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