ProjectController.js 41 KB

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