ProjectController.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. ].filter(Boolean)
  303. const responses = await pProps(
  304. _.mapValues(
  305. {
  306. splitTestAssignments: async () => {
  307. const assignments = {}
  308. await Promise.all(
  309. splitTests.map(async splitTest => {
  310. assignments[splitTest] =
  311. await SplitTestHandler.promises.getAssignment(
  312. req,
  313. res,
  314. splitTest
  315. )
  316. })
  317. )
  318. return assignments
  319. },
  320. project: () =>
  321. ProjectGetter.promises.getProject(projectId, {
  322. name: 1,
  323. lastUpdated: 1,
  324. track_changes: 1,
  325. owner_ref: 1,
  326. brandVariationId: 1,
  327. overleaf: 1,
  328. tokens: 1,
  329. }),
  330. user: async () => {
  331. if (!userId) {
  332. SplitTestSessionHandler.promises
  333. .sessionMaintenance(req, null)
  334. .catch(err => {
  335. logger.error(
  336. { err },
  337. 'failed to update split test info in session'
  338. )
  339. })
  340. return defaultSettingsForAnonymousUser(userId)
  341. } else {
  342. User.updateOne(
  343. { _id: new ObjectId(userId) },
  344. { $set: { lastActive: new Date() } }
  345. )
  346. .exec()
  347. .catch(err => {
  348. logger.error(
  349. { err, userId },
  350. 'failed to update lastActive for user'
  351. )
  352. })
  353. const user = await User.findById(
  354. userId,
  355. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram completedTutorials writefull'
  356. ).exec()
  357. // Handle case of deleted user
  358. if (!user) {
  359. UserController.logout(req, res, next)
  360. return
  361. }
  362. logger.debug({ projectId, userId }, 'got user')
  363. SplitTestSessionHandler.promises
  364. .sessionMaintenance(req, user)
  365. .catch(err => {
  366. logger.error(
  367. { err },
  368. 'failed to update split test info in session'
  369. )
  370. })
  371. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  372. return user
  373. }
  374. return await ProjectController._refreshFeatures(req, user)
  375. }
  376. },
  377. userHasInstitutionLicence: async () => {
  378. if (!userId) {
  379. return false
  380. }
  381. try {
  382. return await InstitutionsFeatures.promises.hasLicence(userId)
  383. } catch {
  384. // Don't fail if we can't get affiliation licences
  385. return false
  386. }
  387. },
  388. learnedWords() {
  389. if (!userId) {
  390. return []
  391. }
  392. return SpellingHandler.promises.getUserDictionary(userId)
  393. },
  394. subscription() {
  395. if (!userId) {
  396. return
  397. }
  398. return SubscriptionLocator.promises.getUsersSubscription(userId)
  399. },
  400. userIsMemberOfGroupSubscription() {
  401. if (!sessionUser) {
  402. return false
  403. }
  404. return LimitationsManager.promises.userIsMemberOfGroupSubscription(
  405. sessionUser
  406. )
  407. },
  408. activate() {
  409. return InactiveProjectManager.promises.reactivateProjectIfRequired(
  410. projectId
  411. )
  412. },
  413. markAsOpened() {
  414. // don't need to wait for this to complete
  415. ProjectUpdateHandler.promises
  416. .markAsOpened(projectId)
  417. .catch(err => {
  418. logger.error(
  419. { err, projectId },
  420. 'failed to mark project as opened'
  421. )
  422. })
  423. },
  424. isTokenMember() {
  425. if (!userId) {
  426. return
  427. }
  428. return CollaboratorsGetter.promises.userIsTokenMember(
  429. userId,
  430. projectId
  431. )
  432. },
  433. isInvitedMember() {
  434. return CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  435. userId,
  436. projectId
  437. )
  438. },
  439. flushToTpds: () => {
  440. return TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(
  441. projectId
  442. )
  443. },
  444. projectTags() {
  445. if (!userId) {
  446. return []
  447. }
  448. return TagsHandler.promises.getTagsForProject(userId, projectId)
  449. },
  450. },
  451. promise => promise()
  452. )
  453. )
  454. const {
  455. project,
  456. user,
  457. userHasInstitutionLicence,
  458. learnedWords,
  459. subscription,
  460. userIsMemberOfGroupSubscription,
  461. isTokenMember,
  462. isInvitedMember,
  463. splitTestAssignments,
  464. projectTags,
  465. } = responses
  466. const brandVariation = project?.brandVariationId
  467. ? await BrandVariationsHandler.promises.getBrandVariationById(
  468. project.brandVariationId
  469. )
  470. : undefined
  471. const anonRequestToken = TokenAccessHandler.getRequestToken(
  472. req,
  473. projectId
  474. )
  475. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  476. const privilegeLevel =
  477. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  478. userId,
  479. projectId,
  480. anonRequestToken
  481. )
  482. let allowedFreeTrial = true
  483. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  484. return res.sendStatus(401)
  485. }
  486. if (subscription != null) {
  487. allowedFreeTrial = false
  488. }
  489. let wsUrl = Settings.wsUrl
  490. let metricName = 'load-editor-ws'
  491. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  492. wsUrl = Settings.wsUrlBeta
  493. metricName += '-beta'
  494. } else if (
  495. Settings.wsUrlV2 &&
  496. Settings.wsUrlV2Percentage > 0 &&
  497. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  498. Settings.wsUrlV2Percentage
  499. ) {
  500. wsUrl = Settings.wsUrlV2
  501. metricName += '-v2'
  502. }
  503. if (req.query && req.query.ws === 'fallback') {
  504. // `?ws=fallback` will connect to the bare origin, and ignore
  505. // the custom wsUrl. Hence it must load the client side
  506. // javascript from there too.
  507. // Not resetting it here would possibly load a socket.io v2
  508. // client and connect to a v0 endpoint.
  509. wsUrl = undefined
  510. metricName += '-fallback'
  511. }
  512. metrics.inc(metricName)
  513. if (userId) {
  514. AnalyticsManager.recordEventForUserInBackground(
  515. userId,
  516. 'project-opened',
  517. {
  518. projectId: project._id,
  519. }
  520. )
  521. }
  522. const isAdminOrTemplateOwner =
  523. hasAdminAccess(user) || Settings.templates?.user_id === userId
  524. const showTemplatesServerPro =
  525. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  526. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  527. const detachRole = req.params.detachRole
  528. const showSymbolPalette =
  529. !Features.hasFeature('saas') ||
  530. (user.features && user.features.symbolPalette)
  531. // Persistent upgrade prompts
  532. // in header & in share project modal
  533. const showUpgradePrompt =
  534. Features.hasFeature('saas') &&
  535. userId &&
  536. !subscription &&
  537. !userIsMemberOfGroupSubscription &&
  538. !userHasInstitutionLicence
  539. const showPersonalAccessToken =
  540. userId &&
  541. (!Features.hasFeature('saas') ||
  542. req.query?.personal_access_token === 'true')
  543. const optionalPersonalAccessToken =
  544. userId &&
  545. !showPersonalAccessToken &&
  546. splitTestAssignments['personal-access-token'].variant === 'enabled' // `?personal-access-token=enabled`
  547. const idePageReact = splitTestAssignments['ide-page'].variant === 'react'
  548. const template =
  549. detachRole === 'detached'
  550. ? // TODO: Create React version of detached page
  551. 'project/editor_detached'
  552. : idePageReact
  553. ? 'project/ide-react'
  554. : 'project/editor'
  555. res.render(template, {
  556. title: project.name,
  557. priority_title: true,
  558. bodyClasses: ['editor'],
  559. project_id: project._id,
  560. projectName: project.name,
  561. user: {
  562. id: userId,
  563. email: user.email,
  564. first_name: user.first_name,
  565. last_name: user.last_name,
  566. referal_id: user.referal_id,
  567. signUpDate: user.signUpDate,
  568. allowedFreeTrial,
  569. featureSwitches: user.featureSwitches,
  570. features: user.features,
  571. refProviders: _.mapValues(user.refProviders, Boolean),
  572. writefull: {
  573. enabled: Boolean(user.writefull?.enabled),
  574. },
  575. alphaProgram: user.alphaProgram,
  576. betaProgram: user.betaProgram,
  577. labsProgram: user.labsProgram,
  578. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  579. isAdmin: hasAdminAccess(user),
  580. },
  581. userSettings: {
  582. mode: user.ace.mode,
  583. editorTheme: user.ace.theme,
  584. fontSize: user.ace.fontSize,
  585. autoComplete: user.ace.autoComplete,
  586. autoPairDelimiters: user.ace.autoPairDelimiters,
  587. pdfViewer: user.ace.pdfViewer,
  588. syntaxValidation: user.ace.syntaxValidation,
  589. fontFamily: user.ace.fontFamily || 'lucida',
  590. lineHeight: user.ace.lineHeight || 'normal',
  591. overallTheme: user.ace.overallTheme,
  592. },
  593. privilegeLevel,
  594. anonymous,
  595. isTokenMember,
  596. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  597. userId,
  598. privilegeLevel,
  599. isTokenMember,
  600. isInvitedMember
  601. ),
  602. languages: Settings.languages,
  603. learnedWords,
  604. editorThemes: THEME_LIST,
  605. legacyEditorThemes: LEGACY_THEME_LIST,
  606. maxDocLength: Settings.max_doc_length,
  607. brandVariation,
  608. allowedImageNames,
  609. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  610. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  611. wsUrl,
  612. showSupport: Features.hasFeature('support'),
  613. showTemplatesServerPro,
  614. pdfjsVariant: splitTestAssignments['pdfjs-40'].variant,
  615. debugPdfDetach,
  616. showSymbolPalette,
  617. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  618. detachRole,
  619. metadata: { viewport: false },
  620. showUpgradePrompt,
  621. fixedSizeDocument: true,
  622. useOpenTelemetry: Settings.useOpenTelemetryClient,
  623. idePageReact,
  624. showPersonalAccessToken,
  625. optionalPersonalAccessToken,
  626. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  627. projectTags,
  628. })
  629. timer.done()
  630. } catch (err) {
  631. OError.tag(err, 'error getting details for project page')
  632. return next(err)
  633. }
  634. },
  635. async _refreshFeatures(req, user) {
  636. // If the feature refresh has failed in this session, don't retry
  637. // it - require the user to log in again.
  638. if (req.session.feature_refresh_failed) {
  639. metrics.inc('features-refresh', 1, {
  640. path: 'load-editor',
  641. status: 'skipped',
  642. })
  643. return user
  644. }
  645. // If the refresh takes too long then return the current
  646. // features. Note that the user.features property may still be
  647. // updated in the background after the promise is resolved.
  648. const abortController = new AbortController()
  649. const refreshTimeoutHandler = async () => {
  650. await setTimeout(5000, { signal: abortController.signal })
  651. req.session.feature_refresh_failed = {
  652. reason: 'timeout',
  653. at: new Date(),
  654. }
  655. metrics.inc('features-refresh', 1, {
  656. path: 'load-editor',
  657. status: 'timeout',
  658. })
  659. return user
  660. }
  661. // try to refresh user features now
  662. const timer = new metrics.Timer('features-refresh-on-load-editor')
  663. return Promise.race([
  664. refreshTimeoutHandler(),
  665. (async () => {
  666. try {
  667. user.features = await FeaturesUpdater.promises.refreshFeatures(
  668. user._id,
  669. 'load-editor'
  670. )
  671. metrics.inc('features-refresh', 1, {
  672. path: 'load-editor',
  673. status: 'success',
  674. })
  675. } catch (err) {
  676. // keep a record to prevent unneceary retries and leave
  677. // the original features unmodified if the refresh failed
  678. req.session.feature_refresh_failed = {
  679. reason: 'error',
  680. at: new Date(),
  681. }
  682. metrics.inc('features-refresh', 1, {
  683. path: 'load-editor',
  684. status: 'error',
  685. })
  686. }
  687. abortController.abort()
  688. timer.done()
  689. return user
  690. })(),
  691. ])
  692. },
  693. _buildProjectList(allProjects, userId) {
  694. let project
  695. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  696. allProjects
  697. const projects = []
  698. for (project of owned) {
  699. projects.push(
  700. ProjectController._buildProjectViewModel(
  701. project,
  702. 'owner',
  703. Sources.OWNER,
  704. userId
  705. )
  706. )
  707. }
  708. // Invite-access
  709. for (project of readAndWrite) {
  710. projects.push(
  711. ProjectController._buildProjectViewModel(
  712. project,
  713. 'readWrite',
  714. Sources.INVITE,
  715. userId
  716. )
  717. )
  718. }
  719. for (project of readOnly) {
  720. projects.push(
  721. ProjectController._buildProjectViewModel(
  722. project,
  723. 'readOnly',
  724. Sources.INVITE,
  725. userId
  726. )
  727. )
  728. }
  729. // Token-access
  730. // Only add these projects if they're not already present, this gives us cascading access
  731. // from 'owner' => 'token-read-only'
  732. for (project of tokenReadAndWrite) {
  733. if (
  734. projects.filter(p => p.id.toString() === project._id.toString())
  735. .length === 0
  736. ) {
  737. projects.push(
  738. ProjectController._buildProjectViewModel(
  739. project,
  740. 'readAndWrite',
  741. Sources.TOKEN,
  742. userId
  743. )
  744. )
  745. }
  746. }
  747. for (project of tokenReadOnly) {
  748. if (
  749. projects.filter(p => p.id.toString() === project._id.toString())
  750. .length === 0
  751. ) {
  752. projects.push(
  753. ProjectController._buildProjectViewModel(
  754. project,
  755. 'readOnly',
  756. Sources.TOKEN,
  757. userId
  758. )
  759. )
  760. }
  761. }
  762. return projects
  763. },
  764. _buildProjectViewModel(project, accessLevel, source, userId) {
  765. const archived = ProjectHelper.isArchived(project, userId)
  766. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  767. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  768. const model = {
  769. id: project._id,
  770. name: project.name,
  771. lastUpdated: project.lastUpdated,
  772. lastUpdatedBy: project.lastUpdatedBy,
  773. publicAccessLevel: project.publicAccesLevel,
  774. accessLevel,
  775. source,
  776. archived,
  777. trashed,
  778. owner_ref: project.owner_ref,
  779. isV1Project: false,
  780. }
  781. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  782. model.owner_ref = null
  783. model.lastUpdatedBy = null
  784. }
  785. return model
  786. },
  787. _buildPortalTemplatesList(affiliations) {
  788. if (affiliations == null) {
  789. affiliations = []
  790. }
  791. const portalTemplates = []
  792. for (const aff of affiliations) {
  793. if (
  794. aff.portal &&
  795. aff.portal.slug &&
  796. aff.portal.templates_count &&
  797. aff.portal.templates_count > 0
  798. ) {
  799. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  800. portalTemplates.push({
  801. name: aff.institution.name,
  802. url: Settings.siteUrl + portalPath + aff.portal.slug,
  803. })
  804. }
  805. }
  806. return portalTemplates
  807. },
  808. }
  809. const defaultSettingsForAnonymousUser = userId => ({
  810. id: userId,
  811. ace: {
  812. mode: 'none',
  813. theme: 'textmate',
  814. fontSize: '12',
  815. autoComplete: true,
  816. spellCheckLanguage: '',
  817. pdfViewer: '',
  818. syntaxValidation: true,
  819. },
  820. subscription: {
  821. freeTrial: {
  822. allowed: true,
  823. },
  824. },
  825. featureSwitches: {
  826. github: false,
  827. },
  828. alphaProgram: false,
  829. betaProgram: false,
  830. writefull: {
  831. enabled: false,
  832. },
  833. })
  834. const THEME_LIST = [
  835. 'cobalt',
  836. 'dracula',
  837. 'eclipse',
  838. 'monokai',
  839. 'overleaf',
  840. 'textmate',
  841. ]
  842. const LEGACY_THEME_LIST = [
  843. 'ambiance',
  844. 'chaos',
  845. 'chrome',
  846. 'clouds',
  847. 'clouds_midnight',
  848. 'crimson_editor',
  849. 'dawn',
  850. 'dreamweaver',
  851. 'github',
  852. 'gob',
  853. 'gruvbox',
  854. 'idle_fingers',
  855. 'iplastic',
  856. 'katzenmilch',
  857. 'kr_theme',
  858. 'kuroir',
  859. 'merbivore',
  860. 'merbivore_soft',
  861. 'mono_industrial',
  862. 'nord_dark',
  863. 'pastel_on_dark',
  864. 'solarized_dark',
  865. 'solarized_light',
  866. 'sqlserver',
  867. 'terminal',
  868. 'tomorrow',
  869. 'tomorrow_night',
  870. 'tomorrow_night_blue',
  871. 'tomorrow_night_bright',
  872. 'tomorrow_night_eighties',
  873. 'twilight',
  874. 'vibrant_ink',
  875. 'xcode',
  876. ]
  877. const ProjectController = {
  878. archiveProject: expressify(_ProjectController.archiveProject),
  879. cloneProject: expressify(_ProjectController.cloneProject),
  880. deleteProject: expressify(_ProjectController.deleteProject),
  881. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  882. expireDeletedProjectsAfterDuration: expressify(
  883. _ProjectController.expireDeletedProjectsAfterDuration
  884. ),
  885. loadEditor: expressify(_ProjectController.loadEditor),
  886. newProject: expressify(_ProjectController.newProject),
  887. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  888. renameProject: expressify(_ProjectController.renameProject),
  889. restoreProject: expressify(_ProjectController.restoreProject),
  890. trashProject: expressify(_ProjectController.trashProject),
  891. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  892. untrashProject: expressify(_ProjectController.untrashProject),
  893. updateProjectAdminSettings: expressify(
  894. _ProjectController.updateProjectAdminSettings
  895. ),
  896. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  897. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  898. _buildProjectList: _ProjectController._buildProjectList,
  899. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  900. _injectProjectUsers: _ProjectController._injectProjectUsers,
  901. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  902. _refreshFeatures: _ProjectController._refreshFeatures,
  903. }
  904. module.exports = ProjectController