user-subscriptions.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import express from 'express'
  2. import { body, param, query } from 'express-validator'
  3. import { arrayify } from '@shared/core-utils'
  4. import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
  5. import { areValidActorHandles, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor'
  6. import { WEBSERVER } from '../../initializers/constants'
  7. import { ActorFollowModel } from '../../models/actor/actor-follow'
  8. import { areValidationErrors } from './shared'
  9. const userSubscriptionListValidator = [
  10. query('search')
  11. .optional()
  12. .not().isEmpty(),
  13. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  14. if (areValidationErrors(req, res)) return
  15. return next()
  16. }
  17. ]
  18. const userSubscriptionAddValidator = [
  19. body('uri')
  20. .custom(isValidActorHandle).withMessage('Should have a valid URI to follow (username@domain)'),
  21. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  22. if (areValidationErrors(req, res)) return
  23. return next()
  24. }
  25. ]
  26. const areSubscriptionsExistValidator = [
  27. query('uris')
  28. .customSanitizer(arrayify)
  29. .custom(areValidActorHandles).withMessage('Should have a valid array of URIs'),
  30. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  31. if (areValidationErrors(req, res)) return
  32. return next()
  33. }
  34. ]
  35. const userSubscriptionGetValidator = [
  36. param('uri')
  37. .custom(isValidActorHandle),
  38. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  39. if (areValidationErrors(req, res)) return
  40. let [ name, host ] = req.params.uri.split('@')
  41. if (host === WEBSERVER.HOST) host = null
  42. const user = res.locals.oauth.token.User
  43. const subscription = await ActorFollowModel.loadByActorAndTargetNameAndHostForAPI({
  44. actorId: user.Account.Actor.id,
  45. targetName: name,
  46. targetHost: host,
  47. state: 'accepted'
  48. })
  49. if (!subscription?.ActorFollowing.VideoChannel) {
  50. return res.fail({
  51. status: HttpStatusCode.NOT_FOUND_404,
  52. message: `Subscription ${req.params.uri} not found.`
  53. })
  54. }
  55. res.locals.subscription = subscription
  56. return next()
  57. }
  58. ]
  59. // ---------------------------------------------------------------------------
  60. export {
  61. areSubscriptionsExistValidator,
  62. userSubscriptionListValidator,
  63. userSubscriptionAddValidator,
  64. userSubscriptionGetValidator
  65. }