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 { 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, updateLocalActorImageFiles } from '../../lib/local-actor'
21 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
24 asyncRetryTransactionMiddleware,
26 commonVideosFiltersValidator,
27 ensureCanManageChannel,
33 videoChannelsAddValidator,
34 videoChannelsRemoveValidator,
35 videoChannelsSortValidator,
36 videoChannelsUpdateValidator,
37 videoPlaylistsSortValidator
38 } from '../../middlewares'
41 videoChannelsFollowersSortValidator,
42 videoChannelsListValidator,
43 videoChannelsNameWithHostValidator,
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'
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 })
57 const videoChannelRouter = express.Router()
59 videoChannelRouter.get('/',
61 videoChannelsSortValidator,
64 videoChannelsListValidator,
65 asyncMiddleware(listVideoChannels)
68 videoChannelRouter.post('/',
70 asyncMiddleware(videoChannelsAddValidator),
71 asyncRetryTransactionMiddleware(addVideoChannel)
74 videoChannelRouter.post('/:nameWithHost/avatar/pick',
77 asyncMiddleware(videoChannelsNameWithHostValidator),
79 ensureCanManageChannel,
80 updateAvatarValidator,
81 asyncMiddleware(updateVideoChannelAvatar)
84 videoChannelRouter.post('/:nameWithHost/banner/pick',
87 asyncMiddleware(videoChannelsNameWithHostValidator),
89 ensureCanManageChannel,
90 updateBannerValidator,
91 asyncMiddleware(updateVideoChannelBanner)
94 videoChannelRouter.delete('/:nameWithHost/avatar',
96 asyncMiddleware(videoChannelsNameWithHostValidator),
98 ensureCanManageChannel,
99 asyncMiddleware(deleteVideoChannelAvatar)
102 videoChannelRouter.delete('/:nameWithHost/banner',
104 asyncMiddleware(videoChannelsNameWithHostValidator),
105 ensureIsLocalChannel,
106 ensureCanManageChannel,
107 asyncMiddleware(deleteVideoChannelBanner)
110 videoChannelRouter.put('/:nameWithHost',
112 asyncMiddleware(videoChannelsNameWithHostValidator),
113 ensureIsLocalChannel,
114 ensureCanManageChannel,
115 videoChannelsUpdateValidator,
116 asyncRetryTransactionMiddleware(updateVideoChannel)
119 videoChannelRouter.delete('/:nameWithHost',
121 asyncMiddleware(videoChannelsNameWithHostValidator),
122 ensureIsLocalChannel,
123 ensureCanManageChannel,
124 asyncMiddleware(videoChannelsRemoveValidator),
125 asyncRetryTransactionMiddleware(removeVideoChannel)
128 videoChannelRouter.get('/:nameWithHost',
129 asyncMiddleware(videoChannelsNameWithHostValidator),
133 videoChannelRouter.get('/:nameWithHost/video-playlists',
134 asyncMiddleware(videoChannelsNameWithHostValidator),
136 videoPlaylistsSortValidator,
138 setDefaultPagination,
139 commonVideoPlaylistFiltersValidator,
140 asyncMiddleware(listVideoChannelPlaylists)
143 videoChannelRouter.get('/:nameWithHost/videos',
144 asyncMiddleware(videoChannelsNameWithHostValidator),
147 setDefaultVideosSort,
148 setDefaultPagination,
149 optionalAuthenticate,
150 commonVideosFiltersValidator,
151 asyncMiddleware(listVideoChannelVideos)
154 videoChannelRouter.get('/:nameWithHost/followers',
156 asyncMiddleware(videoChannelsNameWithHostValidator),
157 ensureCanManageChannel,
159 videoChannelsFollowersSortValidator,
161 setDefaultPagination,
162 asyncMiddleware(listVideoChannelFollowers)
165 // ---------------------------------------------------------------------------
171 // ---------------------------------------------------------------------------
173 async function listVideoChannels (req: express.Request, res: express.Response) {
174 const serverActor = await getServerActor()
175 const resultList = await VideoChannelModel.listForApi({
176 actorId: serverActor.id,
177 start: req.query.start,
178 count: req.query.count,
182 return res.json(getFormattedObjects(resultList.data, resultList.total))
185 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
186 const bannerPhysicalFile = req.files['bannerfile'][0]
187 const videoChannel = res.locals.videoChannel
188 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
190 const banners = await updateLocalActorImageFiles(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
192 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
195 // TODO: remove, deprecated in 4.2
196 banner: getBiggestActorImage(banners).toFormattedJSON(),
197 banners: banners.map(b => b.toFormattedJSON())
201 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
202 const avatarPhysicalFile = req.files['avatarfile'][0]
203 const videoChannel = res.locals.videoChannel
204 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
206 const avatars = await updateLocalActorImageFiles(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
207 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
210 // TODO: remove, deprecated in 4.2
211 avatar: getBiggestActorImage(avatars).toFormattedJSON(),
212 avatars: avatars.map(a => a.toFormattedJSON())
216 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
217 const videoChannel = res.locals.videoChannel
219 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
221 return res.status(HttpStatusCode.NO_CONTENT_204).end()
224 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
225 const videoChannel = res.locals.videoChannel
227 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
229 return res.status(HttpStatusCode.NO_CONTENT_204).end()
232 async function addVideoChannel (req: express.Request, res: express.Response) {
233 const videoChannelInfo: VideoChannelCreate = req.body
235 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
236 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
238 return createLocalVideoChannel(videoChannelInfo, account, t)
241 const payload = { actorId: videoChannelCreated.actorId }
242 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
244 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
245 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
249 id: videoChannelCreated.id
254 async function updateVideoChannel (req: express.Request, res: express.Response) {
255 const videoChannelInstance = res.locals.videoChannel
256 const videoChannelFieldsSave = videoChannelInstance.toJSON()
257 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
258 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
259 let doBulkVideoUpdate = false
262 await sequelizeTypescript.transaction(async t => {
263 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
264 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
266 if (videoChannelInfoToUpdate.support !== undefined) {
267 const oldSupportField = videoChannelInstance.support
268 videoChannelInstance.support = videoChannelInfoToUpdate.support
270 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
271 doBulkVideoUpdate = true
272 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
276 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
277 await sendUpdateActor(videoChannelInstanceUpdated, t)
280 getAuditIdFromRes(res),
281 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
282 oldVideoChannelAuditKeys
285 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
288 logger.debug('Cannot update the video channel.', { err })
290 // Force fields we want to update
291 // If the transaction is retried, sequelize will think the object has not changed
292 // So it will skip the SQL request, even if the last one was ROLLBACKed!
293 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
298 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
300 // Don't process in a transaction, and after the response because it could be long
301 if (doBulkVideoUpdate) {
302 await federateAllVideosOfChannel(videoChannelInstance)
306 async function removeVideoChannel (req: express.Request, res: express.Response) {
307 const videoChannelInstance = res.locals.videoChannel
309 await sequelizeTypescript.transaction(async t => {
310 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
312 await videoChannelInstance.destroy({ transaction: t })
314 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
315 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
318 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
321 function getVideoChannel (req: express.Request, res: express.Response) {
322 const videoChannel = res.locals.videoChannel
324 if (videoChannel.isOutdated()) {
325 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
328 return res.json(videoChannel.toFormattedJSON())
331 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
332 const serverActor = await getServerActor()
334 const resultList = await VideoPlaylistModel.listForApi({
335 followerActorId: serverActor.id,
336 start: req.query.start,
337 count: req.query.count,
338 sort: req.query.sort,
339 videoChannelId: res.locals.videoChannel.id,
340 type: req.query.playlistType
343 return res.json(getFormattedObjects(resultList.data, resultList.total))
346 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
347 const serverActor = await getServerActor()
349 const videoChannelInstance = res.locals.videoChannel
351 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
354 actorId: serverActor.id,
358 const countVideos = getCountVideos(req)
359 const query = pickCommonVideoQuery(req.query)
361 const apiOptions = await Hooks.wrapObject({
364 displayOnlyForFollower,
365 nsfw: buildNSFWFilter(res, query.nsfw),
366 videoChannelId: videoChannelInstance.id,
367 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
369 }, 'filter:api.video-channels.videos.list.params')
371 const resultList = await Hooks.wrapPromiseFun(
372 VideoModel.listForApi,
374 'filter:api.video-channels.videos.list.result'
377 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
380 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
381 const channel = res.locals.videoChannel
383 const resultList = await ActorFollowModel.listFollowersForApi({
384 actorIds: [ channel.actorId ],
385 start: req.query.start,
386 count: req.query.count,
387 sort: req.query.sort,
388 search: req.query.search,
392 return res.json(getFormattedObjects(resultList.data, resultList.total))