1 import * as express from 'express'
2 import { Hooks } from '@server/lib/plugins/hooks'
3 import { getServerActor } from '@server/models/application/application'
4 import { MChannelAccountDefault } from '@server/types/models'
5 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
6 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
7 import { resetSequelizeInstance } from '../../helpers/database-utils'
8 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
9 import { logger } from '../../helpers/logger'
10 import { getFormattedObjects } from '../../helpers/utils'
11 import { CONFIG } from '../../initializers/config'
12 import { MIMETYPES } from '../../initializers/constants'
13 import { sequelizeTypescript } from '../../initializers/database'
14 import { setAsyncActorKeys } from '../../lib/activitypub/actor'
15 import { sendUpdateActor } from '../../lib/activitypub/send'
16 import { updateActorAvatarFile } from '../../lib/avatar'
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 } from '../../middlewares/validators/avatar'
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'
42 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
44 const auditLogger = auditLoggerFactory('channels')
45 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: 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.put('/:nameWithHost',
75 asyncMiddleware(videoChannelsUpdateValidator),
76 asyncRetryTransactionMiddleware(updateVideoChannel)
79 videoChannelRouter.delete('/:nameWithHost',
81 asyncMiddleware(videoChannelsRemoveValidator),
82 asyncRetryTransactionMiddleware(removeVideoChannel)
85 videoChannelRouter.get('/:nameWithHost',
86 asyncMiddleware(videoChannelsNameWithHostValidator),
87 asyncMiddleware(getVideoChannel)
90 videoChannelRouter.get('/:nameWithHost/video-playlists',
91 asyncMiddleware(videoChannelsNameWithHostValidator),
93 videoPlaylistsSortValidator,
96 commonVideoPlaylistFiltersValidator,
97 asyncMiddleware(listVideoChannelPlaylists)
100 videoChannelRouter.get('/:nameWithHost/videos',
101 asyncMiddleware(videoChannelsNameWithHostValidator),
104 setDefaultVideosSort,
105 setDefaultPagination,
106 optionalAuthenticate,
107 commonVideosFiltersValidator,
108 asyncMiddleware(listVideoChannelVideos)
111 // ---------------------------------------------------------------------------
117 // ---------------------------------------------------------------------------
119 async function listVideoChannels (req: express.Request, res: express.Response) {
120 const serverActor = await getServerActor()
121 const resultList = await VideoChannelModel.listForApi({
122 actorId: serverActor.id,
123 start: req.query.start,
124 count: req.query.count,
128 return res.json(getFormattedObjects(resultList.data, resultList.total))
131 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
132 const avatarPhysicalFile = req.files['avatarfile'][0]
133 const videoChannel = res.locals.videoChannel
134 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
136 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
138 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
142 avatar: avatar.toFormattedJSON()
147 async function addVideoChannel (req: express.Request, res: express.Response) {
148 const videoChannelInfo: VideoChannelCreate = req.body
150 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
151 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
153 return createLocalVideoChannel(videoChannelInfo, account, t)
156 setAsyncActorKeys(videoChannelCreated.Actor)
157 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.url, { err }))
159 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
160 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
164 id: videoChannelCreated.id
169 async function updateVideoChannel (req: express.Request, res: express.Response) {
170 const videoChannelInstance = res.locals.videoChannel
171 const videoChannelFieldsSave = videoChannelInstance.toJSON()
172 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
173 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
174 let doBulkVideoUpdate = false
177 await sequelizeTypescript.transaction(async t => {
178 const sequelizeOptions = {
182 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
183 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
185 if (videoChannelInfoToUpdate.support !== undefined) {
186 const oldSupportField = videoChannelInstance.support
187 videoChannelInstance.support = videoChannelInfoToUpdate.support
189 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
190 doBulkVideoUpdate = true
191 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
195 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
196 await sendUpdateActor(videoChannelInstanceUpdated, t)
199 getAuditIdFromRes(res),
200 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
201 oldVideoChannelAuditKeys
204 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
207 logger.debug('Cannot update the video channel.', { err })
209 // Force fields we want to update
210 // If the transaction is retried, sequelize will think the object has not changed
211 // So it will skip the SQL request, even if the last one was ROLLBACKed!
212 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
217 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
219 // Don't process in a transaction, and after the response because it could be long
220 if (doBulkVideoUpdate) {
221 await federateAllVideosOfChannel(videoChannelInstance)
225 async function removeVideoChannel (req: express.Request, res: express.Response) {
226 const videoChannelInstance = res.locals.videoChannel
228 await sequelizeTypescript.transaction(async t => {
229 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
231 await videoChannelInstance.destroy({ transaction: t })
233 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
234 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
237 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
240 async function getVideoChannel (req: express.Request, res: express.Response) {
241 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
243 if (videoChannelWithVideos.isOutdated()) {
244 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
247 return res.json(videoChannelWithVideos.toFormattedJSON())
250 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
251 const serverActor = await getServerActor()
253 const resultList = await VideoPlaylistModel.listForApi({
254 followerActorId: serverActor.id,
255 start: req.query.start,
256 count: req.query.count,
257 sort: req.query.sort,
258 videoChannelId: res.locals.videoChannel.id,
259 type: req.query.playlistType
262 return res.json(getFormattedObjects(resultList.data, resultList.total))
265 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
266 const videoChannelInstance = res.locals.videoChannel
267 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
268 const countVideos = getCountVideos(req)
270 const apiOptions = await Hooks.wrapObject({
272 start: req.query.start,
273 count: req.query.count,
274 sort: req.query.sort,
275 includeLocalVideos: true,
276 categoryOneOf: req.query.categoryOneOf,
277 licenceOneOf: req.query.licenceOneOf,
278 languageOneOf: req.query.languageOneOf,
279 tagsOneOf: req.query.tagsOneOf,
280 tagsAllOf: req.query.tagsAllOf,
281 filter: req.query.filter,
282 nsfw: buildNSFWFilter(res, req.query.nsfw),
284 videoChannelId: videoChannelInstance.id,
285 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
287 }, 'filter:api.video-channels.videos.list.params')
289 const resultList = await Hooks.wrapPromiseFun(
290 VideoModel.listForApi,
292 'filter:api.video-channels.videos.list.result'
295 return res.json(getFormattedObjects(resultList.data, resultList.total))