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