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'
23 asyncRetryTransactionMiddleware,
25 commonVideosFiltersValidator,
26 ensureCanManageChannelOrAccount,
32 videoChannelsAddValidator,
33 videoChannelsRemoveValidator,
34 videoChannelsSortValidator,
35 videoChannelsUpdateValidator,
36 videoPlaylistsSortValidator
37 } from '../../middlewares'
39 ensureChannelOwnerCanUpload,
41 videoChannelImportVideosValidator,
42 videoChannelsFollowersSortValidator,
43 videoChannelsListValidator,
44 videoChannelsNameWithHostValidator,
46 } from '../../middlewares/validators'
47 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
48 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
49 import { AccountModel } from '../../models/account/account'
50 import { VideoModel } from '../../models/video/video'
51 import { VideoChannelModel } from '../../models/video/video-channel'
52 import { VideoPlaylistModel } from '../../models/video/video-playlist'
54 const auditLogger = auditLoggerFactory('channels')
55 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
56 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
58 const videoChannelRouter = express.Router()
60 videoChannelRouter.get('/',
62 videoChannelsSortValidator,
65 videoChannelsListValidator,
66 asyncMiddleware(listVideoChannels)
69 videoChannelRouter.post('/',
71 asyncMiddleware(videoChannelsAddValidator),
72 asyncRetryTransactionMiddleware(addVideoChannel)
75 videoChannelRouter.post('/:nameWithHost/avatar/pick',
78 asyncMiddleware(videoChannelsNameWithHostValidator),
80 ensureCanManageChannelOrAccount,
81 updateAvatarValidator,
82 asyncMiddleware(updateVideoChannelAvatar)
85 videoChannelRouter.post('/:nameWithHost/banner/pick',
88 asyncMiddleware(videoChannelsNameWithHostValidator),
90 ensureCanManageChannelOrAccount,
91 updateBannerValidator,
92 asyncMiddleware(updateVideoChannelBanner)
95 videoChannelRouter.delete('/:nameWithHost/avatar',
97 asyncMiddleware(videoChannelsNameWithHostValidator),
99 ensureCanManageChannelOrAccount,
100 asyncMiddleware(deleteVideoChannelAvatar)
103 videoChannelRouter.delete('/:nameWithHost/banner',
105 asyncMiddleware(videoChannelsNameWithHostValidator),
106 ensureIsLocalChannel,
107 ensureCanManageChannelOrAccount,
108 asyncMiddleware(deleteVideoChannelBanner)
111 videoChannelRouter.put('/:nameWithHost',
113 asyncMiddleware(videoChannelsNameWithHostValidator),
114 ensureIsLocalChannel,
115 ensureCanManageChannelOrAccount,
116 videoChannelsUpdateValidator,
117 asyncRetryTransactionMiddleware(updateVideoChannel)
120 videoChannelRouter.delete('/:nameWithHost',
122 asyncMiddleware(videoChannelsNameWithHostValidator),
123 ensureIsLocalChannel,
124 ensureCanManageChannelOrAccount,
125 asyncMiddleware(videoChannelsRemoveValidator),
126 asyncRetryTransactionMiddleware(removeVideoChannel)
129 videoChannelRouter.get('/:nameWithHost',
130 asyncMiddleware(videoChannelsNameWithHostValidator),
131 asyncMiddleware(getVideoChannel)
134 videoChannelRouter.get('/:nameWithHost/video-playlists',
135 asyncMiddleware(videoChannelsNameWithHostValidator),
137 videoPlaylistsSortValidator,
139 setDefaultPagination,
140 commonVideoPlaylistFiltersValidator,
141 asyncMiddleware(listVideoChannelPlaylists)
144 videoChannelRouter.get('/:nameWithHost/videos',
145 asyncMiddleware(videoChannelsNameWithHostValidator),
148 setDefaultVideosSort,
149 setDefaultPagination,
150 optionalAuthenticate,
151 commonVideosFiltersValidator,
152 asyncMiddleware(listVideoChannelVideos)
155 videoChannelRouter.get('/:nameWithHost/followers',
157 asyncMiddleware(videoChannelsNameWithHostValidator),
158 ensureCanManageChannelOrAccount,
160 videoChannelsFollowersSortValidator,
162 setDefaultPagination,
163 asyncMiddleware(listVideoChannelFollowers)
166 videoChannelRouter.post('/:nameWithHost/import-videos',
168 asyncMiddleware(videoChannelsNameWithHostValidator),
169 asyncMiddleware(videoChannelImportVideosValidator),
170 ensureIsLocalChannel,
171 ensureCanManageChannelOrAccount,
172 asyncMiddleware(ensureChannelOwnerCanUpload),
173 asyncMiddleware(importVideosInChannel)
176 // ---------------------------------------------------------------------------
182 // ---------------------------------------------------------------------------
184 async function listVideoChannels (req: express.Request, res: express.Response) {
185 const serverActor = await getServerActor()
187 const apiOptions = await Hooks.wrapObject({
188 actorId: serverActor.id,
189 start: req.query.start,
190 count: req.query.count,
192 }, 'filter:api.video-channels.list.params')
194 const resultList = await Hooks.wrapPromiseFun(
195 VideoChannelModel.listForApi,
197 'filter:api.video-channels.list.result'
200 return res.json(getFormattedObjects(resultList.data, resultList.total))
203 async 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())
208 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
210 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
213 // TODO: remove, deprecated in 4.2
214 banner: getBiggestActorImage(banners).toFormattedJSON(),
215 banners: banners.map(b => b.toFormattedJSON())
219 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
220 const avatarPhysicalFile = req.files['avatarfile'][0]
221 const videoChannel = res.locals.videoChannel
222 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
224 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
225 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
228 // TODO: remove, deprecated in 4.2
229 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
230 avatars: avatars.map(a => a.toFormattedJSON())
234 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
235 const videoChannel = res.locals.videoChannel
237 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
239 return res.status(HttpStatusCode.NO_CONTENT_204).end()
242 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
243 const videoChannel = res.locals.videoChannel
245 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
247 return res.status(HttpStatusCode.NO_CONTENT_204).end()
250 async function addVideoChannel (req: express.Request, res: express.Response) {
251 const videoChannelInfo: VideoChannelCreate = req.body
253 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
254 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
256 return createLocalVideoChannel(videoChannelInfo, account, t)
259 const payload = { actorId: videoChannelCreated.actorId }
260 await JobQueue.Instance.createJob({ type: 'actor-keys', payload })
262 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
263 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
265 Hooks.runAction('action:api.video-channel.created', { videoChannel: videoChannelCreated, req, res })
269 id: videoChannelCreated.id
274 async function updateVideoChannel (req: express.Request, res: express.Response) {
275 const videoChannelInstance = res.locals.videoChannel
276 const videoChannelFieldsSave = videoChannelInstance.toJSON()
277 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
278 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
279 let doBulkVideoUpdate = false
282 await sequelizeTypescript.transaction(async t => {
283 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
284 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
286 if (videoChannelInfoToUpdate.support !== undefined) {
287 const oldSupportField = videoChannelInstance.support
288 videoChannelInstance.support = videoChannelInfoToUpdate.support
290 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
291 doBulkVideoUpdate = true
292 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
296 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
297 await sendUpdateActor(videoChannelInstanceUpdated, t)
300 getAuditIdFromRes(res),
301 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
302 oldVideoChannelAuditKeys
305 Hooks.runAction('action:api.video-channel.updated', { videoChannel: videoChannelInstanceUpdated, req, res })
307 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
310 logger.debug('Cannot update the video channel.', { err })
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)
320 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
322 // Don't process in a transaction, and after the response because it could be long
323 if (doBulkVideoUpdate) {
324 await federateAllVideosOfChannel(videoChannelInstance)
328 async function removeVideoChannel (req: express.Request, res: express.Response) {
329 const videoChannelInstance = res.locals.videoChannel
331 await sequelizeTypescript.transaction(async t => {
332 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
334 await videoChannelInstance.destroy({ transaction: t })
336 Hooks.runAction('action:api.video-channel.deleted', { videoChannel: videoChannelInstance, req, res })
338 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
339 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
342 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
345 async 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 })
349 if (videoChannel.isOutdated()) {
350 JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
353 return res.json(videoChannel.toFormattedJSON())
356 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
357 const serverActor = await getServerActor()
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,
364 videoChannelId: res.locals.videoChannel.id,
365 type: req.query.playlistType
368 return res.json(getFormattedObjects(resultList.data, resultList.total))
371 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
372 const serverActor = await getServerActor()
374 const videoChannelInstance = res.locals.videoChannel
376 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
379 actorId: serverActor.id,
383 const countVideos = getCountVideos(req)
384 const query = pickCommonVideoQuery(req.query)
386 const apiOptions = await Hooks.wrapObject({
389 displayOnlyForFollower,
390 nsfw: buildNSFWFilter(res, query.nsfw),
391 videoChannelId: videoChannelInstance.id,
392 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
394 }, 'filter:api.video-channels.videos.list.params')
396 const resultList = await Hooks.wrapPromiseFun(
397 VideoModel.listForApi,
399 'filter:api.video-channels.videos.list.result'
402 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
405 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
406 const channel = res.locals.videoChannel
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,
417 return res.json(getFormattedObjects(resultList.data, resultList.total))
420 async function importVideosInChannel (req: express.Request, res: express.Response) {
421 const { externalChannelUrl } = req.body as VideosImportInChannelCreate
423 await JobQueue.Instance.createJob({
424 type: 'video-channel-import',
427 videoChannelId: res.locals.videoChannel.id,
428 partOfChannelSyncId: res.locals.videoChannelSync?.id
432 logger.info('Video import job for channel "%s" with url "%s" created.', res.locals.videoChannel.name, externalChannelUrl)
434 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()