Fix AP collections pagination
[oweals/peertube.git] / server / controllers / activitypub / client.ts
1 // Intercept ActivityPub client requests
2 import * as express from 'express'
3 import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
4 import { activityPubCollectionPagination, activityPubContextify } from '../../helpers/activitypub'
5 import { CONFIG, ROUTE_CACHE_LIFETIME } from '../../initializers'
6 import { buildAnnounceWithVideoAudience, buildDislikeActivity, buildLikeActivity } from '../../lib/activitypub/send'
7 import { audiencify, getAudience } from '../../lib/activitypub/audience'
8 import { buildCreateActivity } from '../../lib/activitypub/send/send-create'
9 import {
10   asyncMiddleware,
11   videosShareValidator,
12   executeIfActivityPub,
13   localAccountValidator,
14   localVideoChannelValidator,
15   videosCustomGetValidator
16 } from '../../middlewares'
17 import {
18   getAccountVideoRateValidator,
19   videoCommentGetValidator,
20   videosGetValidator
21 } from '../../middlewares/validators'
22 import { AccountModel } from '../../models/account/account'
23 import { ActorModel } from '../../models/activitypub/actor'
24 import { ActorFollowModel } from '../../models/activitypub/actor-follow'
25 import { VideoModel } from '../../models/video/video'
26 import { VideoChannelModel } from '../../models/video/video-channel'
27 import { VideoCommentModel } from '../../models/video/video-comment'
28 import { VideoShareModel } from '../../models/video/video-share'
29 import { cacheRoute } from '../../middlewares/cache'
30 import { activityPubResponse } from './utils'
31 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
32 import {
33   getRateUrl,
34   getVideoCommentsActivityPubUrl,
35   getVideoDislikesActivityPubUrl,
36   getVideoLikesActivityPubUrl,
37   getVideoSharesActivityPubUrl
38 } from '../../lib/activitypub'
39 import { VideoCaptionModel } from '../../models/video/video-caption'
40 import { videoRedundancyGetValidator } from '../../middlewares/validators/redundancy'
41 import { getServerActor } from '../../helpers/utils'
42 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
43
44 const activityPubClientRouter = express.Router()
45
46 activityPubClientRouter.get('/accounts?/:name',
47   executeIfActivityPub(asyncMiddleware(localAccountValidator)),
48   executeIfActivityPub(accountController)
49 )
50 activityPubClientRouter.get('/accounts?/:name/followers',
51   executeIfActivityPub(asyncMiddleware(localAccountValidator)),
52   executeIfActivityPub(asyncMiddleware(accountFollowersController))
53 )
54 activityPubClientRouter.get('/accounts?/:name/following',
55   executeIfActivityPub(asyncMiddleware(localAccountValidator)),
56   executeIfActivityPub(asyncMiddleware(accountFollowingController))
57 )
58 activityPubClientRouter.get('/accounts?/:name/likes/:videoId',
59   executeIfActivityPub(asyncMiddleware(getAccountVideoRateValidator('like'))),
60   executeIfActivityPub(getAccountVideoRate('like'))
61 )
62 activityPubClientRouter.get('/accounts?/:name/dislikes/:videoId',
63   executeIfActivityPub(asyncMiddleware(getAccountVideoRateValidator('dislike'))),
64   executeIfActivityPub(getAccountVideoRate('dislike'))
65 )
66
67 activityPubClientRouter.get('/videos/watch/:id',
68   executeIfActivityPub(asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.ACTIVITY_PUB.VIDEOS))),
69   executeIfActivityPub(asyncMiddleware(videosGetValidator)),
70   executeIfActivityPub(asyncMiddleware(videoController))
71 )
72 activityPubClientRouter.get('/videos/watch/:id/activity',
73   executeIfActivityPub(asyncMiddleware(videosGetValidator)),
74   executeIfActivityPub(asyncMiddleware(videoController))
75 )
76 activityPubClientRouter.get('/videos/watch/:id/announces',
77   executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))),
78   executeIfActivityPub(asyncMiddleware(videoAnnouncesController))
79 )
80 activityPubClientRouter.get('/videos/watch/:id/announces/:actorId',
81   executeIfActivityPub(asyncMiddleware(videosShareValidator)),
82   executeIfActivityPub(asyncMiddleware(videoAnnounceController))
83 )
84 activityPubClientRouter.get('/videos/watch/:id/likes',
85   executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))),
86   executeIfActivityPub(asyncMiddleware(videoLikesController))
87 )
88 activityPubClientRouter.get('/videos/watch/:id/dislikes',
89   executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))),
90   executeIfActivityPub(asyncMiddleware(videoDislikesController))
91 )
92 activityPubClientRouter.get('/videos/watch/:id/comments',
93   executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))),
94   executeIfActivityPub(asyncMiddleware(videoCommentsController))
95 )
96 activityPubClientRouter.get('/videos/watch/:videoId/comments/:commentId',
97   executeIfActivityPub(asyncMiddleware(videoCommentGetValidator)),
98   executeIfActivityPub(asyncMiddleware(videoCommentController))
99 )
100 activityPubClientRouter.get('/videos/watch/:videoId/comments/:commentId/activity',
101   executeIfActivityPub(asyncMiddleware(videoCommentGetValidator)),
102   executeIfActivityPub(asyncMiddleware(videoCommentController))
103 )
104
105 activityPubClientRouter.get('/video-channels/:name',
106   executeIfActivityPub(asyncMiddleware(localVideoChannelValidator)),
107   executeIfActivityPub(asyncMiddleware(videoChannelController))
108 )
109 activityPubClientRouter.get('/video-channels/:name/followers',
110   executeIfActivityPub(asyncMiddleware(localVideoChannelValidator)),
111   executeIfActivityPub(asyncMiddleware(videoChannelFollowersController))
112 )
113 activityPubClientRouter.get('/video-channels/:name/following',
114   executeIfActivityPub(asyncMiddleware(localVideoChannelValidator)),
115   executeIfActivityPub(asyncMiddleware(videoChannelFollowingController))
116 )
117
118 activityPubClientRouter.get('/redundancy/videos/:videoId/:resolution([0-9]+)(-:fps([0-9]+))?',
119   executeIfActivityPub(asyncMiddleware(videoRedundancyGetValidator)),
120   executeIfActivityPub(asyncMiddleware(videoRedundancyController))
121 )
122
123 // ---------------------------------------------------------------------------
124
125 export {
126   activityPubClientRouter
127 }
128
129 // ---------------------------------------------------------------------------
130
131 function accountController (req: express.Request, res: express.Response, next: express.NextFunction) {
132   const account: AccountModel = res.locals.account
133
134   return activityPubResponse(activityPubContextify(account.toActivityPubObject()), res)
135 }
136
137 async function accountFollowersController (req: express.Request, res: express.Response, next: express.NextFunction) {
138   const account: AccountModel = res.locals.account
139   const activityPubResult = await actorFollowers(req, account.Actor)
140
141   return activityPubResponse(activityPubContextify(activityPubResult), res)
142 }
143
144 async function accountFollowingController (req: express.Request, res: express.Response, next: express.NextFunction) {
145   const account: AccountModel = res.locals.account
146   const activityPubResult = await actorFollowing(req, account.Actor)
147
148   return activityPubResponse(activityPubContextify(activityPubResult), res)
149 }
150
151 function getAccountVideoRate (rateType: VideoRateType) {
152   return (req: express.Request, res: express.Response) => {
153     const accountVideoRate: AccountVideoRateModel = res.locals.accountVideoRate
154
155     const byActor = accountVideoRate.Account.Actor
156     const url = getRateUrl(rateType, byActor, accountVideoRate.Video)
157     const APObject = rateType === 'like'
158       ? buildLikeActivity(url, byActor, accountVideoRate.Video)
159       : buildCreateActivity(url, byActor, buildDislikeActivity(url, byActor, accountVideoRate.Video))
160
161     return activityPubResponse(activityPubContextify(APObject), res)
162   }
163 }
164
165 async function videoController (req: express.Request, res: express.Response, next: express.NextFunction) {
166   const video: VideoModel = res.locals.video
167
168   if (video.isOwned() === false) return res.redirect(video.url)
169
170   // We need captions to render AP object
171   video.VideoCaptions = await VideoCaptionModel.listVideoCaptions(video.id)
172
173   const audience = getAudience(video.VideoChannel.Account.Actor, video.privacy === VideoPrivacy.PUBLIC)
174   const videoObject = audiencify(video.toActivityPubObject(), audience)
175
176   if (req.path.endsWith('/activity')) {
177     const data = buildCreateActivity(video.url, video.VideoChannel.Account.Actor, videoObject, audience)
178     return activityPubResponse(activityPubContextify(data), res)
179   }
180
181   return activityPubResponse(activityPubContextify(videoObject), res)
182 }
183
184 async function videoAnnounceController (req: express.Request, res: express.Response, next: express.NextFunction) {
185   const share = res.locals.videoShare as VideoShareModel
186
187   if (share.Actor.isOwned() === false) return res.redirect(share.url)
188
189   const { activity } = await buildAnnounceWithVideoAudience(share.Actor, share, res.locals.video, undefined)
190
191   return activityPubResponse(activityPubContextify(activity), res)
192 }
193
194 async function videoAnnouncesController (req: express.Request, res: express.Response, next: express.NextFunction) {
195   const video: VideoModel = res.locals.video
196
197   const handler = async (start: number, count: number) => {
198     const result = await VideoShareModel.listAndCountByVideoId(video.id, start, count)
199     return {
200       total: result.count,
201       data: result.rows.map(r => r.url)
202     }
203   }
204   const json = await activityPubCollectionPagination(getVideoSharesActivityPubUrl(video), handler, req.query.page)
205
206   return activityPubResponse(activityPubContextify(json), res)
207 }
208
209 async function videoLikesController (req: express.Request, res: express.Response, next: express.NextFunction) {
210   const video: VideoModel = res.locals.video
211   const json = await videoRates(req, 'like', video, getVideoLikesActivityPubUrl(video))
212
213   return activityPubResponse(activityPubContextify(json), res)
214 }
215
216 async function videoDislikesController (req: express.Request, res: express.Response, next: express.NextFunction) {
217   const video: VideoModel = res.locals.video
218   const json = await videoRates(req, 'dislike', video, getVideoDislikesActivityPubUrl(video))
219
220   return activityPubResponse(activityPubContextify(json), res)
221 }
222
223 async function videoCommentsController (req: express.Request, res: express.Response, next: express.NextFunction) {
224   const video: VideoModel = res.locals.video
225
226   const handler = async (start: number, count: number) => {
227     const result = await VideoCommentModel.listAndCountByVideoId(video.id, start, count)
228     return {
229       total: result.count,
230       data: result.rows.map(r => r.url)
231     }
232   }
233   const json = await activityPubCollectionPagination(getVideoCommentsActivityPubUrl(video), handler, req.query.page)
234
235   return activityPubResponse(activityPubContextify(json), res)
236 }
237
238 async function videoChannelController (req: express.Request, res: express.Response, next: express.NextFunction) {
239   const videoChannel: VideoChannelModel = res.locals.videoChannel
240
241   return activityPubResponse(activityPubContextify(videoChannel.toActivityPubObject()), res)
242 }
243
244 async function videoChannelFollowersController (req: express.Request, res: express.Response, next: express.NextFunction) {
245   const videoChannel: VideoChannelModel = res.locals.videoChannel
246   const activityPubResult = await actorFollowers(req, videoChannel.Actor)
247
248   return activityPubResponse(activityPubContextify(activityPubResult), res)
249 }
250
251 async function videoChannelFollowingController (req: express.Request, res: express.Response, next: express.NextFunction) {
252   const videoChannel: VideoChannelModel = res.locals.videoChannel
253   const activityPubResult = await actorFollowing(req, videoChannel.Actor)
254
255   return activityPubResponse(activityPubContextify(activityPubResult), res)
256 }
257
258 async function videoCommentController (req: express.Request, res: express.Response, next: express.NextFunction) {
259   const videoComment: VideoCommentModel = res.locals.videoComment
260
261   if (videoComment.isOwned() === false) return res.redirect(videoComment.url)
262
263   const threadParentComments = await VideoCommentModel.listThreadParentComments(videoComment, undefined)
264   const isPublic = true // Comments are always public
265   const audience = getAudience(videoComment.Account.Actor, isPublic)
266
267   const videoCommentObject = audiencify(videoComment.toActivityPubObject(threadParentComments), audience)
268
269   if (req.path.endsWith('/activity')) {
270     const data = buildCreateActivity(videoComment.url, videoComment.Account.Actor, videoCommentObject, audience)
271     return activityPubResponse(activityPubContextify(data), res)
272   }
273
274   return activityPubResponse(activityPubContextify(videoCommentObject), res)
275 }
276
277 async function videoRedundancyController (req: express.Request, res: express.Response) {
278   const videoRedundancy: VideoRedundancyModel = res.locals.videoRedundancy
279   if (videoRedundancy.isOwned() === false) return res.redirect(videoRedundancy.url)
280
281   const serverActor = await getServerActor()
282
283   const audience = getAudience(serverActor)
284   const object = audiencify(videoRedundancy.toActivityPubObject(), audience)
285
286   if (req.path.endsWith('/activity')) {
287     const data = buildCreateActivity(videoRedundancy.url, serverActor, object, audience)
288     return activityPubResponse(activityPubContextify(data), res)
289   }
290
291   return activityPubResponse(activityPubContextify(object), res)
292 }
293
294 // ---------------------------------------------------------------------------
295
296 async function actorFollowing (req: express.Request, actor: ActorModel) {
297   const handler = (start: number, count: number) => {
298     return ActorFollowModel.listAcceptedFollowingUrlsForApi([ actor.id ], undefined, start, count)
299   }
300
301   return activityPubCollectionPagination(CONFIG.WEBSERVER.URL + req.path, handler, req.query.page)
302 }
303
304 async function actorFollowers (req: express.Request, actor: ActorModel) {
305   const handler = (start: number, count: number) => {
306     return ActorFollowModel.listAcceptedFollowerUrlsForApi([ actor.id ], undefined, start, count)
307   }
308
309   return activityPubCollectionPagination(CONFIG.WEBSERVER.URL + req.path, handler, req.query.page)
310 }
311
312 function videoRates (req: express.Request, rateType: VideoRateType, video: VideoModel, url: string) {
313   const handler = async (start: number, count: number) => {
314     const result = await AccountVideoRateModel.listAndCountAccountUrlsByVideoId(rateType, video.id, start, count)
315     return {
316       total: result.count,
317       data: result.rows.map(r => r.url)
318     }
319   }
320   return activityPubCollectionPagination(url, handler, req.query.page)
321 }