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, VideosImportInChannelCreate } 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'
24 asyncRetryTransactionMiddleware,
26 commonVideosFiltersValidator,
27 ensureCanManageChannelOrAccount,
33 videoChannelsAddValidator,
34 videoChannelsRemoveValidator,
35 videoChannelsSortValidator,
36 videoChannelsUpdateValidator,
37 videoPlaylistsSortValidator
38 } from '../../middlewares'
40 ensureChannelOwnerCanUpload,
42 videoChannelImportVideosValidator,
43 videoChannelsFollowersSortValidator,
44 videoChannelsListValidator,
45 videoChannelsNameWithHostValidator,
47 } from '../../middlewares/validators'
48 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
49 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
50 import { AccountModel } from '../../models/account/account'
51 import { VideoModel } from '../../models/video/video'
52 import { VideoChannelModel } from '../../models/video/video-channel'
53 import { VideoPlaylistModel } from '../../models/video/video-playlist'
55 const auditLogger = auditLoggerFactory('channels')
56 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
57 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
59 const videoChannelRouter = express.Router()
61 videoChannelRouter.use(apiRateLimiter)
63 videoChannelRouter.get('/',
65 videoChannelsSortValidator,
68 videoChannelsListValidator,
69 asyncMiddleware(listVideoChannels)
72 videoChannelRouter.post('/',
74 asyncMiddleware(videoChannelsAddValidator),
75 asyncRetryTransactionMiddleware(addVideoChannel)
78 videoChannelRouter.post('/:nameWithHost/avatar/pick',
81 asyncMiddleware(videoChannelsNameWithHostValidator),
83 ensureCanManageChannelOrAccount,
84 updateAvatarValidator,
85 asyncMiddleware(updateVideoChannelAvatar)
88 videoChannelRouter.post('/:nameWithHost/banner/pick',
91 asyncMiddleware(videoChannelsNameWithHostValidator),
93 ensureCanManageChannelOrAccount,
94 updateBannerValidator,
95 asyncMiddleware(updateVideoChannelBanner)
98 videoChannelRouter.delete('/:nameWithHost/avatar',
100 asyncMiddleware(videoChannelsNameWithHostValidator),
101 ensureIsLocalChannel,
102 ensureCanManageChannelOrAccount,
103 asyncMiddleware(deleteVideoChannelAvatar)
106 videoChannelRouter.delete('/:nameWithHost/banner',
108 asyncMiddleware(videoChannelsNameWithHostValidator),
109 ensureIsLocalChannel,
110 ensureCanManageChannelOrAccount,
111 asyncMiddleware(deleteVideoChannelBanner)
114 videoChannelRouter.put('/:nameWithHost',
116 asyncMiddleware(videoChannelsNameWithHostValidator),
117 ensureIsLocalChannel,
118 ensureCanManageChannelOrAccount,
119 videoChannelsUpdateValidator,
120 asyncRetryTransactionMiddleware(updateVideoChannel)
123 videoChannelRouter.delete('/:nameWithHost',
125 asyncMiddleware(videoChannelsNameWithHostValidator),
126 ensureIsLocalChannel,
127 ensureCanManageChannelOrAccount,
128 asyncMiddleware(videoChannelsRemoveValidator),
129 asyncRetryTransactionMiddleware(removeVideoChannel)
132 videoChannelRouter.get('/:nameWithHost',
133 asyncMiddleware(videoChannelsNameWithHostValidator),
134 asyncMiddleware(getVideoChannel)
137 videoChannelRouter.get('/:nameWithHost/video-playlists',
138 asyncMiddleware(videoChannelsNameWithHostValidator),
140 videoPlaylistsSortValidator,
142 setDefaultPagination,
143 commonVideoPlaylistFiltersValidator,
144 asyncMiddleware(listVideoChannelPlaylists)
147 videoChannelRouter.get('/:nameWithHost/videos',
148 asyncMiddleware(videoChannelsNameWithHostValidator),
151 setDefaultVideosSort,
152 setDefaultPagination,
153 optionalAuthenticate,
154 commonVideosFiltersValidator,
155 asyncMiddleware(listVideoChannelVideos)
158 videoChannelRouter.get('/:nameWithHost/followers',
160 asyncMiddleware(videoChannelsNameWithHostValidator),
161 ensureCanManageChannelOrAccount,
163 videoChannelsFollowersSortValidator,
165 setDefaultPagination,
166 asyncMiddleware(listVideoChannelFollowers)
169 videoChannelRouter.post('/:nameWithHost/import-videos',
171 asyncMiddleware(videoChannelsNameWithHostValidator),
172 asyncMiddleware(videoChannelImportVideosValidator),
173 ensureIsLocalChannel,
174 ensureCanManageChannelOrAccount,
175 asyncMiddleware(ensureChannelOwnerCanUpload),
176 asyncMiddleware(importVideosInChannel)
179 // ---------------------------------------------------------------------------
185 // ---------------------------------------------------------------------------
187 async function listVideoChannels (req: express.Request, res: express.Response) {
188 const serverActor = await getServerActor()
190 const apiOptions = await Hooks.wrapObject({
191 actorId: serverActor.id,
192 start: req.query.start,
193 count: req.query.count,
195 }, 'filter:api.video-channels.list.params')
197 const resultList = await Hooks.wrapPromiseFun(
198 VideoChannelModel.listForApi,
200 'filter:api.video-channels.list.result'
203 return res.json(getFormattedObjects(resultList.data, resultList.total))
206 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
207 const bannerPhysicalFile = req.files['bannerfile'][0]
208 const videoChannel = res.locals.videoChannel
209 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
211 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
213 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
216 // TODO: remove, deprecated in 4.2
217 banner: getBiggestActorImage(banners).toFormattedJSON(),
218 banners: banners.map(b => b.toFormattedJSON())
222 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
223 const avatarPhysicalFile = req.files['avatarfile'][0]
224 const videoChannel = res.locals.videoChannel
225 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
227 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
228 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
231 // TODO: remove, deprecated in 4.2
232 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
233 avatars: avatars.map(a => a.toFormattedJSON())
237 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
238 const videoChannel = res.locals.videoChannel
240 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
242 return res.status(HttpStatusCode.NO_CONTENT_204).end()
245 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
246 const videoChannel = res.locals.videoChannel
248 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
250 return res.status(HttpStatusCode.NO_CONTENT_204).end()
253 async function addVideoChannel (req: express.Request, res: express.Response) {
254 const videoChannelInfo: VideoChannelCreate = req.body
256 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
257 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
259 return createLocalVideoChannel(videoChannelInfo, account, t)
262 const payload = { actorId: videoChannelCreated.actorId }
263 await JobQueue.Instance.createJob({ type: 'actor-keys', payload })
265 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
266 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
268 Hooks.runAction('action:api.video-channel.created', { videoChannel: videoChannelCreated, req, res })
272 id: videoChannelCreated.id
277 async function updateVideoChannel (req: express.Request, res: express.Response) {
278 const videoChannelInstance = res.locals.videoChannel
279 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
280 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
281 let doBulkVideoUpdate = false
284 await sequelizeTypescript.transaction(async t => {
285 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
286 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
288 if (videoChannelInfoToUpdate.support !== undefined) {
289 const oldSupportField = videoChannelInstance.support
290 videoChannelInstance.support = videoChannelInfoToUpdate.support
292 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
293 doBulkVideoUpdate = true
294 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
298 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
299 await sendUpdateActor(videoChannelInstanceUpdated, t)
302 getAuditIdFromRes(res),
303 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
304 oldVideoChannelAuditKeys
307 Hooks.runAction('action:api.video-channel.updated', { videoChannel: videoChannelInstanceUpdated, req, res })
309 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
312 logger.debug('Cannot update the video channel.', { err })
314 // If the transaction is retried, sequelize will think the object has not changed
315 // So we need to restore the previous fields
316 await resetSequelizeInstance(videoChannelInstance)
321 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
323 // Don't process in a transaction, and after the response because it could be long
324 if (doBulkVideoUpdate) {
325 await federateAllVideosOfChannel(videoChannelInstance)
329 async function removeVideoChannel (req: express.Request, res: express.Response) {
330 const videoChannelInstance = res.locals.videoChannel
332 await sequelizeTypescript.transaction(async t => {
333 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
335 await videoChannelInstance.destroy({ transaction: t })
337 Hooks.runAction('action:api.video-channel.deleted', { videoChannel: videoChannelInstance, req, res })
339 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
340 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
343 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
346 async function getVideoChannel (req: express.Request, res: express.Response) {
347 const id = res.locals.videoChannel.id
348 const videoChannel = await Hooks.wrapObject(res.locals.videoChannel, 'filter:api.video-channel.get.result', { id })
350 if (videoChannel.isOutdated()) {
351 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
354 return res.json(videoChannel.toFormattedJSON())
357 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
358 const serverActor = await getServerActor()
360 const resultList = await VideoPlaylistModel.listForApi({
361 followerActorId: serverActor.id,
362 start: req.query.start,
363 count: req.query.count,
364 sort: req.query.sort,
365 videoChannelId: res.locals.videoChannel.id,
366 type: req.query.playlistType
369 return res.json(getFormattedObjects(resultList.data, resultList.total))
372 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
373 const serverActor = await getServerActor()
375 const videoChannelInstance = res.locals.videoChannel
377 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
380 actorId: serverActor.id,
384 const countVideos = getCountVideos(req)
385 const query = pickCommonVideoQuery(req.query)
387 const apiOptions = await Hooks.wrapObject({
390 displayOnlyForFollower,
391 nsfw: buildNSFWFilter(res, query.nsfw),
392 videoChannelId: videoChannelInstance.id,
393 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
395 }, 'filter:api.video-channels.videos.list.params')
397 const resultList = await Hooks.wrapPromiseFun(
398 VideoModel.listForApi,
400 'filter:api.video-channels.videos.list.result'
403 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
406 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
407 const channel = res.locals.videoChannel
409 const resultList = await ActorFollowModel.listFollowersForApi({
410 actorIds: [ channel.actorId ],
411 start: req.query.start,
412 count: req.query.count,
413 sort: req.query.sort,
414 search: req.query.search,
418 return res.json(getFormattedObjects(resultList.data, resultList.total))
421 async function importVideosInChannel (req: express.Request, res: express.Response) {
422 const { externalChannelUrl } = req.body as VideosImportInChannelCreate
424 await JobQueue.Instance.createJob({
425 type: 'video-channel-import',
428 videoChannelId: res.locals.videoChannel.id,
429 partOfChannelSyncId: res.locals.videoChannelSync?.id
433 logger.info('Video import job for channel "%s" with url "%s" created.', res.locals.videoChannel.name, externalChannelUrl)
435 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()