ProjectListController.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. // @ts-check
  2. import _ from 'lodash'
  3. import moment from 'moment'
  4. import Metrics from '@overleaf/metrics'
  5. import Settings from '@overleaf/settings'
  6. import ProjectHelper from './ProjectHelper.js'
  7. import ProjectGetter from './ProjectGetter.js'
  8. import PrivilegeLevels from '../Authorization/PrivilegeLevels.js'
  9. import SessionManager from '../Authentication/SessionManager.js'
  10. import Sources from '../Authorization/Sources.js'
  11. import UserGetter from '../User/UserGetter.js'
  12. import SurveyHandler from '../Survey/SurveyHandler.mjs'
  13. import TagsHandler from '../Tags/TagsHandler.js'
  14. import { expressify } from '@overleaf/promise-utils'
  15. import logger from '@overleaf/logger'
  16. import Features from '../../infrastructure/Features.js'
  17. import SubscriptionViewModelBuilder from '../Subscription/SubscriptionViewModelBuilder.mjs'
  18. import NotificationsHandler from '../Notifications/NotificationsHandler.js'
  19. import Modules from '../../infrastructure/Modules.js'
  20. import { OError, V1ConnectionError } from '../Errors/Errors.js'
  21. import { User } from '../../models/User.js'
  22. import UserPrimaryEmailCheckHandler from '../User/UserPrimaryEmailCheckHandler.mjs'
  23. import UserController from '../User/UserController.mjs'
  24. import NotificationsBuilder from '../Notifications/NotificationsBuilder.js'
  25. import GeoIpLookup from '../../infrastructure/GeoIpLookup.mjs'
  26. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  27. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.js'
  28. import TutorialHandler from '../Tutorial/TutorialHandler.mjs'
  29. import SubscriptionHelper from '../Subscription/SubscriptionHelper.js'
  30. import PermissionsManager from '../Authorization/PermissionsManager.mjs'
  31. import AnalyticsManager from '../Analytics/AnalyticsManager.js'
  32. import { OnboardingDataCollection } from '../../models/OnboardingDataCollection.js'
  33. /**
  34. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject, FormattedProject, MongoTag } from "./types"
  35. * @import { Project, ProjectApi, ProjectAccessLevel, Filters, Page, Sort, UserRef } from "../../../../types/project/dashboard/api"
  36. * @import { Affiliation } from "../../../../types/affiliation"
  37. * @import { Source } from "../Authorization/types"
  38. */
  39. /**
  40. * @param {Affiliation} affiliation
  41. * @param session
  42. * @param linkedInstitutionIds
  43. * @returns {boolean}
  44. * @private
  45. */
  46. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  47. if (!affiliation.institution) return false
  48. // institution.confirmed is for the domain being confirmed, not the email
  49. // Do not show SSO UI for unconfirmed domains
  50. if (!affiliation.institution.confirmed) return false
  51. // If ssoEnabled = true and group.domainCaptureEnabled = true
  52. // then Commons is migrating to group subscription and we do not want to prompt
  53. // linking through Commons SSO
  54. if (affiliation?.group?.domainCaptureEnabled) return false
  55. // Could have multiple emails at the same institution, and if any are
  56. // linked to the institution then do not show notification for others
  57. if (
  58. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  59. ) {
  60. if (affiliation.institution.ssoEnabled) return true
  61. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  62. return false
  63. }
  64. return false
  65. }
  66. /**
  67. * @param {Affiliation[]} affiliations
  68. * @returns {Array<{ name: string, url: string }>}
  69. */
  70. const _buildPortalTemplatesList = affiliations => {
  71. if (affiliations == null) {
  72. affiliations = []
  73. }
  74. const portalTemplates = []
  75. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  76. for (const aff of uniqueAffiliations) {
  77. const hasSlug = aff.portal?.slug
  78. const hasTemplates = (aff.portal?.templates_count || 0) > 0
  79. if (hasSlug && hasTemplates) {
  80. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  81. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  82. portalTemplates.push({
  83. name: aff.institution.name,
  84. url: portalTemplateURL,
  85. })
  86. }
  87. }
  88. return portalTemplates
  89. }
  90. function cleanupSession(req) {
  91. // cleanup redirects at the end of the redirect chain
  92. delete req.session.postCheckoutRedirect
  93. delete req.session.postLoginRedirect
  94. delete req.session.postOnboardingRedirect
  95. // cleanup details from register page
  96. delete req.session.sharedProjectData
  97. delete req.session.templateData
  98. }
  99. /**
  100. * @param {import("express").Request} req
  101. * @param {import("express").Response} res
  102. * @param {import("express").NextFunction} next
  103. * @returns {Promise<void>}
  104. */
  105. async function projectListPage(req, res, next) {
  106. cleanupSession(req)
  107. // can have two values:
  108. // - undefined - when there's no "saas" feature or couldn't get subscription data
  109. // - object - the subscription data object
  110. let usersBestSubscription
  111. let usersIndividualSubscription
  112. let usersGroupSubscriptions = []
  113. let survey
  114. let userIsMemberOfGroupSubscription = false
  115. let groupSubscriptionsPendingEnrollment = []
  116. const isSaas = Features.hasFeature('saas')
  117. const userId = SessionManager.getLoggedInUserId(req.session)
  118. if (isSaas) {
  119. const { variant: domainCaptureRedirect } =
  120. await SplitTestHandler.promises.getAssignment(
  121. req,
  122. res,
  123. 'domain-capture-redirect'
  124. )
  125. if (domainCaptureRedirect === 'enabled') {
  126. const subscription = (
  127. await Modules.promises.hooks.fire(
  128. 'findDomainCaptureGroupUserCouldBePartOf',
  129. userId
  130. )
  131. )?.[0]
  132. if (subscription) {
  133. if (subscription.managedUsersEnabled) {
  134. return res.redirect('/domain-capture')
  135. } else {
  136. // TODO show notification or anything else
  137. }
  138. }
  139. }
  140. }
  141. const projectsBlobPending = _getProjects(userId).catch(err => {
  142. logger.err({ err, userId }, 'projects listing in background failed')
  143. return undefined
  144. })
  145. const user = await User.findById(
  146. userId,
  147. `email emails features alphaProgram betaProgram lastPrimaryEmailCheck lastActive signUpDate refProviders${
  148. isSaas ? ' enrollment writefull completedTutorials aiErrorAssistant' : ''
  149. }`
  150. )
  151. // Handle case of deleted user
  152. if (user == null) {
  153. UserController.logout(req, res, next)
  154. return
  155. }
  156. user.refProviders = _.mapValues(user.refProviders, Boolean)
  157. if (isSaas) {
  158. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  159. try {
  160. ;({
  161. bestSubscription: usersBestSubscription,
  162. individualSubscription: usersIndividualSubscription,
  163. memberGroupSubscriptions: usersGroupSubscriptions,
  164. } = await SubscriptionViewModelBuilder.promises.getUsersSubscriptionDetails(
  165. { _id: userId }
  166. ))
  167. } catch (error) {
  168. logger.err(
  169. { err: error, userId },
  170. "Failed to get user's best subscription"
  171. )
  172. }
  173. try {
  174. userIsMemberOfGroupSubscription = usersGroupSubscriptions?.length > 0
  175. // TODO use helper function
  176. if (!user.enrollment?.managedBy) {
  177. groupSubscriptionsPendingEnrollment = usersGroupSubscriptions.filter(
  178. subscription =>
  179. subscription.groupPlan && subscription.managedUsersEnabled
  180. )
  181. }
  182. } catch (error) {
  183. logger.error(
  184. { err: error },
  185. 'Failed to check whether user is a member of group subscription'
  186. )
  187. }
  188. try {
  189. survey = await SurveyHandler.promises.getSurvey(userId)
  190. } catch (error) {
  191. logger.err({ err: error, userId }, 'Failed to load the active survey')
  192. }
  193. if (
  194. user &&
  195. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck({
  196. email: user.email,
  197. emails: user.emails,
  198. lastPrimaryEmailCheck: user.lastPrimaryEmailCheck,
  199. signUpDate: user.signUpDate,
  200. })
  201. ) {
  202. return res.redirect('/user/emails/primary-email-check')
  203. }
  204. }
  205. const tags = await TagsHandler.promises.getAllTags(userId)
  206. /** @type {{ list: any[], allInReconfirmNotificationPeriods?: any[], error?: any }} */
  207. let userEmailsData = {
  208. list: [],
  209. }
  210. try {
  211. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  212. if (!Features.hasFeature('affiliations')) {
  213. userEmailsData.list = fullEmails
  214. } else {
  215. try {
  216. const results = await Modules.promises.hooks.fire(
  217. 'allInReconfirmNotificationPeriodsForUser',
  218. fullEmails
  219. )
  220. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  221. userEmailsData = {
  222. list: fullEmails,
  223. allInReconfirmNotificationPeriods,
  224. }
  225. } catch (error) {
  226. userEmailsData.error = error
  227. }
  228. }
  229. } catch (error) {
  230. if (!(error instanceof V1ConnectionError)) {
  231. logger.error({ err: error, userId }, 'Failed to get user full emails')
  232. }
  233. }
  234. const userEmails = userEmailsData.list || []
  235. const userAffiliations = userEmails
  236. .filter(emailData => !!emailData.affiliation)
  237. .map(emailData => {
  238. const result = emailData.affiliation
  239. result.email = emailData.email
  240. return result
  241. })
  242. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  243. const { allInReconfirmNotificationPeriods } = userEmailsData
  244. const notifications =
  245. await NotificationsHandler.promises.getUserNotifications(userId)
  246. for (const notification of notifications) {
  247. notification.html = req.i18n.translate(
  248. notification.templateKey,
  249. notification.messageOpts
  250. )
  251. }
  252. const notificationsInstitution = []
  253. // Institution and group SSO Notifications
  254. let groupSsoSetupSuccess
  255. let viaDomainCapture
  256. let joinedGroupName = ''
  257. let reconfirmedViaSAML
  258. if (Features.hasFeature('saml')) {
  259. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  260. const samlSession = req.session.saml
  261. // Notification: SSO Available
  262. const linkedInstitutionIds = []
  263. userEmails.forEach(email => {
  264. if (email.samlProviderId) {
  265. linkedInstitutionIds.push(email.samlProviderId)
  266. }
  267. })
  268. if (Array.isArray(userAffiliations)) {
  269. userAffiliations.forEach(affiliation => {
  270. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  271. notificationsInstitution.push({
  272. email: affiliation.email,
  273. institutionId: affiliation.institution.id,
  274. institutionName: affiliation.institution.name,
  275. templateKey: 'notification_institution_sso_available',
  276. })
  277. }
  278. })
  279. }
  280. if (samlSession) {
  281. // Notification institution SSO: After SSO Linked
  282. if (samlSession.linked) {
  283. let templateKey = 'notification_institution_sso_linked'
  284. if (
  285. samlSession.userCreatedViaDomainCapture &&
  286. samlSession.managedUsersEnabled
  287. ) {
  288. templateKey =
  289. 'notification_account_created_via_group_domain_capture_and_managed_users_enabled'
  290. } else if (samlSession.domainCaptureEnabled) {
  291. templateKey = 'notification_group_sso_linked'
  292. }
  293. notificationsInstitution.push({
  294. email: samlSession.institutionEmail,
  295. institutionName:
  296. samlSession.linked.universityName ||
  297. samlSession.linked.providerName,
  298. templateKey,
  299. })
  300. }
  301. // Notification group SSO: After SSO Linked
  302. if (samlSession.linkedGroup) {
  303. groupSsoSetupSuccess = true
  304. viaDomainCapture = samlSession.domainCaptureJoin
  305. joinedGroupName = samlSession.universityName
  306. }
  307. // Notification institution SSO: After SSO Linked or Logging in
  308. // The requested email does not match primary email returned from
  309. // the institution
  310. if (
  311. samlSession.requestedEmail &&
  312. samlSession.emailNonCanonical &&
  313. !samlSession.error
  314. ) {
  315. notificationsInstitution.push({
  316. institutionEmail: samlSession.emailNonCanonical,
  317. requestedEmail: samlSession.requestedEmail,
  318. templateKey: 'notification_institution_sso_non_canonical',
  319. })
  320. }
  321. // Notification institution SSO: Tried to register, but account already existed
  322. // registerIntercept is set before the institution callback.
  323. // institutionEmail is set after institution callback.
  324. // Check for both in case SSO flow was abandoned
  325. if (
  326. samlSession.registerIntercept &&
  327. samlSession.institutionEmail &&
  328. !samlSession.error
  329. ) {
  330. notificationsInstitution.push({
  331. email: samlSession.institutionEmail,
  332. templateKey: 'notification_institution_sso_already_registered',
  333. })
  334. }
  335. // Notification: When there is a session error
  336. if (samlSession.error) {
  337. notificationsInstitution.push({
  338. templateKey: 'notification_institution_sso_error',
  339. error: samlSession.error,
  340. })
  341. }
  342. }
  343. delete req.session.saml
  344. }
  345. const prefetchedProjectsBlob = await projectsBlobPending
  346. Metrics.inc('project-list-prefetch-projects', 1, {
  347. status: prefetchedProjectsBlob ? 'success' : 'error',
  348. })
  349. // in v2 add notifications for matching university IPs
  350. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  351. try {
  352. await NotificationsBuilder.promises
  353. .ipMatcherAffiliation(user._id)
  354. .create(req.ip)
  355. } catch (err) {
  356. logger.error(
  357. { err },
  358. 'failed to create institutional IP match notification'
  359. )
  360. }
  361. }
  362. const hasPaidAffiliation = userAffiliations.some(
  363. affiliation => affiliation.licence && affiliation.licence !== 'free'
  364. )
  365. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  366. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  367. 'getUSGovBanner',
  368. userEmails,
  369. hasPaidAffiliation,
  370. inactiveTutorials
  371. )
  372. const usGovBanner = (usGovBannerHooksResponse &&
  373. usGovBannerHooksResponse[0]) || {
  374. showUSGovBanner: false,
  375. usGovBannerVariant: null,
  376. }
  377. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  378. const isUser30DaysOld = moment.utc().diff(user.signUpDate, 'days') > 30
  379. const showGroupsAndEnterpriseBanner =
  380. Features.hasFeature('saas') &&
  381. !showUSGovBanner &&
  382. !userIsMemberOfGroupSubscription &&
  383. !hasPaidAffiliation &&
  384. !inactiveTutorials.includes('groups-enterprise-banner-repeat') &&
  385. isUser30DaysOld
  386. const groupsAndEnterpriseBannerVariant =
  387. showGroupsAndEnterpriseBanner &&
  388. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  389. let showInrGeoBanner = false
  390. let showBrlGeoBanner = false
  391. let showLATAMBanner = false
  392. let recommendedCurrency
  393. if (
  394. usersBestSubscription?.type === 'free' ||
  395. usersBestSubscription?.type === 'standalone-ai-add-on'
  396. ) {
  397. const { countryCode, currencyCode } =
  398. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  399. if (countryCode === 'IN') {
  400. showInrGeoBanner = true
  401. }
  402. showBrlGeoBanner = countryCode === 'BR'
  403. showLATAMBanner = ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  404. // LATAM Banner needs to know which currency to display
  405. if (showLATAMBanner) {
  406. recommendedCurrency = currencyCode
  407. }
  408. }
  409. let hasIndividualPaidSubscription = false
  410. try {
  411. hasIndividualPaidSubscription =
  412. SubscriptionHelper.isIndividualActivePaidSubscription(
  413. usersIndividualSubscription
  414. )
  415. } catch (error) {
  416. logger.error({ err: error }, 'Failed to get individual subscription')
  417. }
  418. const affiliations = userAffiliations || []
  419. const inEnterpriseCommons = affiliations.some(
  420. affiliation => affiliation.institution?.enterpriseCommons
  421. )
  422. let onboardingDataCollection
  423. let subjectArea
  424. let usedLatex
  425. let primaryOccupation
  426. let role
  427. // customer.io: Premium nudge experiment
  428. // Only do customer-io-trial-conversion assignment for users not in India/China and not in group/commons
  429. let customerIoEnabled = false
  430. const aiBlocked = !(await _canUseAIAssist(user))
  431. const hasAiAssist = await _userHasAIAssist(user)
  432. if (!userIsMemberOfGroupSubscription && !inEnterpriseCommons && isSaas) {
  433. try {
  434. const ip = req.ip
  435. const { countryCode } = await GeoIpLookup.promises.getCurrencyCode(ip)
  436. const excludedCountries = ['IN', 'CN']
  437. if (!excludedCountries.includes(countryCode)) {
  438. const cioAssignment =
  439. await SplitTestHandler.promises.getAssignmentForUser(
  440. userId,
  441. 'customer-io-trial-conversion'
  442. )
  443. if (cioAssignment.variant === 'enabled') {
  444. customerIoEnabled = true
  445. onboardingDataCollection = await OnboardingDataCollection.findById(
  446. userId,
  447. 'subjectArea usedLatex primaryOccupation role'
  448. )
  449. if (onboardingDataCollection) {
  450. subjectArea = onboardingDataCollection.subjectArea
  451. usedLatex = onboardingDataCollection.usedLatex
  452. primaryOccupation = onboardingDataCollection.primaryOccupation
  453. role = onboardingDataCollection.role
  454. }
  455. AnalyticsManager.setUserPropertyForUserInBackground(
  456. userId,
  457. 'customer-io-integration',
  458. true
  459. )
  460. }
  461. }
  462. } catch (err) {
  463. logger.error(
  464. { err },
  465. 'Error checking geo location for customer-io-trial-conversion'
  466. )
  467. // Fallback to not enabled if geoip fails
  468. customerIoEnabled = false
  469. }
  470. }
  471. res.render('project/list-react', {
  472. title: 'your_projects',
  473. usersBestSubscription,
  474. notifications,
  475. notificationsInstitution,
  476. user,
  477. userAffiliations,
  478. userEmails,
  479. reconfirmedViaSAML,
  480. allInReconfirmNotificationPeriods,
  481. survey,
  482. tags,
  483. portalTemplates,
  484. prefetchedProjectsBlob,
  485. showGroupsAndEnterpriseBanner,
  486. groupsAndEnterpriseBannerVariant,
  487. showUSGovBanner,
  488. usGovBannerVariant,
  489. showLATAMBanner,
  490. recommendedCurrency,
  491. showInrGeoBanner,
  492. showBrlGeoBanner,
  493. projectDashboardReact: true, // used in navbar
  494. groupSsoSetupSuccess,
  495. joinedGroupName,
  496. viaDomainCapture,
  497. groupSubscriptionsPendingEnrollment:
  498. groupSubscriptionsPendingEnrollment.map(subscription => ({
  499. groupId: subscription._id,
  500. groupName: subscription.teamName,
  501. })),
  502. hasIndividualPaidSubscription,
  503. userRestrictions: Array.from(req.userRestrictions || []),
  504. customerIoEnabled,
  505. aiBlocked,
  506. hasAiAssist,
  507. lastActive: user.lastActive
  508. ? Math.floor(user.lastActive.getTime() / 1000)
  509. : null,
  510. signUpDate: user.signUpDate
  511. ? Math.floor(user.signUpDate.getTime() / 1000)
  512. : null,
  513. subjectArea,
  514. primaryOccupation,
  515. role,
  516. usedLatex,
  517. inactiveTutorials,
  518. })
  519. }
  520. /**
  521. * Load user's projects with pagination, sorting and filters
  522. *
  523. * @param {GetProjectsRequest} req the request
  524. * @param {GetProjectsResponse} res the response
  525. * @returns {Promise<void>}
  526. */
  527. async function getProjectsJson(req, res) {
  528. const { filters, page, sort } = req.body
  529. const userId = SessionManager.getLoggedInUserId(req.session)
  530. const projectsPage = await _getProjects(userId, filters, sort, page)
  531. res.json(projectsPage)
  532. }
  533. /**
  534. * @param {string} userId
  535. * @param {Filters} filters
  536. * @param {Sort} sort
  537. * @param {Page} page
  538. * @returns {Promise<{totalSize: number, projects: Project[]}>}
  539. * @private
  540. */
  541. async function _getProjects(
  542. userId,
  543. filters = {},
  544. sort = { by: 'lastUpdated', order: 'desc' },
  545. page = { size: 20 }
  546. ) {
  547. /** @type {[AllUsersProjects, MongoTag[]]} */
  548. const results = await Promise.all([
  549. ProjectGetter.promises.findAllUsersProjects(
  550. userId,
  551. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  552. ),
  553. TagsHandler.promises.getAllTags(userId),
  554. ])
  555. const [allProjects, tags] = results
  556. const formattedProjects = _formatProjects(allProjects, userId)
  557. const filteredProjects = _applyFilters(
  558. formattedProjects,
  559. tags,
  560. filters,
  561. userId
  562. )
  563. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  564. const projects = await _injectProjectUsers(pagedProjects)
  565. return {
  566. totalSize: filteredProjects.length,
  567. projects,
  568. }
  569. }
  570. /**
  571. * @param {AllUsersProjects} projects
  572. * @param {string} userId
  573. * @returns {FormattedProject[]}
  574. * @private
  575. */
  576. function _formatProjects(projects, userId) {
  577. const {
  578. owned,
  579. review,
  580. readAndWrite,
  581. readOnly,
  582. tokenReadAndWrite,
  583. tokenReadOnly,
  584. } = projects
  585. const formattedProjects = /** @type {FormattedProject[]} **/ []
  586. for (const project of owned) {
  587. formattedProjects.push(
  588. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  589. )
  590. }
  591. // Invite-access
  592. for (const project of readAndWrite) {
  593. formattedProjects.push(
  594. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  595. )
  596. }
  597. for (const project of review) {
  598. formattedProjects.push(
  599. _formatProjectInfo(project, 'review', Sources.INVITE, userId)
  600. )
  601. }
  602. for (const project of readOnly) {
  603. formattedProjects.push(
  604. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  605. )
  606. }
  607. // Token-access
  608. // Only add these formattedProjects if they're not already present, this gives us cascading access
  609. // from 'owner' => 'token-read-only'
  610. for (const project of tokenReadAndWrite) {
  611. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  612. formattedProjects.push(
  613. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  614. )
  615. }
  616. }
  617. for (const project of tokenReadOnly) {
  618. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  619. formattedProjects.push(
  620. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  621. )
  622. }
  623. }
  624. return formattedProjects
  625. }
  626. /**
  627. * @param {FormattedProject[]} projects
  628. * @param {MongoTag[]} tags
  629. * @param {Filters} filters
  630. * @param {string} userId
  631. * @returns {FormattedProject[]}
  632. * @private
  633. */
  634. function _applyFilters(projects, tags, filters, userId) {
  635. if (!_hasActiveFilter(filters)) {
  636. return projects
  637. }
  638. return projects.filter(project => _matchesFilters(project, tags, filters))
  639. }
  640. /**
  641. * @param {FormattedProject[]} projects
  642. * @param {Sort} sort
  643. * @param {Page} page
  644. * @returns {FormattedProject[]}
  645. * @private
  646. */
  647. function _sortAndPaginate(projects, sort, page) {
  648. if (
  649. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  650. (sort.order && !['asc', 'desc'].includes(sort.order))
  651. ) {
  652. throw new OError('Invalid sorting criteria', { sort })
  653. }
  654. const sortedProjects = _.orderBy(
  655. projects,
  656. [sort.by || 'lastUpdated'],
  657. [sort.order || 'desc']
  658. )
  659. // TODO handle pagination
  660. return sortedProjects
  661. }
  662. /**
  663. * @param {MongoProject} project
  664. * @param {ProjectAccessLevel} accessLevel
  665. * @param {Source} source
  666. * @param {string} userId
  667. * @returns {FormattedProject}
  668. * @private
  669. */
  670. function _formatProjectInfo(project, accessLevel, source, userId) {
  671. const archived = ProjectHelper.isArchived(project, userId)
  672. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  673. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  674. const readOnlyTokenAccess =
  675. accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN
  676. return {
  677. id: project._id.toString(),
  678. name: project.name,
  679. owner_ref: readOnlyTokenAccess ? null : project.owner_ref,
  680. lastUpdated: project.lastUpdated,
  681. lastUpdatedBy: readOnlyTokenAccess ? null : project.lastUpdatedBy,
  682. accessLevel,
  683. source,
  684. archived,
  685. trashed,
  686. }
  687. }
  688. /**
  689. * @param {FormattedProject[]} projects
  690. * @returns {Promise<Project[]>}
  691. * @private
  692. */
  693. async function _injectProjectUsers(projects) {
  694. const userIds = new Set()
  695. for (const project of projects) {
  696. if (project.owner_ref != null) {
  697. userIds.add(project.owner_ref.toString())
  698. }
  699. if (project.lastUpdatedBy != null) {
  700. userIds.add(project.lastUpdatedBy.toString())
  701. }
  702. }
  703. const projection = {
  704. first_name: 1,
  705. last_name: 1,
  706. email: 1,
  707. }
  708. /** @type {Record<string, UserRef>} */
  709. const users = {}
  710. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  711. const userId = user._id.toString()
  712. users[userId] = {
  713. id: userId,
  714. email: user.email,
  715. firstName: user.first_name,
  716. lastName: user.last_name,
  717. }
  718. }
  719. return projects.map(project => ({
  720. id: project.id,
  721. name: project.name,
  722. archived: project.archived,
  723. trashed: project.trashed,
  724. accessLevel: project.accessLevel,
  725. source: project.source,
  726. lastUpdated: project.lastUpdated.toISOString(),
  727. lastUpdatedBy:
  728. project.lastUpdatedBy == null
  729. ? null
  730. : users[project.lastUpdatedBy.toString()] || null,
  731. owner:
  732. project.owner_ref == null
  733. ? undefined
  734. : users[project.owner_ref.toString()],
  735. owner_ref: undefined,
  736. }))
  737. }
  738. /**
  739. * @param {any} project
  740. * @param {MongoTag[]} tags
  741. * @param {Filters} filters
  742. * @private
  743. */
  744. function _matchesFilters(project, tags, filters) {
  745. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  746. return false
  747. }
  748. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  749. return false
  750. }
  751. if (filters.archived && !project.archived) {
  752. return false
  753. }
  754. if (filters.trashed && !project.trashed) {
  755. return false
  756. }
  757. if (
  758. filters.tag &&
  759. !_.find(
  760. tags,
  761. tag =>
  762. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  763. )
  764. ) {
  765. return false
  766. }
  767. if (
  768. filters.search?.length &&
  769. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  770. ) {
  771. return false
  772. }
  773. return true
  774. }
  775. /**
  776. * @param {Filters} filters
  777. * @returns {boolean}
  778. * @private
  779. */
  780. function _hasActiveFilter(filters) {
  781. return Boolean(
  782. filters.ownedByUser ||
  783. filters.sharedWithUser ||
  784. filters.archived ||
  785. filters.trashed ||
  786. filters.tag === null ||
  787. filters.tag?.length ||
  788. filters.search?.length
  789. )
  790. }
  791. async function _userHasAIAssist(user) {
  792. // Check if the user has AI Assist enabled via Overleaf
  793. if (user.features?.aiErrorAssistant) {
  794. return true
  795. }
  796. // Check if the user has AI Assist enabled via Writefull
  797. const { isPremium: hasAiAssistViaWritefull } =
  798. await UserGetter.promises.getWritefullData(user._id)
  799. if (hasAiAssistViaWritefull) {
  800. return true
  801. }
  802. return false
  803. }
  804. // Determines if user is able to enable AI assist
  805. // based on their permissions and settings
  806. // It does NOT determine if the user has AI Assist enabled
  807. async function _canUseAIAssist(user) {
  808. // Check if the assistant has been manually disabled by the user
  809. if (user.aiErrorAssistant?.enabled === false) {
  810. return false
  811. }
  812. // Check if the user can use AI features (policy check)
  813. return await PermissionsManager.promises.checkUserPermissions(user, [
  814. 'use-ai',
  815. ])
  816. }
  817. export default {
  818. projectListPage: expressify(projectListPage),
  819. getProjectsJson: expressify(getProjectsJson),
  820. }