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