1 import * as express from 'express'
2 import { Hooks } from '@server/lib/plugins/hooks'
3 import { getServerActor } from '@server/models/application/application'
4 import { MChannelBannerAccountDefault } from '@server/types/models'
5 import { ActorImageType, VideoChannelCreate, VideoChannelUpdate, VideosCommonQuery } from '../../../shared'
6 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
7 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
8 import { resetSequelizeInstance } from '../../helpers/database-utils'
9 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
10 import { logger } from '../../helpers/logger'
11 import { getFormattedObjects } from '../../helpers/utils'
12 import { CONFIG } from '../../initializers/config'
13 import { MIMETYPES } from '../../initializers/constants'
14 import { sequelizeTypescript } from '../../initializers/database'
15 import { sendUpdateActor } from '../../lib/activitypub/send'
16 import { deleteLocalActorImageFile, updateLocalActorImageFile } from '../../lib/actor-image'
17 import { JobQueue } from '../../lib/job-queue'
18 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
21 asyncRetryTransactionMiddleware,
23 commonVideosFiltersValidator,
29 videoChannelsAddValidator,
30 videoChannelsRemoveValidator,
31 videoChannelsSortValidator,
32 videoChannelsUpdateValidator,
33 videoPlaylistsSortValidator
34 } from '../../middlewares'
35 import { videoChannelsNameWithHostValidator, videoChannelsOwnSearchValidator, videosSortValidator } from '../../middlewares/validators'
36 import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image'
37 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
38 import { AccountModel } from '../../models/account/account'
39 import { VideoModel } from '../../models/video/video'
40 import { VideoChannelModel } from '../../models/video/video-channel'
41 import { VideoPlaylistModel } from '../../models/video/video-playlist'
43 const auditLogger = auditLoggerFactory('channels')
44 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
45 const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { bannerfile: CONFIG.STORAGE.TMP_DIR })
47 const videoChannelRouter = express.Router()
49 videoChannelRouter.get('/',
51 videoChannelsSortValidator,
54 videoChannelsOwnSearchValidator,
55 asyncMiddleware(listVideoChannels)
58 videoChannelRouter.post('/',
60 asyncMiddleware(videoChannelsAddValidator),
61 asyncRetryTransactionMiddleware(addVideoChannel)
64 videoChannelRouter.post('/:nameWithHost/avatar/pick',
68 asyncMiddleware(videoChannelsUpdateValidator),
69 updateAvatarValidator,
70 asyncMiddleware(updateVideoChannelAvatar)
73 videoChannelRouter.post('/:nameWithHost/banner/pick',
77 asyncMiddleware(videoChannelsUpdateValidator),
78 updateBannerValidator,
79 asyncMiddleware(updateVideoChannelBanner)
82 videoChannelRouter.delete('/:nameWithHost/avatar',
85 asyncMiddleware(videoChannelsUpdateValidator),
86 asyncMiddleware(deleteVideoChannelAvatar)
89 videoChannelRouter.delete('/:nameWithHost/banner',
92 asyncMiddleware(videoChannelsUpdateValidator),
93 asyncMiddleware(deleteVideoChannelBanner)
96 videoChannelRouter.put('/:nameWithHost',
98 asyncMiddleware(videoChannelsUpdateValidator),
99 asyncRetryTransactionMiddleware(updateVideoChannel)
102 videoChannelRouter.delete('/:nameWithHost',
104 asyncMiddleware(videoChannelsRemoveValidator),
105 asyncRetryTransactionMiddleware(removeVideoChannel)
108 videoChannelRouter.get('/:nameWithHost',
109 asyncMiddleware(videoChannelsNameWithHostValidator),
110 asyncMiddleware(getVideoChannel)
113 videoChannelRouter.get('/:nameWithHost/video-playlists',
114 asyncMiddleware(videoChannelsNameWithHostValidator),
116 videoPlaylistsSortValidator,
118 setDefaultPagination,
119 commonVideoPlaylistFiltersValidator,
120 asyncMiddleware(listVideoChannelPlaylists)
123 videoChannelRouter.get('/:nameWithHost/videos',
124 asyncMiddleware(videoChannelsNameWithHostValidator),
127 setDefaultVideosSort,
128 setDefaultPagination,
129 optionalAuthenticate,
130 commonVideosFiltersValidator,
131 asyncMiddleware(listVideoChannelVideos)
134 // ---------------------------------------------------------------------------
140 // ---------------------------------------------------------------------------
142 async function listVideoChannels (req: express.Request, res: express.Response) {
143 const serverActor = await getServerActor()
144 const resultList = await VideoChannelModel.listForApi({
145 actorId: serverActor.id,
146 start: req.query.start,
147 count: req.query.count,
151 return res.json(getFormattedObjects(resultList.data, resultList.total))
154 async function updateVideoChannelBanner (req: express.Request, res: express.Response) {
155 const bannerPhysicalFile = req.files['bannerfile'][0]
156 const videoChannel = res.locals.videoChannel
157 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
159 const banner = await updateLocalActorImageFile(videoChannel, bannerPhysicalFile, ActorImageType.BANNER)
161 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
163 return res.json({ banner: banner.toFormattedJSON() })
165 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
166 const avatarPhysicalFile = req.files['avatarfile'][0]
167 const videoChannel = res.locals.videoChannel
168 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
170 const avatar = await updateLocalActorImageFile(videoChannel, avatarPhysicalFile, ActorImageType.AVATAR)
172 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
174 return res.json({ avatar: avatar.toFormattedJSON() })
177 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
178 const videoChannel = res.locals.videoChannel
180 await deleteLocalActorImageFile(videoChannel, ActorImageType.AVATAR)
182 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
185 async function deleteVideoChannelBanner (req: express.Request, res: express.Response) {
186 const videoChannel = res.locals.videoChannel
188 await deleteLocalActorImageFile(videoChannel, ActorImageType.BANNER)
190 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
193 async function addVideoChannel (req: express.Request, res: express.Response) {
194 const videoChannelInfo: VideoChannelCreate = req.body
196 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
197 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
199 return createLocalVideoChannel(videoChannelInfo, account, t)
202 const payload = { actorId: videoChannelCreated.actorId }
203 await JobQueue.Instance.createJobWithPromise({ type: 'actor-keys', payload })
205 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
206 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
210 id: videoChannelCreated.id
215 async function updateVideoChannel (req: express.Request, res: express.Response) {
216 const videoChannelInstance = res.locals.videoChannel
217 const videoChannelFieldsSave = videoChannelInstance.toJSON()
218 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
219 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
220 let doBulkVideoUpdate = false
223 await sequelizeTypescript.transaction(async t => {
224 const sequelizeOptions = {
228 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
229 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
231 if (videoChannelInfoToUpdate.support !== undefined) {
232 const oldSupportField = videoChannelInstance.support
233 videoChannelInstance.support = videoChannelInfoToUpdate.support
235 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
236 doBulkVideoUpdate = true
237 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
241 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelBannerAccountDefault
242 await sendUpdateActor(videoChannelInstanceUpdated, t)
245 getAuditIdFromRes(res),
246 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
247 oldVideoChannelAuditKeys
250 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
253 logger.debug('Cannot update the video channel.', { err })
255 // Force fields we want to update
256 // If the transaction is retried, sequelize will think the object has not changed
257 // So it will skip the SQL request, even if the last one was ROLLBACKed!
258 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
263 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
265 // Don't process in a transaction, and after the response because it could be long
266 if (doBulkVideoUpdate) {
267 await federateAllVideosOfChannel(videoChannelInstance)
271 async function removeVideoChannel (req: express.Request, res: express.Response) {
272 const videoChannelInstance = res.locals.videoChannel
274 await sequelizeTypescript.transaction(async t => {
275 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
277 await videoChannelInstance.destroy({ transaction: t })
279 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
280 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
283 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
286 async function getVideoChannel (req: express.Request, res: express.Response) {
287 const videoChannel = res.locals.videoChannel
289 if (videoChannel.isOutdated()) {
290 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannel.Actor.url } })
293 return res.json(videoChannel.toFormattedJSON())
296 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
297 const serverActor = await getServerActor()
299 const resultList = await VideoPlaylistModel.listForApi({
300 followerActorId: serverActor.id,
301 start: req.query.start,
302 count: req.query.count,
303 sort: req.query.sort,
304 videoChannelId: res.locals.videoChannel.id,
305 type: req.query.playlistType
308 return res.json(getFormattedObjects(resultList.data, resultList.total))
311 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
312 const videoChannelInstance = res.locals.videoChannel
313 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
314 const countVideos = getCountVideos(req)
315 const query = req.query as VideosCommonQuery
317 const apiOptions = await Hooks.wrapObject({
322 includeLocalVideos: true,
323 categoryOneOf: query.categoryOneOf,
324 licenceOneOf: query.licenceOneOf,
325 languageOneOf: query.languageOneOf,
326 tagsOneOf: query.tagsOneOf,
327 tagsAllOf: query.tagsAllOf,
328 filter: query.filter,
329 nsfw: buildNSFWFilter(res, query.nsfw),
331 videoChannelId: videoChannelInstance.id,
332 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
334 }, 'filter:api.video-channels.videos.list.params')
336 const resultList = await Hooks.wrapPromiseFun(
337 VideoModel.listForApi,
339 'filter:api.video-channels.videos.list.result'
342 return res.json(getFormattedObjects(resultList.data, resultList.total))