ProjectController.js 38 KB

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