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