client.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import cors from 'cors'
  2. import express from 'express'
  3. import { activityPubCollectionPagination } from '@server/lib/activitypub/collection'
  4. import { activityPubContextify } from '@server/lib/activitypub/context'
  5. import { getServerActor } from '@server/models/application/application'
  6. import { MAccountId, MActorId, MChannelId, MVideoId } from '@server/types/models'
  7. import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
  8. import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
  9. import { ROUTE_CACHE_LIFETIME, WEBSERVER } from '../../initializers/constants'
  10. import { audiencify, getAudience } from '../../lib/activitypub/audience'
  11. import { buildAnnounceWithVideoAudience, buildLikeActivity } from '../../lib/activitypub/send'
  12. import { buildCreateActivity } from '../../lib/activitypub/send/send-create'
  13. import { buildDislikeActivity } from '../../lib/activitypub/send/send-dislike'
  14. import {
  15. getLocalVideoCommentsActivityPubUrl,
  16. getLocalVideoDislikesActivityPubUrl,
  17. getLocalVideoLikesActivityPubUrl,
  18. getLocalVideoSharesActivityPubUrl
  19. } from '../../lib/activitypub/url'
  20. import {
  21. asyncMiddleware,
  22. ensureIsLocalChannel,
  23. executeIfActivityPub,
  24. localAccountValidator,
  25. videoChannelsNameWithHostValidator,
  26. videosCustomGetValidator,
  27. videosShareValidator
  28. } from '../../middlewares'
  29. import { cacheRoute } from '../../middlewares/cache/cache'
  30. import { getAccountVideoRateValidatorFactory, getVideoLocalViewerValidator, videoCommentGetValidator } from '../../middlewares/validators'
  31. import { videoFileRedundancyGetValidator, videoPlaylistRedundancyGetValidator } from '../../middlewares/validators/redundancy'
  32. import { videoPlaylistElementAPGetValidator, videoPlaylistsGetValidator } from '../../middlewares/validators/videos/video-playlists'
  33. import { AccountModel } from '../../models/account/account'
  34. import { AccountVideoRateModel } from '../../models/account/account-video-rate'
  35. import { ActorFollowModel } from '../../models/actor/actor-follow'
  36. import { VideoCaptionModel } from '../../models/video/video-caption'
  37. import { VideoCommentModel } from '../../models/video/video-comment'
  38. import { VideoPlaylistModel } from '../../models/video/video-playlist'
  39. import { VideoShareModel } from '../../models/video/video-share'
  40. import { activityPubResponse } from './utils'
  41. const activityPubClientRouter = express.Router()
  42. activityPubClientRouter.use(cors())
  43. // Intercept ActivityPub client requests
  44. activityPubClientRouter.get(
  45. [ '/accounts?/:name', '/accounts?/:name/video-channels', '/a/:name', '/a/:name/video-channels' ],
  46. executeIfActivityPub,
  47. asyncMiddleware(localAccountValidator),
  48. accountController
  49. )
  50. activityPubClientRouter.get('/accounts?/:name/followers',
  51. executeIfActivityPub,
  52. asyncMiddleware(localAccountValidator),
  53. asyncMiddleware(accountFollowersController)
  54. )
  55. activityPubClientRouter.get('/accounts?/:name/following',
  56. executeIfActivityPub,
  57. asyncMiddleware(localAccountValidator),
  58. asyncMiddleware(accountFollowingController)
  59. )
  60. activityPubClientRouter.get('/accounts?/:name/playlists',
  61. executeIfActivityPub,
  62. asyncMiddleware(localAccountValidator),
  63. asyncMiddleware(accountPlaylistsController)
  64. )
  65. activityPubClientRouter.get('/accounts?/:name/likes/:videoId',
  66. executeIfActivityPub,
  67. cacheRoute(ROUTE_CACHE_LIFETIME.ACTIVITY_PUB.VIDEOS),
  68. asyncMiddleware(getAccountVideoRateValidatorFactory('like')),
  69. getAccountVideoRateFactory('like')
  70. )
  71. activityPubClientRouter.get('/accounts?/:name/dislikes/:videoId',
  72. executeIfActivityPub,
  73. cacheRoute(ROUTE_CACHE_LIFETIME.ACTIVITY_PUB.VIDEOS),
  74. asyncMiddleware(getAccountVideoRateValidatorFactory('dislike')),
  75. getAccountVideoRateFactory('dislike')
  76. )
  77. activityPubClientRouter.get(
  78. [ '/videos/watch/:id', '/w/:id' ],
  79. executeIfActivityPub,
  80. cacheRoute(ROUTE_CACHE_LIFETIME.ACTIVITY_PUB.VIDEOS),
  81. asyncMiddleware(videosCustomGetValidator('all')),
  82. asyncMiddleware(videoController)
  83. )
  84. activityPubClientRouter.get('/videos/watch/:id/activity',
  85. executeIfActivityPub,
  86. asyncMiddleware(videosCustomGetValidator('all')),
  87. asyncMiddleware(videoController)
  88. )
  89. activityPubClientRouter.get('/videos/watch/:id/announces',
  90. executeIfActivityPub,
  91. asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
  92. asyncMiddleware(videoAnnouncesController)
  93. )
  94. activityPubClientRouter.get('/videos/watch/:id/announces/:actorId',
  95. executeIfActivityPub,
  96. asyncMiddleware(videosShareValidator),
  97. asyncMiddleware(videoAnnounceController)
  98. )
  99. activityPubClientRouter.get('/videos/watch/:id/likes',
  100. executeIfActivityPub,
  101. asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
  102. asyncMiddleware(videoLikesController)
  103. )
  104. activityPubClientRouter.get('/videos/watch/:id/dislikes',
  105. executeIfActivityPub,
  106. asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
  107. asyncMiddleware(videoDislikesController)
  108. )
  109. activityPubClientRouter.get('/videos/watch/:id/comments',
  110. executeIfActivityPub,
  111. asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
  112. asyncMiddleware(videoCommentsController)
  113. )
  114. activityPubClientRouter.get('/videos/watch/:videoId/comments/:commentId',
  115. executeIfActivityPub,
  116. asyncMiddleware(videoCommentGetValidator),
  117. asyncMiddleware(videoCommentController)
  118. )
  119. activityPubClientRouter.get('/videos/watch/:videoId/comments/:commentId/activity',
  120. executeIfActivityPub,
  121. asyncMiddleware(videoCommentGetValidator),
  122. asyncMiddleware(videoCommentController)
  123. )
  124. activityPubClientRouter.get(
  125. [ '/video-channels/:nameWithHost', '/video-channels/:nameWithHost/videos', '/c/:nameWithHost', '/c/:nameWithHost/videos' ],
  126. executeIfActivityPub,
  127. asyncMiddleware(videoChannelsNameWithHostValidator),
  128. ensureIsLocalChannel,
  129. videoChannelController
  130. )
  131. activityPubClientRouter.get('/video-channels/:nameWithHost/followers',
  132. executeIfActivityPub,
  133. asyncMiddleware(videoChannelsNameWithHostValidator),
  134. ensureIsLocalChannel,
  135. asyncMiddleware(videoChannelFollowersController)
  136. )
  137. activityPubClientRouter.get('/video-channels/:nameWithHost/following',
  138. executeIfActivityPub,
  139. asyncMiddleware(videoChannelsNameWithHostValidator),
  140. ensureIsLocalChannel,
  141. asyncMiddleware(videoChannelFollowingController)
  142. )
  143. activityPubClientRouter.get('/video-channels/:nameWithHost/playlists',
  144. executeIfActivityPub,
  145. asyncMiddleware(videoChannelsNameWithHostValidator),
  146. ensureIsLocalChannel,
  147. asyncMiddleware(videoChannelPlaylistsController)
  148. )
  149. activityPubClientRouter.get('/redundancy/videos/:videoId/:resolution([0-9]+)(-:fps([0-9]+))?',
  150. executeIfActivityPub,
  151. asyncMiddleware(videoFileRedundancyGetValidator),
  152. asyncMiddleware(videoRedundancyController)
  153. )
  154. activityPubClientRouter.get('/redundancy/streaming-playlists/:streamingPlaylistType/:videoId',
  155. executeIfActivityPub,
  156. asyncMiddleware(videoPlaylistRedundancyGetValidator),
  157. asyncMiddleware(videoRedundancyController)
  158. )
  159. activityPubClientRouter.get(
  160. [ '/video-playlists/:playlistId', '/videos/watch/playlist/:playlistId', '/w/p/:playlistId' ],
  161. executeIfActivityPub,
  162. asyncMiddleware(videoPlaylistsGetValidator('all')),
  163. asyncMiddleware(videoPlaylistController)
  164. )
  165. activityPubClientRouter.get('/video-playlists/:playlistId/videos/:playlistElementId',
  166. executeIfActivityPub,
  167. asyncMiddleware(videoPlaylistElementAPGetValidator),
  168. videoPlaylistElementController
  169. )
  170. activityPubClientRouter.get('/videos/local-viewer/:localViewerId',
  171. executeIfActivityPub,
  172. asyncMiddleware(getVideoLocalViewerValidator),
  173. getVideoLocalViewerController
  174. )
  175. // ---------------------------------------------------------------------------
  176. export {
  177. activityPubClientRouter
  178. }
  179. // ---------------------------------------------------------------------------
  180. function accountController (req: express.Request, res: express.Response) {
  181. const account = res.locals.account
  182. return activityPubResponse(activityPubContextify(account.toActivityPubObject(), 'Actor'), res)
  183. }
  184. async function accountFollowersController (req: express.Request, res: express.Response) {
  185. const account = res.locals.account
  186. const activityPubResult = await actorFollowers(req, account.Actor)
  187. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  188. }
  189. async function accountFollowingController (req: express.Request, res: express.Response) {
  190. const account = res.locals.account
  191. const activityPubResult = await actorFollowing(req, account.Actor)
  192. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  193. }
  194. async function accountPlaylistsController (req: express.Request, res: express.Response) {
  195. const account = res.locals.account
  196. const activityPubResult = await actorPlaylists(req, { account })
  197. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  198. }
  199. async function videoChannelPlaylistsController (req: express.Request, res: express.Response) {
  200. const channel = res.locals.videoChannel
  201. const activityPubResult = await actorPlaylists(req, { channel })
  202. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  203. }
  204. function getAccountVideoRateFactory (rateType: VideoRateType) {
  205. return (req: express.Request, res: express.Response) => {
  206. const accountVideoRate = res.locals.accountVideoRate
  207. const byActor = accountVideoRate.Account.Actor
  208. const APObject = rateType === 'like'
  209. ? buildLikeActivity(accountVideoRate.url, byActor, accountVideoRate.Video)
  210. : buildDislikeActivity(accountVideoRate.url, byActor, accountVideoRate.Video)
  211. return activityPubResponse(activityPubContextify(APObject, 'Rate'), res)
  212. }
  213. }
  214. async function videoController (req: express.Request, res: express.Response) {
  215. const video = res.locals.videoAll
  216. if (redirectIfNotOwned(video.url, res)) return
  217. // We need captions to render AP object
  218. const captions = await VideoCaptionModel.listVideoCaptions(video.id)
  219. const videoWithCaptions = Object.assign(video, { VideoCaptions: captions })
  220. const audience = getAudience(videoWithCaptions.VideoChannel.Account.Actor, videoWithCaptions.privacy === VideoPrivacy.PUBLIC)
  221. const videoObject = audiencify(videoWithCaptions.toActivityPubObject(), audience)
  222. if (req.path.endsWith('/activity')) {
  223. const data = buildCreateActivity(videoWithCaptions.url, video.VideoChannel.Account.Actor, videoObject, audience)
  224. return activityPubResponse(activityPubContextify(data, 'Video'), res)
  225. }
  226. return activityPubResponse(activityPubContextify(videoObject, 'Video'), res)
  227. }
  228. async function videoAnnounceController (req: express.Request, res: express.Response) {
  229. const share = res.locals.videoShare
  230. if (redirectIfNotOwned(share.url, res)) return
  231. const { activity } = await buildAnnounceWithVideoAudience(share.Actor, share, res.locals.videoAll, undefined)
  232. return activityPubResponse(activityPubContextify(activity, 'Announce'), res)
  233. }
  234. async function videoAnnouncesController (req: express.Request, res: express.Response) {
  235. const video = res.locals.onlyImmutableVideo
  236. if (redirectIfNotOwned(video.url, res)) return
  237. const handler = async (start: number, count: number) => {
  238. const result = await VideoShareModel.listAndCountByVideoId(video.id, start, count)
  239. return {
  240. total: result.total,
  241. data: result.data.map(r => r.url)
  242. }
  243. }
  244. const json = await activityPubCollectionPagination(getLocalVideoSharesActivityPubUrl(video), handler, req.query.page)
  245. return activityPubResponse(activityPubContextify(json, 'Collection'), res)
  246. }
  247. async function videoLikesController (req: express.Request, res: express.Response) {
  248. const video = res.locals.onlyImmutableVideo
  249. if (redirectIfNotOwned(video.url, res)) return
  250. const json = await videoRates(req, 'like', video, getLocalVideoLikesActivityPubUrl(video))
  251. return activityPubResponse(activityPubContextify(json, 'Collection'), res)
  252. }
  253. async function videoDislikesController (req: express.Request, res: express.Response) {
  254. const video = res.locals.onlyImmutableVideo
  255. if (redirectIfNotOwned(video.url, res)) return
  256. const json = await videoRates(req, 'dislike', video, getLocalVideoDislikesActivityPubUrl(video))
  257. return activityPubResponse(activityPubContextify(json, 'Collection'), res)
  258. }
  259. async function videoCommentsController (req: express.Request, res: express.Response) {
  260. const video = res.locals.onlyImmutableVideo
  261. if (redirectIfNotOwned(video.url, res)) return
  262. const handler = async (start: number, count: number) => {
  263. const result = await VideoCommentModel.listAndCountByVideoForAP(video, start, count)
  264. return {
  265. total: result.total,
  266. data: result.data.map(r => r.url)
  267. }
  268. }
  269. const json = await activityPubCollectionPagination(getLocalVideoCommentsActivityPubUrl(video), handler, req.query.page)
  270. return activityPubResponse(activityPubContextify(json, 'Collection'), res)
  271. }
  272. function videoChannelController (req: express.Request, res: express.Response) {
  273. const videoChannel = res.locals.videoChannel
  274. return activityPubResponse(activityPubContextify(videoChannel.toActivityPubObject(), 'Actor'), res)
  275. }
  276. async function videoChannelFollowersController (req: express.Request, res: express.Response) {
  277. const videoChannel = res.locals.videoChannel
  278. const activityPubResult = await actorFollowers(req, videoChannel.Actor)
  279. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  280. }
  281. async function videoChannelFollowingController (req: express.Request, res: express.Response) {
  282. const videoChannel = res.locals.videoChannel
  283. const activityPubResult = await actorFollowing(req, videoChannel.Actor)
  284. return activityPubResponse(activityPubContextify(activityPubResult, 'Collection'), res)
  285. }
  286. async function videoCommentController (req: express.Request, res: express.Response) {
  287. const videoComment = res.locals.videoCommentFull
  288. if (redirectIfNotOwned(videoComment.url, res)) return
  289. const threadParentComments = await VideoCommentModel.listThreadParentComments(videoComment, undefined)
  290. const isPublic = true // Comments are always public
  291. let videoCommentObject = videoComment.toActivityPubObject(threadParentComments)
  292. if (videoComment.Account) {
  293. const audience = getAudience(videoComment.Account.Actor, isPublic)
  294. videoCommentObject = audiencify(videoCommentObject, audience)
  295. if (req.path.endsWith('/activity')) {
  296. const data = buildCreateActivity(videoComment.url, videoComment.Account.Actor, videoCommentObject, audience)
  297. return activityPubResponse(activityPubContextify(data, 'Comment'), res)
  298. }
  299. }
  300. return activityPubResponse(activityPubContextify(videoCommentObject, 'Comment'), res)
  301. }
  302. async function videoRedundancyController (req: express.Request, res: express.Response) {
  303. const videoRedundancy = res.locals.videoRedundancy
  304. if (redirectIfNotOwned(videoRedundancy.url, res)) return
  305. const serverActor = await getServerActor()
  306. const audience = getAudience(serverActor)
  307. const object = audiencify(videoRedundancy.toActivityPubObject(), audience)
  308. if (req.path.endsWith('/activity')) {
  309. const data = buildCreateActivity(videoRedundancy.url, serverActor, object, audience)
  310. return activityPubResponse(activityPubContextify(data, 'CacheFile'), res)
  311. }
  312. return activityPubResponse(activityPubContextify(object, 'CacheFile'), res)
  313. }
  314. async function videoPlaylistController (req: express.Request, res: express.Response) {
  315. const playlist = res.locals.videoPlaylistFull
  316. if (redirectIfNotOwned(playlist.url, res)) return
  317. // We need more attributes
  318. playlist.OwnerAccount = await AccountModel.load(playlist.ownerAccountId)
  319. const json = await playlist.toActivityPubObject(req.query.page, null)
  320. const audience = getAudience(playlist.OwnerAccount.Actor, playlist.privacy === VideoPlaylistPrivacy.PUBLIC)
  321. const object = audiencify(json, audience)
  322. return activityPubResponse(activityPubContextify(object, 'Playlist'), res)
  323. }
  324. function videoPlaylistElementController (req: express.Request, res: express.Response) {
  325. const videoPlaylistElement = res.locals.videoPlaylistElementAP
  326. if (redirectIfNotOwned(videoPlaylistElement.url, res)) return
  327. const json = videoPlaylistElement.toActivityPubObject()
  328. return activityPubResponse(activityPubContextify(json, 'Playlist'), res)
  329. }
  330. function getVideoLocalViewerController (req: express.Request, res: express.Response) {
  331. const localViewer = res.locals.localViewerFull
  332. return activityPubResponse(activityPubContextify(localViewer.toActivityPubObject(), 'WatchAction'), res)
  333. }
  334. // ---------------------------------------------------------------------------
  335. function actorFollowing (req: express.Request, actor: MActorId) {
  336. const handler = (start: number, count: number) => {
  337. return ActorFollowModel.listAcceptedFollowingUrlsForApi([ actor.id ], undefined, start, count)
  338. }
  339. return activityPubCollectionPagination(WEBSERVER.URL + req.path, handler, req.query.page)
  340. }
  341. function actorFollowers (req: express.Request, actor: MActorId) {
  342. const handler = (start: number, count: number) => {
  343. return ActorFollowModel.listAcceptedFollowerUrlsForAP([ actor.id ], undefined, start, count)
  344. }
  345. return activityPubCollectionPagination(WEBSERVER.URL + req.path, handler, req.query.page)
  346. }
  347. function actorPlaylists (req: express.Request, options: { account: MAccountId } | { channel: MChannelId }) {
  348. const handler = (start: number, count: number) => {
  349. return VideoPlaylistModel.listPublicUrlsOfForAP(options, start, count)
  350. }
  351. return activityPubCollectionPagination(WEBSERVER.URL + req.path, handler, req.query.page)
  352. }
  353. function videoRates (req: express.Request, rateType: VideoRateType, video: MVideoId, url: string) {
  354. const handler = async (start: number, count: number) => {
  355. const result = await AccountVideoRateModel.listAndCountAccountUrlsByVideoId(rateType, video.id, start, count)
  356. return {
  357. total: result.total,
  358. data: result.data.map(r => r.url)
  359. }
  360. }
  361. return activityPubCollectionPagination(url, handler, req.query.page)
  362. }
  363. function redirectIfNotOwned (url: string, res: express.Response) {
  364. if (url.startsWith(WEBSERVER.URL) === false) {
  365. res.redirect(url)
  366. return true
  367. }
  368. return false
  369. }