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 { MChannelBannerAccountDefault } from '@server/types/models'
7 import { ActorImageType, VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
8 import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
9 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
10 import { resetSequelizeInstance } from '../../helpers/database-utils'
11 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
12 import { logger } from '../../helpers/logger'
13 import { getFormattedObjects } from '../../helpers/utils'
14 import { CONFIG } from '../../initializers/config'
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, updateLocalActorImageFile } from '../../lib/local-actor'
20 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
23 asyncRetryTransactionMiddleware,
25 commonVideosFiltersValidator,
31 videoChannelsAddValidator,
32 videoChannelsRemoveValidator,
33 videoChannelsSortValidator,
34 videoChannelsUpdateValidator,
35 videoPlaylistsSortValidator
36 } from '../../middlewares'
38 ensureAuthUserOwnsChannelValidator,
39 videoChannelsFollowersSortValidator,
40 videoChannelsListValidator,
41 videoChannelsNameWithHostValidator,
43 } from '../../middlewares/validators'
44 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
45 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
46 import { AccountModel } from '../../models/account/account'
47 import { VideoModel } from '../../models/video/video'
48 import { VideoChannelModel } from '../../models/video/video-channel'
49 import { VideoPlaylistModel } from '../../models/video/video-playlist'
51 const auditLogger = auditLoggerFactory('channels')
52 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
53 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { bannerfile: CONFIG.STORAGE.TMP_DIR })
55 const videoChannelRouter = express.Router()
57 videoChannelRouter.get('/',
59 videoChannelsSortValidator,
62 videoChannelsListValidator,
63 asyncMiddleware(listVideoChannels)
66 videoChannelRouter.post('/',
68 asyncMiddleware(videoChannelsAddValidator),
69 asyncRetryTransactionMiddleware(addVideoChannel)
72 videoChannelRouter.post('/:nameWithHost/avatar/pick',
75 asyncMiddleware(videoChannelsNameWithHostValidator),
76 ensureAuthUserOwnsChannelValidator,
77 updateAvatarValidator,
78 asyncMiddleware(updateVideoChannelAvatar)
81 videoChannelRouter.post('/:nameWithHost/banner/pick',
84 asyncMiddleware(videoChannelsNameWithHostValidator),
85 ensureAuthUserOwnsChannelValidator,
86 updateBannerValidator,
87 asyncMiddleware(updateVideoChannelBanner)
90 videoChannelRouter.delete('/:nameWithHost/avatar',
92 asyncMiddleware(videoChannelsNameWithHostValidator),
93 ensureAuthUserOwnsChannelValidator,
94 asyncMiddleware(deleteVideoChannelAvatar)
97 videoChannelRouter.delete('/:nameWithHost/banner',
99 asyncMiddleware(videoChannelsNameWithHostValidator),
100 ensureAuthUserOwnsChannelValidator,
101 asyncMiddleware(deleteVideoChannelBanner)
104 videoChannelRouter.put('/:nameWithHost',
106 asyncMiddleware(videoChannelsNameWithHostValidator),
107 ensureAuthUserOwnsChannelValidator,
108 videoChannelsUpdateValidator,
109 asyncRetryTransactionMiddleware(updateVideoChannel)
112 videoChannelRouter.delete('/:nameWithHost',
114 asyncMiddleware(videoChannelsRemoveValidator),
115 asyncRetryTransactionMiddleware(removeVideoChannel)
118 videoChannelRouter.get('/:nameWithHost',
119 asyncMiddleware(videoChannelsNameWithHostValidator),
123 videoChannelRouter.get('/:nameWithHost/video-playlists',
124 asyncMiddleware(videoChannelsNameWithHostValidator),
126 videoPlaylistsSortValidator,
128 setDefaultPagination,
129 commonVideoPlaylistFiltersValidator,
130 asyncMiddleware(listVideoChannelPlaylists)
133 videoChannelRouter.get('/:nameWithHost/videos',
134 asyncMiddleware(videoChannelsNameWithHostValidator),
137 setDefaultVideosSort,
138 setDefaultPagination,
139 optionalAuthenticate,
140 commonVideosFiltersValidator,
141 asyncMiddleware(listVideoChannelVideos)
144 videoChannelRouter.get('/:nameWithHost/followers',
146 asyncMiddleware(videoChannelsNameWithHostValidator),
147 ensureAuthUserOwnsChannelValidator,
149 videoChannelsFollowersSortValidator,
151 setDefaultPagination,
152 asyncMiddleware(listVideoChannelFollowers)
155 // ---------------------------------------------------------------------------
161 // ---------------------------------------------------------------------------
163 async function listVideoChannels (req: express.Request, res: express.Response) {
164 const serverActor = await getServerActor()
165 const resultList = await VideoChannelModel.listForApi({
166 actorId: serverActor.id,
167 start: req.query.start,
168 count: req.query.count,
172 return res.json(getFormattedObjects(resultList.data, resultList.total))
175 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
176 const bannerPhysicalFile = req.files['bannerfile'][0]
177 const videoChannel = res.locals.videoChannel
178 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
180 const banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
182 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
184 return res.json({ banner: banner.toFormattedJSON() })
187 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
188 const avatarPhysicalFile = req.files['avatarfile'][0]
189 const videoChannel = res.locals.videoChannel
190 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
192 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
194 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
196 return res.json({ avatar: avatar.toFormattedJSON() })
199 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
200 const videoChannel = res.locals.videoChannel
202 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
204 return res.status(HttpStatusCode.NO_CONTENT_204).end()
207 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
208 const videoChannel = res.locals.videoChannel
210 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
212 return res.status(HttpStatusCode.NO_CONTENT_204).end()
215 async function addVideoChannel (req: express.Request, res: express.Response) {
216 const videoChannelInfo: VideoChannelCreate = req.body
218 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
219 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
221 return createLocalVideoChannel(videoChannelInfo, account, t)
224 const payload = { actorId: videoChannelCreated.actorId }
225 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
227 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
228 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
232 id: videoChannelCreated.id
237 async function updateVideoChannel (req: express.Request, res: express.Response) {
238 const videoChannelInstance = res.locals.videoChannel
239 const videoChannelFieldsSave = videoChannelInstance.toJSON()
240 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
241 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
242 let doBulkVideoUpdate = false
245 await sequelizeTypescript.transaction(async t => {
246 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
247 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
249 if (videoChannelInfoToUpdate.support !== undefined) {
250 const oldSupportField = videoChannelInstance.support
251 videoChannelInstance.support = videoChannelInfoToUpdate.support
253 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
254 doBulkVideoUpdate = true
255 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
259 const videoChannelInstanceUpdated = await videoChannelInstance.save({ transaction: t }) as MChannelBannerAccountDefault
260 await sendUpdateActor(videoChannelInstanceUpdated, t)
263 getAuditIdFromRes(res),
264 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
265 oldVideoChannelAuditKeys
268 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
271 logger.debug('Cannot update the video channel.', { err })
273 // Force fields we want to update
274 // If the transaction is retried, sequelize will think the object has not changed
275 // So it will skip the SQL request, even if the last one was ROLLBACKed!
276 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
281 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
283 // Don't process in a transaction, and after the response because it could be long
284 if (doBulkVideoUpdate) {
285 await federateAllVideosOfChannel(videoChannelInstance)
289 async function removeVideoChannel (req: express.Request, res: express.Response) {
290 const videoChannelInstance = res.locals.videoChannel
292 await sequelizeTypescript.transaction(async t => {
293 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
295 await videoChannelInstance.destroy({ transaction: t })
297 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
298 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
301 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
304 function getVideoChannel (req: express.Request, res: express.Response) {
305 const videoChannel = res.locals.videoChannel
307 if (videoChannel.isOutdated()) {
308 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
311 return res.json(videoChannel.toFormattedJSON())
314 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
315 const serverActor = await getServerActor()
317 const resultList = await VideoPlaylistModel.listForApi({
318 followerActorId: serverActor.id,
319 start: req.query.start,
320 count: req.query.count,
321 sort: req.query.sort,
322 videoChannelId: res.locals.videoChannel.id,
323 type: req.query.playlistType
326 return res.json(getFormattedObjects(resultList.data, resultList.total))
329 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
330 const videoChannelInstance = res.locals.videoChannel
331 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
332 const countVideos = getCountVideos(req)
333 const query = pickCommonVideoQuery(req.query)
335 const apiOptions = await Hooks.wrapObject({
339 includeLocalVideos: true,
340 nsfw: buildNSFWFilter(res, query.nsfw),
342 videoChannelId: videoChannelInstance.id,
343 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
345 }, 'filter:api.video-channels.videos.list.params')
347 const resultList = await Hooks.wrapPromiseFun(
348 VideoModel.listForApi,
350 'filter:api.video-channels.videos.list.result'
353 return res.json(getFormattedObjects(resultList.data, resultList.total))
356 async function listVideoChannelFollowers (req: express.Request, res: express.Response) {
357 const channel = res.locals.videoChannel
359 const resultList = await ActorFollowModel.listFollowersForApi({
360 actorIds: [ channel.actorId ],
361 start: req.query.start,
362 count: req.query.count,
363 sort: req.query.sort,
364 search: req.query.search,
368 return res.json(getFormattedObjects(resultList.data, resultList.total))