]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-channel.ts
Give moderators access to edit channels (#4608)
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-channel.ts
1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { Hooks } from '@server/lib/plugins/hooks'
4 import { ActorFollowModel } from '@server/models/actor/actor-follow'
5 import { getServerActor } from '@server/models/application/application'
6 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
7 import { MChannelBannerAccountDefault } from '@server/types/models'
8 import { ActorImageType, VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
9 import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
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, updateLocalActorImageFile } 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 banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
191
192 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
193
194 return res.json({ banner: banner.toFormattedJSON() })
195 }
196
197 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
198 const avatarPhysicalFile = req.files['avatarfile'][0]
199 const videoChannel = res.locals.videoChannel
200 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
201
202 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
203
204 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
205
206 return res.json({ avatar: avatar.toFormattedJSON() })
207 }
208
209 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
210 const videoChannel = res.locals.videoChannel
211
212 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
213
214 return res.status(HttpStatusCode.NO_CONTENT_204).end()
215 }
216
217 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
218 const videoChannel = res.locals.videoChannel
219
220 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
221
222 return res.status(HttpStatusCode.NO_CONTENT_204).end()
223 }
224
225 async function addVideoChannel (req: express.Request, res: express.Response) {
226 const videoChannelInfo: VideoChannelCreate = req.body
227
228 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
229 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
230
231 return createLocalVideoChannel(videoChannelInfo, account, t)
232 })
233
234 const payload = { actorId: videoChannelCreated.actorId }
235 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
236
237 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
238 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
239
240 return res.json({
241 videoChannel: {
242 id: videoChannelCreated.id
243 }
244 })
245 }
246
247 async function updateVideoChannel (req: express.Request, res: express.Response) {
248 const videoChannelInstance = res.locals.videoChannel
249 const videoChannelFieldsSave = videoChannelInstance.toJSON()
250 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
251 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
252 let doBulkVideoUpdate = false
253
254 try {
255 await sequelizeTypescript.transaction(async t => {
256 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
257 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
258
259 if (videoChannelInfoToUpdate.support !== undefined) {
260 const oldSupportField = videoChannelInstance.support
261 videoChannelInstance.support = videoChannelInfoToUpdate.support
262
263 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
264 doBulkVideoUpdate = true
265 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
266 }
267 }
268
269 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
270 await sendUpdateActor(videoChannelInstanceUpdated, t)
271
272 auditLogger.update(
273 getAuditIdFromRes(res),
274 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
275 oldVideoChannelAuditKeys
276 )
277
278 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
279 })
280 } catch (err) {
281 logger.debug('Cannot update the video channel.', { err })
282
283 // Force fields we want to update
284 // If the transaction is retried, sequelize will think the object has not changed
285 // So it will skip the SQL request, even if the last one was ROLLBACKed!
286 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
287
288 throw err
289 }
290
291 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
292
293 // Don't process in a transaction, and after the response because it could be long
294 if (doBulkVideoUpdate) {
295 await federateAllVideosOfChannel(videoChannelInstance)
296 }
297 }
298
299 async function removeVideoChannel (req: express.Request, res: express.Response) {
300 const videoChannelInstance = res.locals.videoChannel
301
302 await sequelizeTypescript.transaction(async t => {
303 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
304
305 await videoChannelInstance.destroy({ transaction: t })
306
307 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
308 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
309 })
310
311 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
312 }
313
314 function getVideoChannel (req: express.Request, res: express.Response) {
315 const videoChannel = res.locals.videoChannel
316
317 if (videoChannel.isOutdated()) {
318 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
319 }
320
321 return res.json(videoChannel.toFormattedJSON())
322 }
323
324 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
325 const serverActor = await getServerActor()
326
327 const resultList = await VideoPlaylistModel.listForApi({
328 followerActorId: serverActor.id,
329 start: req.query.start,
330 count: req.query.count,
331 sort: req.query.sort,
332 videoChannelId: res.locals.videoChannel.id,
333 type: req.query.playlistType
334 })
335
336 return res.json(getFormattedObjects(resultList.data, resultList.total))
337 }
338
339 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
340 const serverActor = await getServerActor()
341
342 const videoChannelInstance = res.locals.videoChannel
343
344 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
345 ? null
346 : {
347 actorId: serverActor.id,
348 orLocalVideos: true
349 }
350
351 const countVideos = getCountVideos(req)
352 const query = pickCommonVideoQuery(req.query)
353
354 const apiOptions = await Hooks.wrapObject({
355 ...query,
356
357 displayOnlyForFollower,
358 nsfw: buildNSFWFilter(res, query.nsfw),
359 videoChannelId: videoChannelInstance.id,
360 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
361 countVideos
362 }, 'filter:api.video-channels.videos.list.params')
363
364 const resultList = await Hooks.wrapPromiseFun(
365 VideoModel.listForApi,
366 apiOptions,
367 'filter:api.video-channels.videos.list.result'
368 )
369
370 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
371 }
372
373 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
374 const channel = res.locals.videoChannel
375
376 const resultList = await ActorFollowModel.listFollowersForApi({
377 actorIds: [ channel.actorId ],
378 start: req.query.start,
379 count: req.query.count,
380 sort: req.query.sort,
381 search: req.query.search,
382 state: 'accepted'
383 })
384
385 return res.json(getFormattedObjects(resultList.data, resultList.total))
386 }