ProjectController.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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 LimitationsManager = require('../Subscription/LimitationsManager')
  18. const FeaturesHelper = require('../Subscription/FeaturesHelper')
  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 OnboardingDataCollectionManager = require('../OnboardingDataCollection/OnboardingDataCollectionManager')
  47. const UserUpdater = require('../User/UserUpdater')
  48. const Modules = require('../../infrastructure/Modules')
  49. const UserGetter = require('../User/UserGetter')
  50. const {
  51. isStandaloneAiAddOnPlanCode,
  52. } = require('../Subscription/PaymentProviderEntities')
  53. const SubscriptionController = require('../Subscription/SubscriptionController.js')
  54. const { formatCurrency } = require('../../util/currency')
  55. /**
  56. * @import { GetProjectsRequest, GetProjectsResponse, Project } from "./types"
  57. */
  58. const _ProjectController = {
  59. _isInPercentageRollout(rolloutName, objectId, percentage) {
  60. if (Settings.bypassPercentageRollouts === true) {
  61. return true
  62. }
  63. const data = `${rolloutName}:${objectId.toString()}`
  64. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  65. const counter = parseInt(md5hash.slice(26, 32), 16)
  66. return counter % 100 < percentage
  67. },
  68. async updateProjectSettings(req, res) {
  69. const projectId = req.params.Project_id
  70. if (req.body.compiler != null) {
  71. await EditorController.promises.setCompiler(projectId, req.body.compiler)
  72. }
  73. if (req.body.imageName != null) {
  74. await EditorController.promises.setImageName(
  75. projectId,
  76. req.body.imageName
  77. )
  78. }
  79. if (req.body.name != null) {
  80. await EditorController.promises.renameProject(projectId, req.body.name)
  81. }
  82. if (req.body.spellCheckLanguage != null) {
  83. await EditorController.promises.setSpellCheckLanguage(
  84. projectId,
  85. req.body.spellCheckLanguage
  86. )
  87. }
  88. if (req.body.rootDocId != null) {
  89. await EditorController.promises.setRootDoc(projectId, req.body.rootDocId)
  90. }
  91. if (req.body.mainBibliographyDocId != null) {
  92. await EditorController.promises.setMainBibliographyDoc(
  93. projectId,
  94. req.body.mainBibliographyDocId
  95. )
  96. }
  97. res.sendStatus(204)
  98. },
  99. async updateProjectAdminSettings(req, res) {
  100. const projectId = req.params.Project_id
  101. const user = SessionManager.getSessionUser(req.session)
  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. const projectId = req.params.Project_id
  291. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  292. function shouldDisplayFeature(name, variantFlag) {
  293. if (req.query && req.query[name]) {
  294. return req.query[name] === 'true'
  295. } else {
  296. return variantFlag === true
  297. }
  298. }
  299. const splitTests = [
  300. 'compile-log-events',
  301. 'external-socket-heartbeat',
  302. 'full-project-search',
  303. 'null-test-share-modal',
  304. 'populate-clsi-cache',
  305. 'pdf-caching-cached-url-lookup',
  306. 'pdf-caching-mode',
  307. 'pdf-caching-prefetch-large',
  308. 'pdf-caching-prefetching',
  309. 'revert-file',
  310. 'revert-project',
  311. !anonymous && 'ro-mirror-on-client',
  312. 'track-pdf-download',
  313. !anonymous && 'writefull-oauth-promotion',
  314. 'hotjar',
  315. 'reviewer-role',
  316. 'editor-redesign',
  317. 'paywall-change-compile-timeout',
  318. 'overleaf-assist-bundle',
  319. 'word-count-client',
  320. 'editor-popup-ux-survey',
  321. ].filter(Boolean)
  322. const getUserValues = async userId =>
  323. pProps(
  324. _.mapValues({
  325. user: (async () => {
  326. const user = await User.findById(
  327. userId,
  328. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsExperiments completedTutorials writefull aiErrorAssistant'
  329. ).exec()
  330. // Handle case of deleted user
  331. if (!user) {
  332. UserController.logout(req, res, next)
  333. return
  334. }
  335. logger.debug({ projectId, userId }, 'got user')
  336. return FeaturesUpdater.featuresEpochIsCurrent(user)
  337. ? user
  338. : await ProjectController._refreshFeatures(req, user)
  339. })(),
  340. learnedWords: SpellingHandler.promises.getUserDictionary(userId),
  341. projectTags: TagsHandler.promises.getTagsForProject(
  342. userId,
  343. projectId
  344. ),
  345. userHasInstitutionLicence: InstitutionsFeatures.promises
  346. .hasLicence(userId)
  347. .catch(err => {
  348. logger.error({ err, userId }, 'failed to get institution licence')
  349. return false
  350. }),
  351. affiliations: InstitutionsGetter.promises
  352. .getCurrentAffiliations(userId)
  353. .catch(err => {
  354. logger.error({ err, userId }, 'failed to get institution licence')
  355. return false
  356. }),
  357. subscription:
  358. SubscriptionLocator.promises.getUsersSubscription(userId),
  359. isTokenMember: CollaboratorsGetter.promises.userIsTokenMember(
  360. userId,
  361. projectId
  362. ),
  363. isInvitedMember:
  364. CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  365. userId,
  366. projectId
  367. ),
  368. odcRole: OnboardingDataCollectionManager.getOnboardingDataValue(
  369. userId,
  370. 'role'
  371. ).catch(err => {
  372. logger.error({ err, userId })
  373. return null
  374. }),
  375. })
  376. )
  377. const splitTestAssignments = {}
  378. try {
  379. const responses = await pProps({
  380. userValues: userId ? getUserValues(userId) : defaultUserValues(),
  381. splitTestAssignments: Promise.all(
  382. splitTests.map(async splitTest => {
  383. splitTestAssignments[splitTest] =
  384. await SplitTestHandler.promises.getAssignment(req, res, splitTest)
  385. })
  386. ),
  387. project: ProjectGetter.promises.getProject(projectId, {
  388. name: 1,
  389. lastUpdated: 1,
  390. track_changes: 1,
  391. owner_ref: 1,
  392. brandVariationId: 1,
  393. overleaf: 1,
  394. tokens: 1,
  395. tokenAccessReadAndWrite_refs: 1, // used for link sharing analytics
  396. collaberator_refs: 1, // used for link sharing analytics
  397. pendingEditor_refs: 1, // used for link sharing analytics
  398. reviewer_refs: 1,
  399. }),
  400. userIsMemberOfGroupSubscription: sessionUser
  401. ? (async () =>
  402. (
  403. await LimitationsManager.promises.userIsMemberOfGroupSubscription(
  404. sessionUser
  405. )
  406. ).isMember)()
  407. : false,
  408. _flushToTpds:
  409. TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(projectId),
  410. _activate:
  411. InactiveProjectManager.promises.reactivateProjectIfRequired(
  412. projectId
  413. ),
  414. })
  415. const { project, userValues, userIsMemberOfGroupSubscription } = responses
  416. const {
  417. user,
  418. learnedWords,
  419. projectTags,
  420. userHasInstitutionLicence,
  421. subscription,
  422. isTokenMember,
  423. isInvitedMember,
  424. odcRole,
  425. } = userValues
  426. const brandVariation = project?.brandVariationId
  427. ? await BrandVariationsHandler.promises.getBrandVariationById(
  428. project.brandVariationId
  429. )
  430. : undefined
  431. const anonRequestToken = TokenAccessHandler.getRequestToken(
  432. req,
  433. projectId
  434. )
  435. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  436. const privilegeLevel =
  437. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  438. userId,
  439. projectId,
  440. anonRequestToken
  441. )
  442. const reviewerRoleAssignment =
  443. await SplitTestHandler.promises.getAssignmentForUser(
  444. project.owner_ref,
  445. 'reviewer-role'
  446. )
  447. await Modules.promises.hooks.fire('enforceCollaboratorLimit', projectId)
  448. if (isTokenMember) {
  449. // Check explicitly that the user is in read write token refs, while this could be inferred
  450. // from the privilege level, the privilege level of token members might later be restricted
  451. const isReadWriteTokenMember =
  452. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  453. userId,
  454. projectId
  455. )
  456. if (isReadWriteTokenMember) {
  457. // Check for an edge case where a user is both in read write token access refs but also
  458. // an invited read write member. Ensure they are not redirected to the sharing updates page
  459. // We could also delete the token access ref if the user is already a member of the project
  460. const isInvitedReadWriteMember =
  461. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  462. userId,
  463. projectId
  464. )
  465. if (!isInvitedReadWriteMember) {
  466. return res.redirect(`/project/${projectId}/sharing-updates`)
  467. }
  468. }
  469. }
  470. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  471. return res.sendStatus(401)
  472. }
  473. const allowedFreeTrial =
  474. subscription == null ||
  475. isStandaloneAiAddOnPlanCode(subscription.planCode)
  476. let wsUrl = Settings.wsUrl
  477. let metricName = 'load-editor-ws'
  478. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  479. wsUrl = Settings.wsUrlBeta
  480. metricName += '-beta'
  481. } else if (
  482. Settings.wsUrlV2 &&
  483. Settings.wsUrlV2Percentage > 0 &&
  484. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  485. Settings.wsUrlV2Percentage
  486. ) {
  487. wsUrl = Settings.wsUrlV2
  488. metricName += '-v2'
  489. }
  490. if (req.query && req.query.ws === 'fallback') {
  491. // `?ws=fallback` will connect to the bare origin, and ignore
  492. // the custom wsUrl. Hence it must load the client side
  493. // javascript from there too.
  494. // Not resetting it here would possibly load a socket.io v2
  495. // client and connect to a v0 endpoint.
  496. wsUrl = undefined
  497. metricName += '-fallback'
  498. }
  499. metrics.inc(metricName)
  500. // don't need to wait for these to complete
  501. ProjectUpdateHandler.promises
  502. .markAsOpened(projectId)
  503. .catch(err =>
  504. logger.error({ err, projectId }, 'failed to mark project as opened')
  505. )
  506. SplitTestSessionHandler.promises
  507. .sessionMaintenance(req, userId ? user : null)
  508. .catch(err =>
  509. logger.error({ err }, 'failed to update split test info in session')
  510. )
  511. const ownerFeatures = await UserGetter.promises.getUserFeatures(
  512. project.owner_ref
  513. )
  514. if (userId) {
  515. const planLimit = ownerFeatures?.collaborators || 0
  516. const namedEditors = project.collaberator_refs?.length || 0
  517. const pendingEditors = project.pendingEditor_refs?.length || 0
  518. const exceedAtLimit = planLimit > -1 && namedEditors >= planLimit
  519. let mode = 'edit'
  520. if (privilegeLevel === PrivilegeLevels.READ_ONLY) {
  521. mode = 'view'
  522. } else if (
  523. project.track_changes === true ||
  524. project.track_changes?.[userId] === true
  525. ) {
  526. mode = 'review'
  527. }
  528. const projectOpenedSegmentation = {
  529. role: privilegeLevel,
  530. mode,
  531. ownerId: project.owner_ref,
  532. projectId: project._id,
  533. namedEditors,
  534. pendingEditors,
  535. tokenEditors: project.tokenAccessReadAndWrite_refs?.length || 0,
  536. planLimit,
  537. exceedAtLimit,
  538. }
  539. AnalyticsManager.recordEventForUserInBackground(
  540. userId,
  541. 'project-opened',
  542. projectOpenedSegmentation
  543. )
  544. User.updateOne(
  545. { _id: new ObjectId(userId) },
  546. { $set: { lastActive: new Date() } }
  547. )
  548. .exec()
  549. .catch(err =>
  550. logger.error(
  551. { err, userId },
  552. 'failed to update lastActive for user'
  553. )
  554. )
  555. }
  556. const isAdminOrTemplateOwner =
  557. hasAdminAccess(user) || Settings.templates?.user_id === userId
  558. const showTemplatesServerPro =
  559. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  560. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  561. const detachRole = req.params.detachRole
  562. const showSymbolPalette =
  563. !Features.hasFeature('saas') ||
  564. (user.features && user.features.symbolPalette)
  565. const userInNonIndividualSub =
  566. userIsMemberOfGroupSubscription || userHasInstitutionLicence
  567. const userHasPremiumSub =
  568. subscription && !isStandaloneAiAddOnPlanCode(subscription.planCode)
  569. // Persistent upgrade prompts
  570. // in header & in share project modal
  571. const showUpgradePrompt =
  572. Features.hasFeature('saas') &&
  573. userId &&
  574. !userHasPremiumSub &&
  575. !userInNonIndividualSub
  576. let aiFeaturesAllowed = false
  577. if (userId && Features.hasFeature('saas')) {
  578. try {
  579. // exit early if the user couldnt use ai anyways, since permissions checks are expensive
  580. const canUserWriteOrReviewProjectContent =
  581. privilegeLevel === PrivilegeLevels.READ_AND_WRITE ||
  582. privilegeLevel === PrivilegeLevels.OWNER ||
  583. privilegeLevel === PrivilegeLevels.REVIEW
  584. if (canUserWriteOrReviewProjectContent) {
  585. // check permissions for user and project owner, to see if they allow AI on the project
  586. const permissionsResults = await Modules.promises.hooks.fire(
  587. 'projectAllowsCapability',
  588. project,
  589. userId,
  590. ['use-ai']
  591. )
  592. const aiAllowed = permissionsResults.every(
  593. result => result === true
  594. )
  595. aiFeaturesAllowed = aiAllowed
  596. }
  597. } catch (err) {
  598. // still allow users to access project if we cant get their permissions, but disable AI feature
  599. aiFeaturesAllowed = false
  600. }
  601. }
  602. const hasNonRecurlySubscription =
  603. subscription && !subscription.recurlySubscription_id
  604. const hasManuallyCollectedSubscription =
  605. subscription?.collectionMethod === 'manual'
  606. const canPurchaseAddons = !(
  607. hasNonRecurlySubscription || hasManuallyCollectedSubscription
  608. )
  609. const assistantDisabled = user.aiErrorAssistant?.enabled === false // the assistant has been manually disabled by the user
  610. const canUseErrorAssistant =
  611. (user.features?.aiErrorAssistant || canPurchaseAddons) &&
  612. !assistantDisabled
  613. let featureUsage = {}
  614. if (Features.hasFeature('saas')) {
  615. const usagesLeft = await Modules.promises.hooks.fire(
  616. 'remainingFeatureAllocation',
  617. userId
  618. )
  619. usagesLeft?.forEach(usage => {
  620. featureUsage = { ...featureUsage, ...usage }
  621. })
  622. }
  623. let inEnterpriseCommons = false
  624. const affiliations = userValues.affiliations || []
  625. for (const affiliation of affiliations) {
  626. inEnterpriseCommons =
  627. inEnterpriseCommons || affiliation.institution?.enterpriseCommons
  628. }
  629. // check if a user has never tried writefull before (writefull.enabled will be null)
  630. // if they previously accepted writefull, or are have been already assigned to a trial, user.writefull will be true,
  631. // if they explicitly disabled it, user.writefull will be false
  632. if (
  633. aiFeaturesAllowed &&
  634. user.writefull?.enabled === null &&
  635. !userIsMemberOfGroupSubscription &&
  636. !inEnterpriseCommons
  637. ) {
  638. const { variant } = await SplitTestHandler.promises.getAssignment(
  639. req,
  640. res,
  641. 'writefull-auto-account-creation'
  642. )
  643. if (variant === 'enabled') {
  644. await UserUpdater.promises.updateUser(userId, {
  645. $set: {
  646. writefull: { enabled: true, autoCreatedAccount: true },
  647. },
  648. })
  649. user.writefull.enabled = true
  650. user.writefull.autoCreatedAccount = true
  651. } else {
  652. const { variant } = await SplitTestHandler.promises.getAssignment(
  653. req,
  654. res,
  655. 'writefull-auto-load'
  656. )
  657. if (variant === 'enabled') {
  658. await UserUpdater.promises.updateUser(userId, {
  659. $set: {
  660. writefull: { enabled: true },
  661. },
  662. })
  663. user.writefull.enabled = true
  664. user.writefull.firstAutoLoad = true
  665. }
  666. }
  667. }
  668. const template =
  669. detachRole === 'detached'
  670. ? 'project/ide-react-detached'
  671. : 'project/ide-react'
  672. let chatEnabled
  673. if (Features.hasFeature('saas')) {
  674. chatEnabled =
  675. Features.hasFeature('chat') && req.capabilitySet.has('chat')
  676. } else {
  677. chatEnabled = Features.hasFeature('chat')
  678. }
  679. const isOverleafAssistBundleEnabled =
  680. splitTestAssignments['overleaf-assist-bundle']?.variant === 'enabled'
  681. let fullFeatureSet = user?.features
  682. if (!anonymous) {
  683. // generate users feature set including features added, or overriden via modules
  684. const moduleFeatures =
  685. (await Modules.promises.hooks.fire(
  686. 'getModuleProvidedFeatures',
  687. userId
  688. )) || []
  689. fullFeatureSet = FeaturesHelper.computeFeatureSet([
  690. user.features,
  691. ...moduleFeatures,
  692. ])
  693. }
  694. const isPaywallChangeCompileTimeoutEnabled =
  695. splitTestAssignments['paywall-change-compile-timeout']?.variant ===
  696. 'enabled'
  697. const paywallPlans =
  698. isPaywallChangeCompileTimeoutEnabled &&
  699. (await ProjectController._getPaywallPlansPrices(req, res))
  700. const customerIoEnabled =
  701. await SplitTestHandler.promises.hasUserBeenAssignedToVariant(
  702. req,
  703. userId,
  704. 'customer-io-trial-conversion',
  705. 'enabled',
  706. true
  707. )
  708. const addonPrices =
  709. isOverleafAssistBundleEnabled &&
  710. (await ProjectController._getAddonPrices(req, res))
  711. let planCode = subscription?.planCode
  712. if (!planCode && !userInNonIndividualSub) {
  713. planCode = 'personal'
  714. }
  715. const planDetails = Settings.plans.find(p => p.planCode === planCode)
  716. res.render(template, {
  717. title: project.name,
  718. priority_title: true,
  719. bodyClasses: ['editor'],
  720. project_id: project._id,
  721. projectName: project.name,
  722. projectOwnerHasPremiumOnPageLoad:
  723. ownerFeatures?.compileGroup === 'priority',
  724. user: {
  725. id: userId,
  726. email: user.email,
  727. first_name: user.first_name,
  728. last_name: user.last_name,
  729. referal_id: user.referal_id,
  730. signUpDate: user.signUpDate,
  731. allowedFreeTrial,
  732. hasRecurlySubscription: subscription?.recurlySubscription_id != null,
  733. featureSwitches: user.featureSwitches,
  734. features: fullFeatureSet,
  735. featureUsage,
  736. refProviders: _.mapValues(user.refProviders, Boolean),
  737. writefull: {
  738. enabled: Boolean(user.writefull?.enabled && aiFeaturesAllowed),
  739. autoCreatedAccount: Boolean(user.writefull?.autoCreatedAccount),
  740. firstAutoLoad: Boolean(user.writefull?.firstAutoLoad),
  741. },
  742. alphaProgram: user.alphaProgram,
  743. betaProgram: user.betaProgram,
  744. labsProgram: user.labsProgram,
  745. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  746. isAdmin: hasAdminAccess(user),
  747. planCode,
  748. planName: planDetails?.name,
  749. isAnnualPlan: planCode && planDetails?.annual,
  750. isMemberOfGroupSubscription: userIsMemberOfGroupSubscription,
  751. hasInstitutionLicence: userHasInstitutionLicence,
  752. },
  753. userSettings: {
  754. mode: user.ace.mode,
  755. editorTheme: user.ace.theme,
  756. fontSize: user.ace.fontSize,
  757. autoComplete: user.ace.autoComplete,
  758. autoPairDelimiters: user.ace.autoPairDelimiters,
  759. pdfViewer: user.ace.pdfViewer,
  760. syntaxValidation: user.ace.syntaxValidation,
  761. fontFamily: user.ace.fontFamily || 'lucida',
  762. lineHeight: user.ace.lineHeight || 'normal',
  763. overallTheme: user.ace.overallTheme,
  764. mathPreview: user.ace.mathPreview,
  765. referencesSearchMode: user.ace.referencesSearchMode,
  766. enableNewEditor: user.ace.enableNewEditor ?? true,
  767. },
  768. labsExperiments: user.labsExperiments ?? [],
  769. privilegeLevel,
  770. anonymous,
  771. isTokenMember,
  772. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  773. userId,
  774. privilegeLevel,
  775. isTokenMember,
  776. isInvitedMember
  777. ),
  778. chatEnabled,
  779. projectHistoryBlobsEnabled: Features.hasFeature(
  780. 'project-history-blobs'
  781. ),
  782. roMirrorOnClientNoLocalStorage:
  783. Settings.adminOnlyLogin || project.name.startsWith('Debug: '),
  784. languages: Settings.languages,
  785. learnedWords,
  786. editorThemes: THEME_LIST,
  787. legacyEditorThemes: LEGACY_THEME_LIST,
  788. maxDocLength: Settings.max_doc_length,
  789. maxReconnectGracefullyIntervalMs:
  790. Settings.maxReconnectGracefullyIntervalMs,
  791. brandVariation,
  792. allowedImageNames,
  793. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  794. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  795. wsUrl,
  796. showSupport: Features.hasFeature('support'),
  797. showTemplatesServerPro,
  798. debugPdfDetach,
  799. showSymbolPalette,
  800. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  801. userRestrictions: Array.from(req.userRestrictions || []),
  802. showAiErrorAssistant: aiFeaturesAllowed && canUseErrorAssistant,
  803. detachRole,
  804. metadata: { viewport: false },
  805. showUpgradePrompt,
  806. fixedSizeDocument: true,
  807. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  808. projectTags,
  809. odcRole:
  810. // only use the ODC role value if the split test is enabled
  811. splitTestAssignments['paywall-change-compile-timeout']?.variant ===
  812. 'enabled'
  813. ? odcRole
  814. : null,
  815. isSaas: Features.hasFeature('saas'),
  816. shouldLoadHotjar: splitTestAssignments.hotjar?.variant === 'enabled',
  817. isReviewerRoleEnabled:
  818. reviewerRoleAssignment?.variant === 'enabled' ||
  819. Object.keys(project.reviewer_refs || {}).length > 0,
  820. isPaywallChangeCompileTimeoutEnabled,
  821. isOverleafAssistBundleEnabled,
  822. paywallPlans,
  823. customerIoEnabled,
  824. addonPrices,
  825. })
  826. timer.done()
  827. } catch (err) {
  828. OError.tag(err, 'error getting details for project page')
  829. return next(err)
  830. }
  831. },
  832. async _getPaywallPlansPrices(
  833. req,
  834. res,
  835. paywallPlans = ['collaborator', 'student']
  836. ) {
  837. const plansData = {}
  838. const locale = req.i18n.language
  839. const { currency } = await SubscriptionController.getRecommendedCurrency(
  840. req,
  841. res
  842. )
  843. paywallPlans.forEach(plan => {
  844. const planPrice = Settings.localizedPlanPricing[currency][plan].monthly
  845. const formattedPlanPrice = formatCurrency(
  846. planPrice,
  847. currency,
  848. locale,
  849. true
  850. )
  851. plansData[plan] = formattedPlanPrice
  852. })
  853. return plansData
  854. },
  855. async _getAddonPrices(req, res, addonPlans = ['assistant']) {
  856. const plansData = {}
  857. const locale = req.i18n.language
  858. const { currency } = await SubscriptionController.getRecommendedCurrency(
  859. req,
  860. res
  861. )
  862. addonPlans.forEach(plan => {
  863. const annualPrice = Settings.localizedAddOnsPricing[currency][plan].annual
  864. const monthlyPrice =
  865. Settings.localizedAddOnsPricing[currency][plan].monthly
  866. plansData[plan] = {
  867. annual: formatCurrency(annualPrice, currency, locale, true),
  868. monthly: formatCurrency(monthlyPrice, currency, locale, true),
  869. }
  870. })
  871. return plansData
  872. },
  873. async _refreshFeatures(req, user) {
  874. // If the feature refresh has failed in this session, don't retry
  875. // it - require the user to log in again.
  876. if (req.session.feature_refresh_failed) {
  877. metrics.inc('features-refresh', 1, {
  878. path: 'load-editor',
  879. status: 'skipped',
  880. })
  881. return user
  882. }
  883. // If the refresh takes too long then return the current
  884. // features. Note that the user.features property may still be
  885. // updated in the background after the promise is resolved.
  886. const abortController = new AbortController()
  887. const refreshTimeoutHandler = async () => {
  888. await setTimeout(5000, { signal: abortController.signal })
  889. req.session.feature_refresh_failed = {
  890. reason: 'timeout',
  891. at: new Date(),
  892. }
  893. metrics.inc('features-refresh', 1, {
  894. path: 'load-editor',
  895. status: 'timeout',
  896. })
  897. return user
  898. }
  899. // try to refresh user features now
  900. const timer = new metrics.Timer('features-refresh-on-load-editor')
  901. return Promise.race([
  902. refreshTimeoutHandler(),
  903. (async () => {
  904. try {
  905. user.features = await FeaturesUpdater.promises.refreshFeatures(
  906. user._id,
  907. 'load-editor'
  908. )
  909. metrics.inc('features-refresh', 1, {
  910. path: 'load-editor',
  911. status: 'success',
  912. })
  913. } catch (err) {
  914. // keep a record to prevent unneceary retries and leave
  915. // the original features unmodified if the refresh failed
  916. req.session.feature_refresh_failed = {
  917. reason: 'error',
  918. at: new Date(),
  919. }
  920. metrics.inc('features-refresh', 1, {
  921. path: 'load-editor',
  922. status: 'error',
  923. })
  924. }
  925. abortController.abort()
  926. timer.done()
  927. return user
  928. })(),
  929. ])
  930. },
  931. _buildProjectList(allProjects, userId) {
  932. let project
  933. const {
  934. owned,
  935. review,
  936. readAndWrite,
  937. readOnly,
  938. tokenReadAndWrite,
  939. tokenReadOnly,
  940. } = allProjects
  941. const projects = []
  942. for (project of owned) {
  943. projects.push(
  944. ProjectController._buildProjectViewModel(
  945. project,
  946. 'owner',
  947. Sources.OWNER,
  948. userId
  949. )
  950. )
  951. }
  952. // Invite-access
  953. for (project of readAndWrite) {
  954. projects.push(
  955. ProjectController._buildProjectViewModel(
  956. project,
  957. 'readWrite',
  958. Sources.INVITE,
  959. userId
  960. )
  961. )
  962. }
  963. for (project of review) {
  964. projects.push(
  965. ProjectController._buildProjectViewModel(
  966. project,
  967. 'review',
  968. Sources.INVITE,
  969. userId
  970. )
  971. )
  972. }
  973. for (project of readOnly) {
  974. projects.push(
  975. ProjectController._buildProjectViewModel(
  976. project,
  977. 'readOnly',
  978. Sources.INVITE,
  979. userId
  980. )
  981. )
  982. }
  983. // Token-access
  984. // Only add these projects if they're not already present, this gives us cascading access
  985. // from 'owner' => 'token-read-only'
  986. for (project of tokenReadAndWrite) {
  987. if (
  988. projects.filter(p => p.id.toString() === project._id.toString())
  989. .length === 0
  990. ) {
  991. projects.push(
  992. ProjectController._buildProjectViewModel(
  993. project,
  994. 'readAndWrite',
  995. Sources.TOKEN,
  996. userId
  997. )
  998. )
  999. }
  1000. }
  1001. for (project of tokenReadOnly) {
  1002. if (
  1003. projects.filter(p => p.id.toString() === project._id.toString())
  1004. .length === 0
  1005. ) {
  1006. projects.push(
  1007. ProjectController._buildProjectViewModel(
  1008. project,
  1009. 'readOnly',
  1010. Sources.TOKEN,
  1011. userId
  1012. )
  1013. )
  1014. }
  1015. }
  1016. return projects
  1017. },
  1018. _buildProjectViewModel(project, accessLevel, source, userId) {
  1019. const archived = ProjectHelper.isArchived(project, userId)
  1020. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1021. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1022. const model = {
  1023. id: project._id,
  1024. name: project.name,
  1025. lastUpdated: project.lastUpdated,
  1026. lastUpdatedBy: project.lastUpdatedBy,
  1027. publicAccessLevel: project.publicAccesLevel,
  1028. accessLevel,
  1029. source,
  1030. archived,
  1031. trashed,
  1032. owner_ref: project.owner_ref,
  1033. isV1Project: false,
  1034. }
  1035. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1036. model.owner_ref = null
  1037. model.lastUpdatedBy = null
  1038. }
  1039. return model
  1040. },
  1041. _buildPortalTemplatesList(affiliations) {
  1042. if (affiliations == null) {
  1043. affiliations = []
  1044. }
  1045. const portalTemplates = []
  1046. for (const aff of affiliations) {
  1047. if (
  1048. aff.portal &&
  1049. aff.portal.slug &&
  1050. aff.portal.templates_count &&
  1051. aff.portal.templates_count > 0
  1052. ) {
  1053. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1054. portalTemplates.push({
  1055. name: aff.institution.name,
  1056. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1057. })
  1058. }
  1059. }
  1060. return portalTemplates
  1061. },
  1062. }
  1063. const defaultSettingsForAnonymousUser = userId => ({
  1064. id: userId,
  1065. ace: {
  1066. mode: 'none',
  1067. theme: 'textmate',
  1068. fontSize: '12',
  1069. autoComplete: true,
  1070. spellCheckLanguage: '',
  1071. pdfViewer: '',
  1072. syntaxValidation: true,
  1073. },
  1074. subscription: {
  1075. freeTrial: {
  1076. allowed: true,
  1077. },
  1078. },
  1079. featureSwitches: {
  1080. github: false,
  1081. },
  1082. alphaProgram: false,
  1083. betaProgram: false,
  1084. writefull: {
  1085. enabled: false,
  1086. },
  1087. })
  1088. const defaultUserValues = () => ({
  1089. user: defaultSettingsForAnonymousUser(null),
  1090. learnedWords: [],
  1091. projectTags: [],
  1092. userHasInstitutionLicence: false,
  1093. subscription: undefined,
  1094. isTokenMember: false,
  1095. isInvitedMember: false,
  1096. })
  1097. const THEME_LIST = [
  1098. 'cobalt',
  1099. 'dracula',
  1100. 'eclipse',
  1101. 'monokai',
  1102. 'overleaf',
  1103. 'textmate',
  1104. ]
  1105. const LEGACY_THEME_LIST = [
  1106. 'ambiance',
  1107. 'chaos',
  1108. 'chrome',
  1109. 'clouds',
  1110. 'clouds_midnight',
  1111. 'crimson_editor',
  1112. 'dawn',
  1113. 'dreamweaver',
  1114. 'github',
  1115. 'gob',
  1116. 'gruvbox',
  1117. 'idle_fingers',
  1118. 'iplastic',
  1119. 'katzenmilch',
  1120. 'kr_theme',
  1121. 'kuroir',
  1122. 'merbivore',
  1123. 'merbivore_soft',
  1124. 'mono_industrial',
  1125. 'nord_dark',
  1126. 'pastel_on_dark',
  1127. 'solarized_dark',
  1128. 'solarized_light',
  1129. 'sqlserver',
  1130. 'terminal',
  1131. 'tomorrow',
  1132. 'tomorrow_night',
  1133. 'tomorrow_night_blue',
  1134. 'tomorrow_night_bright',
  1135. 'tomorrow_night_eighties',
  1136. 'twilight',
  1137. 'vibrant_ink',
  1138. 'xcode',
  1139. ]
  1140. const ProjectController = {
  1141. archiveProject: expressify(_ProjectController.archiveProject),
  1142. cloneProject: expressify(_ProjectController.cloneProject),
  1143. deleteProject: expressify(_ProjectController.deleteProject),
  1144. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  1145. expireDeletedProjectsAfterDuration: expressify(
  1146. _ProjectController.expireDeletedProjectsAfterDuration
  1147. ),
  1148. loadEditor: expressify(_ProjectController.loadEditor),
  1149. newProject: expressify(_ProjectController.newProject),
  1150. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  1151. renameProject: expressify(_ProjectController.renameProject),
  1152. restoreProject: expressify(_ProjectController.restoreProject),
  1153. trashProject: expressify(_ProjectController.trashProject),
  1154. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  1155. untrashProject: expressify(_ProjectController.untrashProject),
  1156. updateProjectAdminSettings: expressify(
  1157. _ProjectController.updateProjectAdminSettings
  1158. ),
  1159. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  1160. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  1161. _buildProjectList: _ProjectController._buildProjectList,
  1162. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  1163. _injectProjectUsers: _ProjectController._injectProjectUsers,
  1164. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  1165. _refreshFeatures: _ProjectController._refreshFeatures,
  1166. _getPaywallPlansPrices: _ProjectController._getPaywallPlansPrices,
  1167. _getAddonPrices: _ProjectController._getAddonPrices,
  1168. }
  1169. module.exports = ProjectController