ProjectController.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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')
  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 ProjectAuditLogHandler = require('./ProjectAuditLogHandler')
  41. const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
  42. const TagsHandler = require('../Tags/TagsHandler')
  43. const TutorialHandler = require('../Tutorial/TutorialHandler')
  44. /**
  45. * @typedef {import("./types").GetProjectsRequest} GetProjectsRequest
  46. * @typedef {import("./types").GetProjectsResponse} GetProjectsResponse
  47. * @typedef {import("./types").Project} Project
  48. */
  49. const _ProjectController = {
  50. _isInPercentageRollout(rolloutName, objectId, percentage) {
  51. if (Settings.bypassPercentageRollouts === true) {
  52. return true
  53. }
  54. const data = `${rolloutName}:${objectId.toString()}`
  55. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  56. const counter = parseInt(md5hash.slice(26, 32), 16)
  57. return counter % 100 < percentage
  58. },
  59. async updateProjectSettings(req, res) {
  60. const projectId = req.params.Project_id
  61. if (req.body.compiler != null) {
  62. await EditorController.promises.setCompiler(projectId, req.body.compiler)
  63. }
  64. if (req.body.imageName != null) {
  65. await EditorController.promises.setImageName(
  66. projectId,
  67. req.body.imageName
  68. )
  69. }
  70. if (req.body.name != null) {
  71. await EditorController.promises.renameProject(projectId, req.body.name)
  72. }
  73. if (req.body.spellCheckLanguage != null) {
  74. await EditorController.promises.setSpellCheckLanguage(
  75. projectId,
  76. req.body.spellCheckLanguage
  77. )
  78. }
  79. if (req.body.rootDocId != null) {
  80. await EditorController.promises.setRootDoc(projectId, req.body.rootDocId)
  81. }
  82. res.sendStatus(204)
  83. },
  84. async updateProjectAdminSettings(req, res) {
  85. const projectId = req.params.Project_id
  86. const user = SessionManager.getSessionUser(req.session)
  87. const publicAccessLevel = req.body.publicAccessLevel
  88. const publicAccessLevels = [
  89. PublicAccessLevels.READ_ONLY,
  90. PublicAccessLevels.READ_AND_WRITE,
  91. PublicAccessLevels.PRIVATE,
  92. PublicAccessLevels.TOKEN_BASED,
  93. ]
  94. if (
  95. req.body.publicAccessLevel != null &&
  96. publicAccessLevels.includes(publicAccessLevel)
  97. ) {
  98. await EditorController.promises.setPublicAccessLevel(
  99. projectId,
  100. req.body.publicAccessLevel
  101. )
  102. await ProjectAuditLogHandler.promises.addEntry(
  103. projectId,
  104. 'toggle-access-level',
  105. user._id,
  106. req.ip,
  107. { publicAccessLevel: req.body.publicAccessLevel, status: 'OK' }
  108. )
  109. res.sendStatus(204)
  110. } else {
  111. res.sendStatus(500)
  112. }
  113. },
  114. async deleteProject(req, res) {
  115. const projectId = req.params.Project_id
  116. const user = SessionManager.getSessionUser(req.session)
  117. await ProjectDeleter.promises.deleteProject(projectId, {
  118. deleterUser: user,
  119. ipAddress: req.ip,
  120. })
  121. res.sendStatus(200)
  122. },
  123. async archiveProject(req, res) {
  124. const projectId = req.params.Project_id
  125. const userId = SessionManager.getLoggedInUserId(req.session)
  126. await ProjectDeleter.promises.archiveProject(projectId, userId)
  127. res.sendStatus(200)
  128. },
  129. async unarchiveProject(req, res) {
  130. const projectId = req.params.Project_id
  131. const userId = SessionManager.getLoggedInUserId(req.session)
  132. await ProjectDeleter.promises.unarchiveProject(projectId, userId)
  133. res.sendStatus(200)
  134. },
  135. async trashProject(req, res) {
  136. const projectId = req.params.project_id
  137. const userId = SessionManager.getLoggedInUserId(req.session)
  138. await ProjectDeleter.promises.trashProject(projectId, userId)
  139. res.sendStatus(200)
  140. },
  141. async untrashProject(req, res) {
  142. const projectId = req.params.project_id
  143. const userId = SessionManager.getLoggedInUserId(req.session)
  144. await ProjectDeleter.promises.untrashProject(projectId, userId)
  145. res.sendStatus(200)
  146. },
  147. async expireDeletedProjectsAfterDuration(_req, res) {
  148. await ProjectDeleter.promises.expireDeletedProjectsAfterDuration()
  149. res.sendStatus(200)
  150. },
  151. async expireDeletedProject(req, res) {
  152. const { projectId } = req.params
  153. await ProjectDeleter.promises.expireDeletedProject(projectId)
  154. res.sendStatus(200)
  155. },
  156. async restoreProject(req, res) {
  157. const projectId = req.params.Project_id
  158. await ProjectDeleter.promises.restoreProject(projectId)
  159. res.sendStatus(200)
  160. },
  161. async cloneProject(req, res, next) {
  162. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  163. metrics.inc('cloned-project')
  164. const projectId = req.params.Project_id
  165. const { projectName, tags } = req.body
  166. logger.debug({ projectId, projectName }, 'cloning project')
  167. if (!SessionManager.isUserLoggedIn(req.session)) {
  168. return res.json({ redir: '/register' })
  169. }
  170. const currentUser = SessionManager.getSessionUser(req.session)
  171. const { first_name: firstName, last_name: lastName, email } = currentUser
  172. try {
  173. const project = await ProjectDuplicator.promises.duplicate(
  174. currentUser,
  175. projectId,
  176. projectName,
  177. tags
  178. )
  179. res.json({
  180. name: project.name,
  181. lastUpdated: project.lastUpdated,
  182. project_id: project._id,
  183. owner_ref: project.owner_ref,
  184. owner: {
  185. first_name: firstName,
  186. last_name: lastName,
  187. email,
  188. _id: currentUser._id,
  189. },
  190. })
  191. } catch (err) {
  192. OError.tag(err, 'error cloning project', {
  193. projectId,
  194. userId: currentUser._id,
  195. })
  196. return next(err)
  197. }
  198. },
  199. async newProject(req, res) {
  200. const currentUser = SessionManager.getSessionUser(req.session)
  201. const {
  202. first_name: firstName,
  203. last_name: lastName,
  204. email,
  205. _id: userId,
  206. } = currentUser
  207. const projectName =
  208. req.body.projectName != null ? req.body.projectName.trim() : undefined
  209. const { template } = req.body
  210. const project = await (template === 'example'
  211. ? ProjectCreationHandler.promises.createExampleProject(
  212. userId,
  213. projectName
  214. )
  215. : ProjectCreationHandler.promises.createBasicProject(userId, projectName))
  216. res.json({
  217. project_id: project._id,
  218. owner_ref: project.owner_ref,
  219. owner: {
  220. first_name: firstName,
  221. last_name: lastName,
  222. email,
  223. _id: userId,
  224. },
  225. })
  226. },
  227. async renameProject(req, res) {
  228. const projectId = req.params.Project_id
  229. const newName = req.body.newProjectName
  230. await EditorController.promises.renameProject(projectId, newName)
  231. res.sendStatus(200)
  232. },
  233. async userProjectsJson(req, res) {
  234. const userId = SessionManager.getLoggedInUserId(req.session)
  235. let projects = await ProjectGetter.promises.findAllUsersProjects(
  236. userId,
  237. 'name lastUpdated publicAccesLevel archived trashed owner_ref'
  238. )
  239. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  240. projects = ProjectController._buildProjectList(projects, userId)
  241. .filter(p => !(p.archived || p.trashed))
  242. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  243. res.json({ projects })
  244. },
  245. async projectEntitiesJson(req, res) {
  246. const projectId = req.params.Project_id
  247. const project = await ProjectGetter.promises.getProject(projectId)
  248. const { docs, files } =
  249. ProjectEntityHandler.getAllEntitiesFromProject(project)
  250. const entities = docs
  251. .concat(files)
  252. // Sort by path ascending
  253. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  254. .map(e => ({
  255. path: e.path,
  256. type: e.doc != null ? 'doc' : 'file',
  257. }))
  258. res.json({ project_id: projectId, entities })
  259. },
  260. async loadEditor(req, res, next) {
  261. const timer = new metrics.Timer('load-editor')
  262. if (!Settings.editorIsOpen) {
  263. return res.render('general/closed', { title: 'updating_site' })
  264. }
  265. let anonymous, userId, sessionUser
  266. if (SessionManager.isUserLoggedIn(req.session)) {
  267. sessionUser = SessionManager.getSessionUser(req.session)
  268. userId = SessionManager.getLoggedInUserId(req.session)
  269. anonymous = false
  270. } else {
  271. sessionUser = null
  272. anonymous = true
  273. userId = null
  274. }
  275. const projectId = req.params.Project_id
  276. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  277. function shouldDisplayFeature(name, variantFlag) {
  278. if (req.query && req.query[name]) {
  279. return req.query[name] === 'true'
  280. } else {
  281. return variantFlag === true
  282. }
  283. }
  284. try {
  285. const splitTests = [
  286. !anonymous && 'bib-file-tpr-prompt',
  287. 'compile-log-events',
  288. 'ide-page',
  289. 'null-test-share-modal',
  290. 'paywall-cta',
  291. 'pdf-caching-cached-url-lookup',
  292. 'pdf-caching-mode',
  293. 'pdf-caching-prefetch-large',
  294. 'pdf-caching-prefetching',
  295. 'pdf-controls',
  296. 'pdfjs-40',
  297. 'personal-access-token',
  298. 'revert-file',
  299. 'table-generator-promotion',
  300. 'track-pdf-download',
  301. !anonymous && 'writefull-oauth-promotion',
  302. 'ieee-stylesheet',
  303. ].filter(Boolean)
  304. const responses = await pProps(
  305. _.mapValues(
  306. {
  307. splitTestAssignments: async () => {
  308. const assignments = {}
  309. await Promise.all(
  310. splitTests.map(async splitTest => {
  311. assignments[splitTest] =
  312. await SplitTestHandler.promises.getAssignment(
  313. req,
  314. res,
  315. splitTest
  316. )
  317. })
  318. )
  319. return assignments
  320. },
  321. project: () =>
  322. ProjectGetter.promises.getProject(projectId, {
  323. name: 1,
  324. lastUpdated: 1,
  325. track_changes: 1,
  326. owner_ref: 1,
  327. brandVariationId: 1,
  328. overleaf: 1,
  329. tokens: 1,
  330. }),
  331. user: async () => {
  332. if (!userId) {
  333. SplitTestSessionHandler.promises
  334. .sessionMaintenance(req, null)
  335. .catch(err => {
  336. logger.error(
  337. { err },
  338. 'failed to update split test info in session'
  339. )
  340. })
  341. return defaultSettingsForAnonymousUser(userId)
  342. } else {
  343. User.updateOne(
  344. { _id: new ObjectId(userId) },
  345. { $set: { lastActive: new Date() } }
  346. )
  347. .exec()
  348. .catch(err => {
  349. logger.error(
  350. { err, userId },
  351. 'failed to update lastActive for user'
  352. )
  353. })
  354. const user = await User.findById(
  355. userId,
  356. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram completedTutorials writefull'
  357. ).exec()
  358. // Handle case of deleted user
  359. if (!user) {
  360. UserController.logout(req, res, next)
  361. return
  362. }
  363. logger.debug({ projectId, userId }, 'got user')
  364. SplitTestSessionHandler.promises
  365. .sessionMaintenance(req, user)
  366. .catch(err => {
  367. logger.error(
  368. { err },
  369. 'failed to update split test info in session'
  370. )
  371. })
  372. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  373. return user
  374. }
  375. return await ProjectController._refreshFeatures(req, user)
  376. }
  377. },
  378. userHasInstitutionLicence: async () => {
  379. if (!userId) {
  380. return false
  381. }
  382. try {
  383. return await InstitutionsFeatures.promises.hasLicence(userId)
  384. } catch {
  385. // Don't fail if we can't get affiliation licences
  386. return false
  387. }
  388. },
  389. learnedWords() {
  390. if (!userId) {
  391. return []
  392. }
  393. return SpellingHandler.promises.getUserDictionary(userId)
  394. },
  395. subscription() {
  396. if (!userId) {
  397. return
  398. }
  399. return SubscriptionLocator.promises.getUsersSubscription(userId)
  400. },
  401. userIsMemberOfGroupSubscription() {
  402. if (!sessionUser) {
  403. return false
  404. }
  405. return LimitationsManager.promises.userIsMemberOfGroupSubscription(
  406. sessionUser
  407. )
  408. },
  409. activate() {
  410. return InactiveProjectManager.promises.reactivateProjectIfRequired(
  411. projectId
  412. )
  413. },
  414. markAsOpened() {
  415. // don't need to wait for this to complete
  416. ProjectUpdateHandler.promises
  417. .markAsOpened(projectId)
  418. .catch(err => {
  419. logger.error(
  420. { err, projectId },
  421. 'failed to mark project as opened'
  422. )
  423. })
  424. },
  425. isTokenMember() {
  426. if (!userId) {
  427. return
  428. }
  429. return CollaboratorsGetter.promises.userIsTokenMember(
  430. userId,
  431. projectId
  432. )
  433. },
  434. isInvitedMember() {
  435. return CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  436. userId,
  437. projectId
  438. )
  439. },
  440. flushToTpds: () => {
  441. return TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(
  442. projectId
  443. )
  444. },
  445. projectTags() {
  446. if (!userId) {
  447. return []
  448. }
  449. return TagsHandler.promises.getTagsForProject(userId, projectId)
  450. },
  451. },
  452. promise => promise()
  453. )
  454. )
  455. const {
  456. project,
  457. user,
  458. userHasInstitutionLicence,
  459. learnedWords,
  460. subscription,
  461. userIsMemberOfGroupSubscription,
  462. isTokenMember,
  463. isInvitedMember,
  464. splitTestAssignments,
  465. projectTags,
  466. } = responses
  467. const brandVariation = project?.brandVariationId
  468. ? await BrandVariationsHandler.promises.getBrandVariationById(
  469. project.brandVariationId
  470. )
  471. : undefined
  472. const anonRequestToken = TokenAccessHandler.getRequestToken(
  473. req,
  474. projectId
  475. )
  476. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  477. const privilegeLevel =
  478. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  479. userId,
  480. projectId,
  481. anonRequestToken
  482. )
  483. let allowedFreeTrial = true
  484. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  485. return res.sendStatus(401)
  486. }
  487. if (subscription != null) {
  488. allowedFreeTrial = false
  489. }
  490. let wsUrl = Settings.wsUrl
  491. let metricName = 'load-editor-ws'
  492. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  493. wsUrl = Settings.wsUrlBeta
  494. metricName += '-beta'
  495. } else if (
  496. Settings.wsUrlV2 &&
  497. Settings.wsUrlV2Percentage > 0 &&
  498. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  499. Settings.wsUrlV2Percentage
  500. ) {
  501. wsUrl = Settings.wsUrlV2
  502. metricName += '-v2'
  503. }
  504. if (req.query && req.query.ws === 'fallback') {
  505. // `?ws=fallback` will connect to the bare origin, and ignore
  506. // the custom wsUrl. Hence it must load the client side
  507. // javascript from there too.
  508. // Not resetting it here would possibly load a socket.io v2
  509. // client and connect to a v0 endpoint.
  510. wsUrl = undefined
  511. metricName += '-fallback'
  512. }
  513. metrics.inc(metricName)
  514. if (userId) {
  515. AnalyticsManager.recordEventForUserInBackground(
  516. userId,
  517. 'project-opened',
  518. {
  519. projectId: project._id,
  520. }
  521. )
  522. }
  523. const isAdminOrTemplateOwner =
  524. hasAdminAccess(user) || Settings.templates?.user_id === userId
  525. const showTemplatesServerPro =
  526. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  527. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  528. const detachRole = req.params.detachRole
  529. const showSymbolPalette =
  530. !Features.hasFeature('saas') ||
  531. (user.features && user.features.symbolPalette)
  532. // Persistent upgrade prompts
  533. // in header & in share project modal
  534. const showUpgradePrompt =
  535. Features.hasFeature('saas') &&
  536. userId &&
  537. !subscription &&
  538. !userIsMemberOfGroupSubscription &&
  539. !userHasInstitutionLicence
  540. const showPersonalAccessToken =
  541. userId &&
  542. (!Features.hasFeature('saas') ||
  543. req.query?.personal_access_token === 'true')
  544. const optionalPersonalAccessToken =
  545. userId &&
  546. !showPersonalAccessToken &&
  547. splitTestAssignments['personal-access-token'].variant === 'enabled' // `?personal-access-token=enabled`
  548. const idePageReact = splitTestAssignments['ide-page'].variant === 'react'
  549. const template =
  550. detachRole === 'detached'
  551. ? // TODO: Create React version of detached page
  552. 'project/editor_detached'
  553. : idePageReact
  554. ? 'project/ide-react'
  555. : 'project/editor'
  556. res.render(template, {
  557. title: project.name,
  558. priority_title: true,
  559. bodyClasses: ['editor'],
  560. project_id: project._id,
  561. projectName: project.name,
  562. user: {
  563. id: userId,
  564. email: user.email,
  565. first_name: user.first_name,
  566. last_name: user.last_name,
  567. referal_id: user.referal_id,
  568. signUpDate: user.signUpDate,
  569. allowedFreeTrial,
  570. featureSwitches: user.featureSwitches,
  571. features: user.features,
  572. refProviders: _.mapValues(user.refProviders, Boolean),
  573. writefull: {
  574. enabled: Boolean(user.writefull?.enabled),
  575. },
  576. alphaProgram: user.alphaProgram,
  577. betaProgram: user.betaProgram,
  578. labsProgram: user.labsProgram,
  579. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  580. isAdmin: hasAdminAccess(user),
  581. },
  582. userSettings: {
  583. mode: user.ace.mode,
  584. editorTheme: user.ace.theme,
  585. fontSize: user.ace.fontSize,
  586. autoComplete: user.ace.autoComplete,
  587. autoPairDelimiters: user.ace.autoPairDelimiters,
  588. pdfViewer: user.ace.pdfViewer,
  589. syntaxValidation: user.ace.syntaxValidation,
  590. fontFamily: user.ace.fontFamily || 'lucida',
  591. lineHeight: user.ace.lineHeight || 'normal',
  592. overallTheme: user.ace.overallTheme,
  593. },
  594. privilegeLevel,
  595. anonymous,
  596. isTokenMember,
  597. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  598. userId,
  599. privilegeLevel,
  600. isTokenMember,
  601. isInvitedMember
  602. ),
  603. languages: Settings.languages,
  604. learnedWords,
  605. editorThemes: THEME_LIST,
  606. legacyEditorThemes: LEGACY_THEME_LIST,
  607. maxDocLength: Settings.max_doc_length,
  608. brandVariation,
  609. allowedImageNames,
  610. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  611. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  612. wsUrl,
  613. showSupport: Features.hasFeature('support'),
  614. showTemplatesServerPro,
  615. pdfjsVariant: splitTestAssignments['pdfjs-40'].variant,
  616. debugPdfDetach,
  617. showSymbolPalette,
  618. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  619. detachRole,
  620. metadata: { viewport: false },
  621. showUpgradePrompt,
  622. fixedSizeDocument: true,
  623. useOpenTelemetry: Settings.useOpenTelemetryClient,
  624. idePageReact,
  625. showPersonalAccessToken,
  626. optionalPersonalAccessToken,
  627. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  628. projectTags,
  629. })
  630. timer.done()
  631. } catch (err) {
  632. OError.tag(err, 'error getting details for project page')
  633. return next(err)
  634. }
  635. },
  636. async _refreshFeatures(req, user) {
  637. // If the feature refresh has failed in this session, don't retry
  638. // it - require the user to log in again.
  639. if (req.session.feature_refresh_failed) {
  640. metrics.inc('features-refresh', 1, {
  641. path: 'load-editor',
  642. status: 'skipped',
  643. })
  644. return user
  645. }
  646. // If the refresh takes too long then return the current
  647. // features. Note that the user.features property may still be
  648. // updated in the background after the promise is resolved.
  649. const abortController = new AbortController()
  650. const refreshTimeoutHandler = async () => {
  651. await setTimeout(5000, { signal: abortController.signal })
  652. req.session.feature_refresh_failed = {
  653. reason: 'timeout',
  654. at: new Date(),
  655. }
  656. metrics.inc('features-refresh', 1, {
  657. path: 'load-editor',
  658. status: 'timeout',
  659. })
  660. return user
  661. }
  662. // try to refresh user features now
  663. const timer = new metrics.Timer('features-refresh-on-load-editor')
  664. return Promise.race([
  665. refreshTimeoutHandler(),
  666. (async () => {
  667. try {
  668. user.features = await FeaturesUpdater.promises.refreshFeatures(
  669. user._id,
  670. 'load-editor'
  671. )
  672. metrics.inc('features-refresh', 1, {
  673. path: 'load-editor',
  674. status: 'success',
  675. })
  676. } catch (err) {
  677. // keep a record to prevent unneceary retries and leave
  678. // the original features unmodified if the refresh failed
  679. req.session.feature_refresh_failed = {
  680. reason: 'error',
  681. at: new Date(),
  682. }
  683. metrics.inc('features-refresh', 1, {
  684. path: 'load-editor',
  685. status: 'error',
  686. })
  687. }
  688. abortController.abort()
  689. timer.done()
  690. return user
  691. })(),
  692. ])
  693. },
  694. _buildProjectList(allProjects, userId) {
  695. let project
  696. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  697. allProjects
  698. const projects = []
  699. for (project of owned) {
  700. projects.push(
  701. ProjectController._buildProjectViewModel(
  702. project,
  703. 'owner',
  704. Sources.OWNER,
  705. userId
  706. )
  707. )
  708. }
  709. // Invite-access
  710. for (project of readAndWrite) {
  711. projects.push(
  712. ProjectController._buildProjectViewModel(
  713. project,
  714. 'readWrite',
  715. Sources.INVITE,
  716. userId
  717. )
  718. )
  719. }
  720. for (project of readOnly) {
  721. projects.push(
  722. ProjectController._buildProjectViewModel(
  723. project,
  724. 'readOnly',
  725. Sources.INVITE,
  726. userId
  727. )
  728. )
  729. }
  730. // Token-access
  731. // Only add these projects if they're not already present, this gives us cascading access
  732. // from 'owner' => 'token-read-only'
  733. for (project of tokenReadAndWrite) {
  734. if (
  735. projects.filter(p => p.id.toString() === project._id.toString())
  736. .length === 0
  737. ) {
  738. projects.push(
  739. ProjectController._buildProjectViewModel(
  740. project,
  741. 'readAndWrite',
  742. Sources.TOKEN,
  743. userId
  744. )
  745. )
  746. }
  747. }
  748. for (project of tokenReadOnly) {
  749. if (
  750. projects.filter(p => p.id.toString() === project._id.toString())
  751. .length === 0
  752. ) {
  753. projects.push(
  754. ProjectController._buildProjectViewModel(
  755. project,
  756. 'readOnly',
  757. Sources.TOKEN,
  758. userId
  759. )
  760. )
  761. }
  762. }
  763. return projects
  764. },
  765. _buildProjectViewModel(project, accessLevel, source, userId) {
  766. const archived = ProjectHelper.isArchived(project, userId)
  767. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  768. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  769. const model = {
  770. id: project._id,
  771. name: project.name,
  772. lastUpdated: project.lastUpdated,
  773. lastUpdatedBy: project.lastUpdatedBy,
  774. publicAccessLevel: project.publicAccesLevel,
  775. accessLevel,
  776. source,
  777. archived,
  778. trashed,
  779. owner_ref: project.owner_ref,
  780. isV1Project: false,
  781. }
  782. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  783. model.owner_ref = null
  784. model.lastUpdatedBy = null
  785. }
  786. return model
  787. },
  788. _buildPortalTemplatesList(affiliations) {
  789. if (affiliations == null) {
  790. affiliations = []
  791. }
  792. const portalTemplates = []
  793. for (const aff of affiliations) {
  794. if (
  795. aff.portal &&
  796. aff.portal.slug &&
  797. aff.portal.templates_count &&
  798. aff.portal.templates_count > 0
  799. ) {
  800. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  801. portalTemplates.push({
  802. name: aff.institution.name,
  803. url: Settings.siteUrl + portalPath + aff.portal.slug,
  804. })
  805. }
  806. }
  807. return portalTemplates
  808. },
  809. }
  810. const defaultSettingsForAnonymousUser = userId => ({
  811. id: userId,
  812. ace: {
  813. mode: 'none',
  814. theme: 'textmate',
  815. fontSize: '12',
  816. autoComplete: true,
  817. spellCheckLanguage: '',
  818. pdfViewer: '',
  819. syntaxValidation: true,
  820. },
  821. subscription: {
  822. freeTrial: {
  823. allowed: true,
  824. },
  825. },
  826. featureSwitches: {
  827. github: false,
  828. },
  829. alphaProgram: false,
  830. betaProgram: false,
  831. writefull: {
  832. enabled: false,
  833. },
  834. })
  835. const THEME_LIST = [
  836. 'cobalt',
  837. 'dracula',
  838. 'eclipse',
  839. 'monokai',
  840. 'overleaf',
  841. 'textmate',
  842. ]
  843. const LEGACY_THEME_LIST = [
  844. 'ambiance',
  845. 'chaos',
  846. 'chrome',
  847. 'clouds',
  848. 'clouds_midnight',
  849. 'crimson_editor',
  850. 'dawn',
  851. 'dreamweaver',
  852. 'github',
  853. 'gob',
  854. 'gruvbox',
  855. 'idle_fingers',
  856. 'iplastic',
  857. 'katzenmilch',
  858. 'kr_theme',
  859. 'kuroir',
  860. 'merbivore',
  861. 'merbivore_soft',
  862. 'mono_industrial',
  863. 'nord_dark',
  864. 'pastel_on_dark',
  865. 'solarized_dark',
  866. 'solarized_light',
  867. 'sqlserver',
  868. 'terminal',
  869. 'tomorrow',
  870. 'tomorrow_night',
  871. 'tomorrow_night_blue',
  872. 'tomorrow_night_bright',
  873. 'tomorrow_night_eighties',
  874. 'twilight',
  875. 'vibrant_ink',
  876. 'xcode',
  877. ]
  878. const ProjectController = {
  879. archiveProject: expressify(_ProjectController.archiveProject),
  880. cloneProject: expressify(_ProjectController.cloneProject),
  881. deleteProject: expressify(_ProjectController.deleteProject),
  882. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  883. expireDeletedProjectsAfterDuration: expressify(
  884. _ProjectController.expireDeletedProjectsAfterDuration
  885. ),
  886. loadEditor: expressify(_ProjectController.loadEditor),
  887. newProject: expressify(_ProjectController.newProject),
  888. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  889. renameProject: expressify(_ProjectController.renameProject),
  890. restoreProject: expressify(_ProjectController.restoreProject),
  891. trashProject: expressify(_ProjectController.trashProject),
  892. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  893. untrashProject: expressify(_ProjectController.untrashProject),
  894. updateProjectAdminSettings: expressify(
  895. _ProjectController.updateProjectAdminSettings
  896. ),
  897. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  898. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  899. _buildProjectList: _ProjectController._buildProjectList,
  900. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  901. _injectProjectUsers: _ProjectController._injectProjectUsers,
  902. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  903. _refreshFeatures: _ProjectController._refreshFeatures,
  904. }
  905. module.exports = ProjectController