]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
6b33e894d837da37a8c1cfc4ae548db2a32764d5
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { getBiggestActorImage } from '@server/lib/actor-image'
4 import { Hooks } from '@server/lib/plugins/hooks'
5 import { ActorFollowModel } from '@server/models/actor/actor-follow'
6 import { getServerActor } from '@server/models/application/application'
7 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
8 import { MChannelBannerAccountDefault } from '@server/types/models'
9 import { ActorImageType, HttpStatusCode, VideoChannelCreate, VideoChannelUpdate } from '@shared/models'
10 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
11 import { resetSequelizeInstance } from '../../helpers/database-utils'
12 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
13 import { logger } from '../../helpers/logger'
14 import { getFormattedObjects } from '../../helpers/utils'
15 import { MIMETYPES } from '../../initializers/constants'
16 import { sequelizeTypescript } from '../../initializers/database'
17 import { sendUpdateActor } from '../../lib/activitypub/send'
18 import { JobQueue } from '../../lib/job-queue'
19 import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '../../lib/local-actor'
20 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
21 import {
22 asyncMiddleware,
23 asyncRetryTransactionMiddleware,
24 authenticate,
25 commonVideosFiltersValidator,
26 ensureCanManageChannel,
27 optionalAuthenticate,
28 paginationValidator,
29 setDefaultPagination,
30 setDefaultSort,
31 setDefaultVideosSort,
32 videoChannelsAddValidator,
33 videoChannelsRemoveValidator,
34 videoChannelsSortValidator,
35 videoChannelsUpdateValidator,
36 videoPlaylistsSortValidator
37 } from '../../middlewares'
38 import {
39 ensureIsLocalChannel,
40 videoChannelsFollowersSortValidator,
41 videoChannelsListValidator,
42 videoChannelsNameWithHostValidator,
43 videosSortValidator
44 } from '../../middlewares/validators'
45 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
46 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
47 import { AccountModel } from '../../models/account/account'
48 import { VideoModel } from '../../models/video/video'
49 import { VideoChannelModel } from '../../models/video/video-channel'
50 import { VideoPlaylistModel } from '../../models/video/video-playlist'
51
52 const auditLogger = auditLoggerFactory('channels')
53 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
54 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
55
56 const videoChannelRouter = express.Router()
57
58 videoChannelRouter.get('/',
59 paginationValidator,
60 videoChannelsSortValidator,
61 setDefaultSort,
62 setDefaultPagination,
63 videoChannelsListValidator,
64 asyncMiddleware(listVideoChannels)
65 )
66
67 videoChannelRouter.post('/',
68 authenticate,
69 asyncMiddleware(videoChannelsAddValidator),
70 asyncRetryTransactionMiddleware(addVideoChannel)
71 )
72
73 videoChannelRouter.post('/:nameWithHost/avatar/pick',
74 authenticate,
75 reqAvatarFile,
76 asyncMiddleware(videoChannelsNameWithHostValidator),
77 ensureIsLocalChannel,
78 ensureCanManageChannel,
79 updateAvatarValidator,
80 asyncMiddleware(updateVideoChannelAvatar)
81 )
82
83 videoChannelRouter.post('/:nameWithHost/banner/pick',
84 authenticate,
85 reqBannerFile,
86 asyncMiddleware(videoChannelsNameWithHostValidator),
87 ensureIsLocalChannel,
88 ensureCanManageChannel,
89 updateBannerValidator,
90 asyncMiddleware(updateVideoChannelBanner)
91 )
92
93 videoChannelRouter.delete('/:nameWithHost/avatar',
94 authenticate,
95 asyncMiddleware(videoChannelsNameWithHostValidator),
96 ensureIsLocalChannel,
97 ensureCanManageChannel,
98 asyncMiddleware(deleteVideoChannelAvatar)
99 )
100
101 videoChannelRouter.delete('/:nameWithHost/banner',
102 authenticate,
103 asyncMiddleware(videoChannelsNameWithHostValidator),
104 ensureIsLocalChannel,
105 ensureCanManageChannel,
106 asyncMiddleware(deleteVideoChannelBanner)
107 )
108
109 videoChannelRouter.put('/:nameWithHost',
110 authenticate,
111 asyncMiddleware(videoChannelsNameWithHostValidator),
112 ensureIsLocalChannel,
113 ensureCanManageChannel,
114 videoChannelsUpdateValidator,
115 asyncRetryTransactionMiddleware(updateVideoChannel)
116 )
117
118 videoChannelRouter.delete('/:nameWithHost',
119 authenticate,
120 asyncMiddleware(videoChannelsNameWithHostValidator),
121 ensureIsLocalChannel,
122 ensureCanManageChannel,
123 asyncMiddleware(videoChannelsRemoveValidator),
124 asyncRetryTransactionMiddleware(removeVideoChannel)
125 )
126
127 videoChannelRouter.get('/:nameWithHost',
128 asyncMiddleware(videoChannelsNameWithHostValidator),
129 asyncMiddleware(getVideoChannel)
130 )
131
132 videoChannelRouter.get('/:nameWithHost/video-playlists',
133 asyncMiddleware(videoChannelsNameWithHostValidator),
134 paginationValidator,
135 videoPlaylistsSortValidator,
136 setDefaultSort,
137 setDefaultPagination,
138 commonVideoPlaylistFiltersValidator,
139 asyncMiddleware(listVideoChannelPlaylists)
140 )
141
142 videoChannelRouter.get('/:nameWithHost/videos',
143 asyncMiddleware(videoChannelsNameWithHostValidator),
144 paginationValidator,
145 videosSortValidator,
146 setDefaultVideosSort,
147 setDefaultPagination,
148 optionalAuthenticate,
149 commonVideosFiltersValidator,
150 asyncMiddleware(listVideoChannelVideos)
151 )
152
153 videoChannelRouter.get('/:nameWithHost/followers',
154 authenticate,
155 asyncMiddleware(videoChannelsNameWithHostValidator),
156 ensureCanManageChannel,
157 paginationValidator,
158 videoChannelsFollowersSortValidator,
159 setDefaultSort,
160 setDefaultPagination,
161 asyncMiddleware(listVideoChannelFollowers)
162 )
163
164 // ---------------------------------------------------------------------------
165
166 export {
167 videoChannelRouter
168 }
169
170 // ---------------------------------------------------------------------------
171
172 async function listVideoChannels (req: express.Request, res: express.Response) {
173 const serverActor = await getServerActor()
174
175 const apiOptions = await Hooks.wrapObject({
176 actorId: serverActor.id,
177 start: req.query.start,
178 count: req.query.count,
179 sort: req.query.sort
180 }, 'filter:api.video-channels.list.params')
181
182 const resultList = await Hooks.wrapPromiseFun(
183 VideoChannelModel.listForApi,
184 apiOptions,
185 'filter:api.video-channels.list.result'
186 )
187
188 return res.json(getFormattedObjects(resultList.data, resultList.total))
189 }
190
191 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
192 const bannerPhysicalFile = req.files['bannerfile'][0]
193 const videoChannel = res.locals.videoChannel
194 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
195
196 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
197
198 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
199
200 return res.json({
201 // TODO: remove, deprecated in 4.2
202 banner: getBiggestActorImage(banners).toFormattedJSON(),
203 banners: banners.map(b => b.toFormattedJSON())
204 })
205 }
206
207 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
208 const avatarPhysicalFile = req.files['avatarfile'][0]
209 const videoChannel = res.locals.videoChannel
210 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
211
212 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
213 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
214
215 return res.json({
216 // TODO: remove, deprecated in 4.2
217 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
218 avatars: avatars.map(a => a.toFormattedJSON())
219 })
220 }
221
222 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
223 const videoChannel = res.locals.videoChannel
224
225 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
226
227 return res.status(HttpStatusCode.NO_CONTENT_204).end()
228 }
229
230 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
231 const videoChannel = res.locals.videoChannel
232
233 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
234
235 return res.status(HttpStatusCode.NO_CONTENT_204).end()
236 }
237
238 async function addVideoChannel (req: express.Request, res: express.Response) {
239 const videoChannelInfo: VideoChannelCreate = req.body
240
241 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
242 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
243
244 return createLocalVideoChannel(videoChannelInfo, account, t)
245 })
246
247 const payload = { actorId: videoChannelCreated.actorId }
248 await JobQueue.Instance.createJob({ type: 'actor-keys', payload })
249
250 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
251 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
252
253 Hooks.runAction('action:api.video-channel.created', { videoChannel: videoChannelCreated, req, res })
254
255 return res.json({
256 videoChannel: {
257 id: videoChannelCreated.id
258 }
259 })
260 }
261
262 async function updateVideoChannel (req: express.Request, res: express.Response) {
263 const videoChannelInstance = res.locals.videoChannel
264 const videoChannelFieldsSave = videoChannelInstance.toJSON()
265 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
266 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
267 let doBulkVideoUpdate = false
268
269 try {
270 await sequelizeTypescript.transaction(async t => {
271 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
272 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
273
274 if (videoChannelInfoToUpdate.support !== undefined) {
275 const oldSupportField = videoChannelInstance.support
276 videoChannelInstance.support = videoChannelInfoToUpdate.support
277
278 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
279 doBulkVideoUpdate = true
280 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
281 }
282 }
283
284 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
285 await sendUpdateActor(videoChannelInstanceUpdated, t)
286
287 auditLogger.update(
288 getAuditIdFromRes(res),
289 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
290 oldVideoChannelAuditKeys
291 )
292
293 Hooks.runAction('action:api.video-channel.updated', { videoChannel: videoChannelInstanceUpdated, req, res })
294
295 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
296 })
297 } catch (err) {
298 logger.debug('Cannot update the video channel.', { err })
299
300 // Force fields we want to update
301 // If the transaction is retried, sequelize will think the object has not changed
302 // So it will skip the SQL request, even if the last one was ROLLBACKed!
303 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
304
305 throw err
306 }
307
308 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
309
310 // Don't process in a transaction, and after the response because it could be long
311 if (doBulkVideoUpdate) {
312 await federateAllVideosOfChannel(videoChannelInstance)
313 }
314 }
315
316 async function removeVideoChannel (req: express.Request, res: express.Response) {
317 const videoChannelInstance = res.locals.videoChannel
318
319 await sequelizeTypescript.transaction(async t => {
320 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
321
322 await videoChannelInstance.destroy({ transaction: t })
323
324 Hooks.runAction('action:api.video-channel.deleted', { videoChannel: videoChannelInstance, req, res })
325
326 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
327 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
328 })
329
330 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
331 }
332
333 async function getVideoChannel (req: express.Request, res: express.Response) {
334 const id = res.locals.videoChannel.id
335 const videoChannel = await Hooks.wrapObject(res.locals.videoChannel, 'filter:api.video-channel.get.result', { id })
336
337 if (videoChannel.isOutdated()) {
338 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
339 }
340
341 return res.json(videoChannel.toFormattedJSON())
342 }
343
344 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
345 const serverActor = await getServerActor()
346
347 const resultList = await VideoPlaylistModel.listForApi({
348 followerActorId: serverActor.id,
349 start: req.query.start,
350 count: req.query.count,
351 sort: req.query.sort,
352 videoChannelId: res.locals.videoChannel.id,
353 type: req.query.playlistType
354 })
355
356 return res.json(getFormattedObjects(resultList.data, resultList.total))
357 }
358
359 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
360 const serverActor = await getServerActor()
361
362 const videoChannelInstance = res.locals.videoChannel
363
364 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
365 ? null
366 : {
367 actorId: serverActor.id,
368 orLocalVideos: true
369 }
370
371 const countVideos = getCountVideos(req)
372 const query = pickCommonVideoQuery(req.query)
373
374 const apiOptions = await Hooks.wrapObject({
375 ...query,
376
377 displayOnlyForFollower,
378 nsfw: buildNSFWFilter(res, query.nsfw),
379 videoChannelId: videoChannelInstance.id,
380 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
381 countVideos
382 }, 'filter:api.video-channels.videos.list.params')
383
384 const resultList = await Hooks.wrapPromiseFun(
385 VideoModel.listForApi,
386 apiOptions,
387 'filter:api.video-channels.videos.list.result'
388 )
389
390 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
391 }
392
393 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
394 const channel = res.locals.videoChannel
395
396 const resultList = await ActorFollowModel.listFollowersForApi({
397 actorIds: [ channel.actorId ],
398 start: req.query.start,
399 count: req.query.count,
400 sort: req.query.sort,
401 search: req.query.search,
402 state: 'accepted'
403 })
404
405 return res.json(getFormattedObjects(resultList.data, resultList.total))
406 }