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 { deleteLocalActorAvatarFile, updateLocalActorAvatarFile } 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.delete('/:nameWithHost/avatar',
76 asyncMiddleware(videoChannelsUpdateValidator),
77 asyncMiddleware(deleteVideoChannelAvatar)
80 videoChannelRouter.put('/:nameWithHost',
82 asyncMiddleware(videoChannelsUpdateValidator),
83 asyncRetryTransactionMiddleware(updateVideoChannel)
86 videoChannelRouter.delete('/:nameWithHost',
88 asyncMiddleware(videoChannelsRemoveValidator),
89 asyncRetryTransactionMiddleware(removeVideoChannel)
92 videoChannelRouter.get('/:nameWithHost',
93 asyncMiddleware(videoChannelsNameWithHostValidator),
94 asyncMiddleware(getVideoChannel)
97 videoChannelRouter.get('/:nameWithHost/video-playlists',
98 asyncMiddleware(videoChannelsNameWithHostValidator),
100 videoPlaylistsSortValidator,
102 setDefaultPagination,
103 commonVideoPlaylistFiltersValidator,
104 asyncMiddleware(listVideoChannelPlaylists)
107 videoChannelRouter.get('/:nameWithHost/videos',
108 asyncMiddleware(videoChannelsNameWithHostValidator),
111 setDefaultVideosSort,
112 setDefaultPagination,
113 optionalAuthenticate,
114 commonVideosFiltersValidator,
115 asyncMiddleware(listVideoChannelVideos)
118 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 async function listVideoChannels (req: express.Request, res: express.Response) {
127 const serverActor = await getServerActor()
128 const resultList = await VideoChannelModel.listForApi({
129 actorId: serverActor.id,
130 start: req.query.start,
131 count: req.query.count,
135 return res.json(getFormattedObjects(resultList.data, resultList.total))
138 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
139 const avatarPhysicalFile = req.files['avatarfile'][0]
140 const videoChannel = res.locals.videoChannel
141 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
143 const avatar = await updateLocalActorAvatarFile(videoChannel, avatarPhysicalFile)
145 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
149 avatar: avatar.toFormattedJSON()
154 async function deleteVideoChannelAvatar (req: express.Request, res: express.Response) {
155 const videoChannel = res.locals.videoChannel
157 await deleteLocalActorAvatarFile(videoChannel)
159 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
162 async function addVideoChannel (req: express.Request, res: express.Response) {
163 const videoChannelInfo: VideoChannelCreate = req.body
165 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
166 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
168 return createLocalVideoChannel(videoChannelInfo, account, t)
171 setAsyncActorKeys(videoChannelCreated.Actor)
172 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.url, { err }))
174 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
175 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
179 id: videoChannelCreated.id
184 async function updateVideoChannel (req: express.Request, res: express.Response) {
185 const videoChannelInstance = res.locals.videoChannel
186 const videoChannelFieldsSave = videoChannelInstance.toJSON()
187 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
188 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
189 let doBulkVideoUpdate = false
192 await sequelizeTypescript.transaction(async t => {
193 const sequelizeOptions = {
197 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
198 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
200 if (videoChannelInfoToUpdate.support !== undefined) {
201 const oldSupportField = videoChannelInstance.support
202 videoChannelInstance.support = videoChannelInfoToUpdate.support
204 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
205 doBulkVideoUpdate = true
206 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
210 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
211 await sendUpdateActor(videoChannelInstanceUpdated, t)
214 getAuditIdFromRes(res),
215 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
216 oldVideoChannelAuditKeys
219 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
222 logger.debug('Cannot update the video channel.', { err })
224 // Force fields we want to update
225 // If the transaction is retried, sequelize will think the object has not changed
226 // So it will skip the SQL request, even if the last one was ROLLBACKed!
227 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
232 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
234 // Don't process in a transaction, and after the response because it could be long
235 if (doBulkVideoUpdate) {
236 await federateAllVideosOfChannel(videoChannelInstance)
240 async function removeVideoChannel (req: express.Request, res: express.Response) {
241 const videoChannelInstance = res.locals.videoChannel
243 await sequelizeTypescript.transaction(async t => {
244 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
246 await videoChannelInstance.destroy({ transaction: t })
248 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
249 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
252 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
255 async function getVideoChannel (req: express.Request, res: express.Response) {
256 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
258 if (videoChannelWithVideos.isOutdated()) {
259 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
262 return res.json(videoChannelWithVideos.toFormattedJSON())
265 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
266 const serverActor = await getServerActor()
268 const resultList = await VideoPlaylistModel.listForApi({
269 followerActorId: serverActor.id,
270 start: req.query.start,
271 count: req.query.count,
272 sort: req.query.sort,
273 videoChannelId: res.locals.videoChannel.id,
274 type: req.query.playlistType
277 return res.json(getFormattedObjects(resultList.data, resultList.total))
280 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
281 const videoChannelInstance = res.locals.videoChannel
282 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
283 const countVideos = getCountVideos(req)
285 const apiOptions = await Hooks.wrapObject({
287 start: req.query.start,
288 count: req.query.count,
289 sort: req.query.sort,
290 includeLocalVideos: true,
291 categoryOneOf: req.query.categoryOneOf,
292 licenceOneOf: req.query.licenceOneOf,
293 languageOneOf: req.query.languageOneOf,
294 tagsOneOf: req.query.tagsOneOf,
295 tagsAllOf: req.query.tagsAllOf,
296 filter: req.query.filter,
297 nsfw: buildNSFWFilter(res, req.query.nsfw),
299 videoChannelId: videoChannelInstance.id,
300 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
302 }, 'filter:api.video-channels.videos.list.params')
304 const resultList = await Hooks.wrapPromiseFun(
305 VideoModel.listForApi,
307 'filter:api.video-channels.videos.list.result'
310 return res.json(getFormattedObjects(resultList.data, resultList.total))