1 import express from 'express'
2 import { pickCommonVideoQuery } from '@server/helpers/query'
3 import { Hooks } from '@server/lib/plugins/hooks'
4 import { ActorFollowModel } from '@server/models/actor/actor-follow'
5 import { getServerActor } from '@server/models/application/application'
6 import { guessAdditionalAttributesFromQuery } from '@server/models/video/formatter/video-format-utils'
7 import { MChannelBannerAccountDefault } from '@server/types/models'
8 import { ActorImageType, VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
9 import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
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, updateLocalActorImageFile } 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 banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
192 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
194 return res.json({ banner: banner.toFormattedJSON() })
197 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
198 const avatarPhysicalFile = req.files['avatarfile'][0]
199 const videoChannel = res.locals.videoChannel
200 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
202 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
204 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
206 return res.json({ avatar: avatar.toFormattedJSON() })
209 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
210 const videoChannel = res.locals.videoChannel
212 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
214 return res.status(HttpStatusCode.NO_CONTENT_204).end()
217 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
218 const videoChannel = res.locals.videoChannel
220 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
222 return res.status(HttpStatusCode.NO_CONTENT_204).end()
225 async function addVideoChannel (req: express.Request, res: express.Response) {
226 const videoChannelInfo: VideoChannelCreate = req.body
228 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
229 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
231 return createLocalVideoChannel(videoChannelInfo, account, t)
234 const payload = { actorId: videoChannelCreated.actorId }
235 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
237 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
238 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
242 id: videoChannelCreated.id
247 async function updateVideoChannel (req: express.Request, res: express.Response) {
248 const videoChannelInstance = res.locals.videoChannel
249 const videoChannelFieldsSave = videoChannelInstance.toJSON()
250 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
251 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
252 let doBulkVideoUpdate = false
255 await sequelizeTypescript.transaction(async t => {
256 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
257 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
259 if (videoChannelInfoToUpdate.support !== undefined) {
260 const oldSupportField = videoChannelInstance.support
261 videoChannelInstance.support = videoChannelInfoToUpdate.support
263 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
264 doBulkVideoUpdate = true
265 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
269 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
270 await sendUpdateActor(videoChannelInstanceUpdated, t)
273 getAuditIdFromRes(res),
274 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
275 oldVideoChannelAuditKeys
278 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
281 logger.debug('Cannot update the video channel.', { err })
283 // Force fields we want to update
284 // If the transaction is retried, sequelize will think the object has not changed
285 // So it will skip the SQL request, even if the last one was ROLLBACKed!
286 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
291 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
293 // Don't process in a transaction, and after the response because it could be long
294 if (doBulkVideoUpdate) {
295 await federateAllVideosOfChannel(videoChannelInstance)
299 async function removeVideoChannel (req: express.Request, res: express.Response) {
300 const videoChannelInstance = res.locals.videoChannel
302 await sequelizeTypescript.transaction(async t => {
303 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
305 await videoChannelInstance.destroy({ transaction: t })
307 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
308 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
311 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
314 function getVideoChannel (req: express.Request, res: express.Response) {
315 const videoChannel = res.locals.videoChannel
317 if (videoChannel.isOutdated()) {
318 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
321 return res.json(videoChannel.toFormattedJSON())
324 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
325 const serverActor = await getServerActor()
327 const resultList = await VideoPlaylistModel.listForApi({
328 followerActorId: serverActor.id,
329 start: req.query.start,
330 count: req.query.count,
331 sort: req.query.sort,
332 videoChannelId: res.locals.videoChannel.id,
333 type: req.query.playlistType
336 return res.json(getFormattedObjects(resultList.data, resultList.total))
339 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
340 const serverActor = await getServerActor()
342 const videoChannelInstance = res.locals.videoChannel
344 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
347 actorId: serverActor.id,
351 const countVideos = getCountVideos(req)
352 const query = pickCommonVideoQuery(req.query)
354 const apiOptions = await Hooks.wrapObject({
357 displayOnlyForFollower,
358 nsfw: buildNSFWFilter(res, query.nsfw),
359 videoChannelId: videoChannelInstance.id,
360 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
362 }, 'filter:api.video-channels.videos.list.params')
364 const resultList = await Hooks.wrapPromiseFun(
365 VideoModel.listForApi,
367 'filter:api.video-channels.videos.list.result'
370 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
373 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
374 const channel = res.locals.videoChannel
376 const resultList = await ActorFollowModel.listFollowersForApi({
377 actorIds: [ channel.actorId ],
378 start: req.query.start,
379 count: req.query.count,
380 sort: req.query.sort,
381 search: req.query.search,
385 return res.json(getFormattedObjects(resultList.data, resultList.total))