ProjectController.js 40 KB

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