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 ensureUserCanManageChannel,
33 videoChannelsAddValidator,
34 videoChannelsRemoveValidator,
35 videoChannelsSortValidator,
36 videoChannelsUpdateValidator,
37 videoPlaylistsSortValidator
38 } from '../../middlewares'
40 ensureAuthUserOwnsChannelValidator,
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),
78 ensureUserCanManageChannel,
79 updateAvatarValidator,
80 asyncMiddleware(updateVideoChannelAvatar)
83 videoChannelRouter.post('/:nameWithHost/banner/pick',
86 asyncMiddleware(videoChannelsNameWithHostValidator),
87 ensureUserCanManageChannel,
88 updateBannerValidator,
89 asyncMiddleware(updateVideoChannelBanner)
92 videoChannelRouter.delete('/:nameWithHost/avatar',
94 asyncMiddleware(videoChannelsNameWithHostValidator),
95 ensureUserCanManageChannel,
96 asyncMiddleware(deleteVideoChannelAvatar)
99 videoChannelRouter.delete('/:nameWithHost/banner',
101 asyncMiddleware(videoChannelsNameWithHostValidator),
102 ensureUserCanManageChannel,
103 asyncMiddleware(deleteVideoChannelBanner)
106 videoChannelRouter.put('/:nameWithHost',
108 asyncMiddleware(videoChannelsNameWithHostValidator),
109 ensureUserCanManageChannel,
110 videoChannelsUpdateValidator,
111 asyncRetryTransactionMiddleware(updateVideoChannel)
114 videoChannelRouter.delete('/:nameWithHost',
116 asyncMiddleware(videoChannelsRemoveValidator),
117 asyncRetryTransactionMiddleware(removeVideoChannel)
120 videoChannelRouter.get('/:nameWithHost',
121 asyncMiddleware(videoChannelsNameWithHostValidator),
125 videoChannelRouter.get('/:nameWithHost/video-playlists',
126 asyncMiddleware(videoChannelsNameWithHostValidator),
128 videoPlaylistsSortValidator,
130 setDefaultPagination,
131 commonVideoPlaylistFiltersValidator,
132 asyncMiddleware(listVideoChannelPlaylists)
135 videoChannelRouter.get('/:nameWithHost/videos',
136 asyncMiddleware(videoChannelsNameWithHostValidator),
139 setDefaultVideosSort,
140 setDefaultPagination,
141 optionalAuthenticate,
142 commonVideosFiltersValidator,
143 asyncMiddleware(listVideoChannelVideos)
146 videoChannelRouter.get('/:nameWithHost/followers',
148 asyncMiddleware(videoChannelsNameWithHostValidator),
149 ensureAuthUserOwnsChannelValidator,
151 videoChannelsFollowersSortValidator,
153 setDefaultPagination,
154 asyncMiddleware(listVideoChannelFollowers)
157 // ---------------------------------------------------------------------------
163 // ---------------------------------------------------------------------------
165 async function listVideoChannels (req: express.Request, res: express.Response) {
166 const serverActor = await getServerActor()
167 const resultList = await VideoChannelModel.listForApi({
168 actorId: serverActor.id,
169 start: req.query.start,
170 count: req.query.count,
174 return res.json(getFormattedObjects(resultList.data, resultList.total))
177 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
178 const bannerPhysicalFile = req.files['bannerfile'][0]
179 const videoChannel = res.locals.videoChannel
180 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
182 const banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
184 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
186 return res.json({ banner: banner.toFormattedJSON() })
189 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
190 const avatarPhysicalFile = req.files['avatarfile'][0]
191 const videoChannel = res.locals.videoChannel
192 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
194 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
196 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
198 return res.json({ avatar: avatar.toFormattedJSON() })
201 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
202 const videoChannel = res.locals.videoChannel
204 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
206 return res.status(HttpStatusCode.NO_CONTENT_204).end()
209 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
210 const videoChannel = res.locals.videoChannel
212 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
214 return res.status(HttpStatusCode.NO_CONTENT_204).end()
217 async function addVideoChannel (req: express.Request, res: express.Response) {
218 const videoChannelInfo: VideoChannelCreate = req.body
220 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
221 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
223 return createLocalVideoChannel(videoChannelInfo, account, t)
226 const payload = { actorId: videoChannelCreated.actorId }
227 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
229 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
230 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
234 id: videoChannelCreated.id
239 async function updateVideoChannel (req: express.Request, res: express.Response) {
240 const videoChannelInstance = res.locals.videoChannel
241 const videoChannelFieldsSave = videoChannelInstance.toJSON()
242 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
243 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
244 let doBulkVideoUpdate = false
247 await sequelizeTypescript.transaction(async t => {
248 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
249 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
251 if (videoChannelInfoToUpdate.support !== undefined) {
252 const oldSupportField = videoChannelInstance.support
253 videoChannelInstance.support = videoChannelInfoToUpdate.support
255 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
256 doBulkVideoUpdate = true
257 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
261 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
262 await sendUpdateActor(videoChannelInstanceUpdated, t)
265 getAuditIdFromRes(res),
266 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
267 oldVideoChannelAuditKeys
270 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
273 logger.debug('Cannot update the video channel.', { err })
275 // Force fields we want to update
276 // If the transaction is retried, sequelize will think the object has not changed
277 // So it will skip the SQL request, even if the last one was ROLLBACKed!
278 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
283 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
285 // Don't process in a transaction, and after the response because it could be long
286 if (doBulkVideoUpdate) {
287 await federateAllVideosOfChannel(videoChannelInstance)
291 async function removeVideoChannel (req: express.Request, res: express.Response) {
292 const videoChannelInstance = res.locals.videoChannel
294 await sequelizeTypescript.transaction(async t => {
295 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
297 await videoChannelInstance.destroy({ transaction: t })
299 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
300 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
303 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
306 function getVideoChannel (req: express.Request, res: express.Response) {
307 const videoChannel = res.locals.videoChannel
309 if (videoChannel.isOutdated()) {
310 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
313 return res.json(videoChannel.toFormattedJSON())
316 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
317 const serverActor = await getServerActor()
319 const resultList = await VideoPlaylistModel.listForApi({
320 followerActorId: serverActor.id,
321 start: req.query.start,
322 count: req.query.count,
323 sort: req.query.sort,
324 videoChannelId: res.locals.videoChannel.id,
325 type: req.query.playlistType
328 return res.json(getFormattedObjects(resultList.data, resultList.total))
331 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
332 const serverActor = await getServerActor()
334 const videoChannelInstance = res.locals.videoChannel
336 const displayOnlyForFollower = isUserAbleToSearchRemoteURI(res)
339 actorId: serverActor.id,
343 const countVideos = getCountVideos(req)
344 const query = pickCommonVideoQuery(req.query)
346 const apiOptions = await Hooks.wrapObject({
349 displayOnlyForFollower,
350 nsfw: buildNSFWFilter(res, query.nsfw),
351 videoChannelId: videoChannelInstance.id,
352 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
354 }, 'filter:api.video-channels.videos.list.params')
356 const resultList = await Hooks.wrapPromiseFun(
357 VideoModel.listForApi,
359 'filter:api.video-channels.videos.list.result'
362 return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
365 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
366 const channel = res.locals.videoChannel
368 const resultList = await ActorFollowModel.listFollowersForApi({
369 actorIds: [ channel.actorId ],
370 start: req.query.start,
371 count: req.query.count,
372 sort: req.query.sort,
373 search: req.query.search,
377 return res.json(getFormattedObjects(resultList.data, resultList.total))