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 } 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 ensureCanManageChannel,
32 videoChannelsAddValidator,
33 videoChannelsRemoveValidator,
34 videoChannelsSortValidator,
35 videoChannelsUpdateValidator,
36 videoPlaylistsSortValidator
37 } from '../../middlewares'
40 videoChannelsFollowersSortValidator,
41 videoChannelsListValidator,
42 videoChannelsNameWithHostValidator,
44 } from '../../middlewares/validators'
45 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
46 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
47 import { AccountModel } from '../../models/account/account'
48 import { VideoModel } from '../../models/video/video'
49 import { VideoChannelModel } from '../../models/video/video-channel'
50 import { VideoPlaylistModel } from '../../models/video/video-playlist'
52 const auditLogger = auditLoggerFactory('channels')
53 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
54 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
56 const videoChannelRouter = express.Router()
58 videoChannelRouter.get('/',
60 videoChannelsSortValidator,
63 videoChannelsListValidator,
64 asyncMiddleware(listVideoChannels)
67 videoChannelRouter.post('/',
69 asyncMiddleware(videoChannelsAddValidator),
70 asyncRetryTransactionMiddleware(addVideoChannel)
73 videoChannelRouter.post('/:nameWithHost/avatar/pick',
76 asyncMiddleware(videoChannelsNameWithHostValidator),
78 ensureCanManageChannel,
79 updateAvatarValidator,
80 asyncMiddleware(updateVideoChannelAvatar)
83 videoChannelRouter.post('/:nameWithHost/banner/pick',
86 asyncMiddleware(videoChannelsNameWithHostValidator),
88 ensureCanManageChannel,
89 updateBannerValidator,
90 asyncMiddleware(updateVideoChannelBanner)
93 videoChannelRouter.delete('/:nameWithHost/avatar',
95 asyncMiddleware(videoChannelsNameWithHostValidator),
97 ensureCanManageChannel,
98 asyncMiddleware(deleteVideoChannelAvatar)
101 videoChannelRouter.delete('/:nameWithHost/banner',
103 asyncMiddleware(videoChannelsNameWithHostValidator),
104 ensureIsLocalChannel,
105 ensureCanManageChannel,
106 asyncMiddleware(deleteVideoChannelBanner)
109 videoChannelRouter.put('/:nameWithHost',
111 asyncMiddleware(videoChannelsNameWithHostValidator),
112 ensureIsLocalChannel,
113 ensureCanManageChannel,
114 videoChannelsUpdateValidator,
115 asyncRetryTransactionMiddleware(updateVideoChannel)
118 videoChannelRouter.delete('/:nameWithHost',
120 asyncMiddleware(videoChannelsNameWithHostValidator),
121 ensureIsLocalChannel,
122 ensureCanManageChannel,
123 asyncMiddleware(videoChannelsRemoveValidator),
124 asyncRetryTransactionMiddleware(removeVideoChannel)
127 videoChannelRouter.get('/:nameWithHost',
128 asyncMiddleware(videoChannelsNameWithHostValidator),
132 videoChannelRouter.get('/:nameWithHost/video-playlists',
133 asyncMiddleware(videoChannelsNameWithHostValidator),
135 videoPlaylistsSortValidator,
137 setDefaultPagination,
138 commonVideoPlaylistFiltersValidator,
139 asyncMiddleware(listVideoChannelPlaylists)
142 videoChannelRouter.get('/:nameWithHost/videos',
143 asyncMiddleware(videoChannelsNameWithHostValidator),
146 setDefaultVideosSort,
147 setDefaultPagination,
148 optionalAuthenticate,
149 commonVideosFiltersValidator,
150 asyncMiddleware(listVideoChannelVideos)
153 videoChannelRouter.get('/:nameWithHost/followers',
155 asyncMiddleware(videoChannelsNameWithHostValidator),
156 ensureCanManageChannel,
158 videoChannelsFollowersSortValidator,
160 setDefaultPagination,
161 asyncMiddleware(listVideoChannelFollowers)
164 // ---------------------------------------------------------------------------
170 // ---------------------------------------------------------------------------
172 async function listVideoChannels (req: express.Request, res: express.Response) {
173 const serverActor = await getServerActor()
174 const resultList = await VideoChannelModel.listForApi({
175 actorId: serverActor.id,
176 start: req.query.start,
177 count: req.query.count,
181 return res.json(getFormattedObjects(resultList.data, resultList.total))
184 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
185 const bannerPhysicalFile = req.files['bannerfile'][0]
186 const videoChannel = res.locals.videoChannel
187 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
189 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
191 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
194 // TODO: remove, deprecated in 4.2
195 banner: getBiggestActorImage(banners).toFormattedJSON(),
196 banners: banners.map(b => b.toFormattedJSON())
200 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
201 const avatarPhysicalFile = req.files['avatarfile'][0]
202 const videoChannel = res.locals.videoChannel
203 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
205 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
206 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
209 // TODO: remove, deprecated in 4.2
210 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
211 avatars: avatars.map(a => a.toFormattedJSON())
215 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
216 const videoChannel = res.locals.videoChannel
218 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
220 return res.status(HttpStatusCode.NO_CONTENT_204).end()
223 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
224 const videoChannel = res.locals.videoChannel
226 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
228 return res.status(HttpStatusCode.NO_CONTENT_204).end()
231 async function addVideoChannel (req: express.Request, res: express.Response) {
232 const videoChannelInfo: VideoChannelCreate = req.body
234 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
235 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
237 return createLocalVideoChannel(videoChannelInfo, account, t)
240 const payload = { actorId: videoChannelCreated.actorId }
241 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
243 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
244 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
248 id: videoChannelCreated.id
253 async function updateVideoChannel (req: express.Request, res: express.Response) {
254 const videoChannelInstance = res.locals.videoChannel
255 const videoChannelFieldsSave = videoChannelInstance.toJSON()
256 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
257 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
258 let doBulkVideoUpdate = false
261 await sequelizeTypescript.transaction(async t => {
262 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
263 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
265 if (videoChannelInfoToUpdate.support !== undefined) {
266 const oldSupportField = videoChannelInstance.support
267 videoChannelInstance.support = videoChannelInfoToUpdate.support
269 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
270 doBulkVideoUpdate = true
271 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
275 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
276 await sendUpdateActor(videoChannelInstanceUpdated, t)
279 getAuditIdFromRes(res),
280 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
281 oldVideoChannelAuditKeys
284 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
287 logger.debug('Cannot update the video channel.', { err })
289 // Force fields we want to update
290 // If the transaction is retried, sequelize will think the object has not changed
291 // So it will skip the SQL request, even if the last one was ROLLBACKed!
292 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
297 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
299 // Don't process in a transaction, and after the response because it could be long
300 if (doBulkVideoUpdate) {
301 await federateAllVideosOfChannel(videoChannelInstance)
305 async function removeVideoChannel (req: express.Request, res: express.Response) {
306 const videoChannelInstance = res.locals.videoChannel
308 await sequelizeTypescript.transaction(async t => {
309 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
311 await videoChannelInstance.destroy({ transaction: t })
313 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
314 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
317 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
320 function getVideoChannel (req: express.Request, res: express.Response) {
321 const videoChannel = res.locals.videoChannel
323 if (videoChannel.isOutdated()) {
324 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
327 return res.json(videoChannel.toFormattedJSON())
330 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
331 const serverActor = await getServerActor()
333 const resultList = await VideoPlaylistModel.listForApi({
334 followerActorId: serverActor.id,
335 start: req.query.start,
336 count: req.query.count,
337 sort: req.query.sort,
338 videoChannelId: res.locals.videoChannel.id,
339 type: req.query.playlistType
342 return res.json(getFormattedObjects(resultList.data, resultList.total))
345 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
346 const serverActor = await getServerActor()
348 const videoChannelInstance = res.locals.videoChannel
350 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
353 actorId: serverActor.id,
357 const countVideos = getCountVideos(req)
358 const query = pickCommonVideoQuery(req.query)
360 const apiOptions = await Hooks.wrapObject({
363 displayOnlyForFollower,
364 nsfw: buildNSFWFilter(res, query.nsfw),
365 videoChannelId: videoChannelInstance.id,
366 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
368 }, 'filter:api.video-channels.videos.list.params')
370 const resultList = await Hooks.wrapPromiseFun(
371 VideoModel.listForApi,
373 'filter:api.video-channels.videos.list.result'
376 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
379 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
380 const channel = res.locals.videoChannel
382 const resultList = await ActorFollowModel.listFollowersForApi({
383 actorIds: [ channel.actorId ],
384 start: req.query.start,
385 count: req.query.count,
386 sort: req.query.sort,
387 search: req.query.search,
391 return res.json(getFormattedObjects(resultList.data, resultList.total))