1 import * as express from 'express'
2 import { getServerActor } from '@server/models/application/application'
3 import { MChannelAccountDefault } from '@server/types/models'
4 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
5 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
6 import { resetSequelizeInstance } from '../../helpers/database-utils'
7 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
8 import { logger } from '../../helpers/logger'
9 import { getFormattedObjects } from '../../helpers/utils'
10 import { CONFIG } from '../../initializers/config'
11 import { MIMETYPES } from '../../initializers/constants'
12 import { sequelizeTypescript } from '../../initializers/database'
13 import { setAsyncActorKeys } from '../../lib/activitypub/actor'
14 import { sendUpdateActor } from '../../lib/activitypub/send'
15 import { updateActorAvatarFile } from '../../lib/avatar'
16 import { JobQueue } from '../../lib/job-queue'
17 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
20 asyncRetryTransactionMiddleware,
22 commonVideosFiltersValidator,
28 videoChannelsAddValidator,
29 videoChannelsRemoveValidator,
30 videoChannelsSortValidator,
31 videoChannelsUpdateValidator,
32 videoPlaylistsSortValidator
33 } from '../../middlewares'
34 import { videoChannelsNameWithHostValidator, videoChannelsOwnSearchValidator, videosSortValidator } from '../../middlewares/validators'
35 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
36 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
37 import { AccountModel } from '../../models/account/account'
38 import { VideoModel } from '../../models/video/video'
39 import { VideoChannelModel } from '../../models/video/video-channel'
40 import { VideoPlaylistModel } from '../../models/video/video-playlist'
41 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
43 const auditLogger = auditLoggerFactory('channels')
44 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
46 const videoChannelRouter = express.Router()
48 videoChannelRouter.get('/',
50 videoChannelsSortValidator,
53 videoChannelsOwnSearchValidator,
54 asyncMiddleware(listVideoChannels)
57 videoChannelRouter.post('/',
59 asyncMiddleware(videoChannelsAddValidator),
60 asyncRetryTransactionMiddleware(addVideoChannel)
63 videoChannelRouter.post('/:nameWithHost/avatar/pick',
67 asyncMiddleware(videoChannelsUpdateValidator),
68 updateAvatarValidator,
69 asyncMiddleware(updateVideoChannelAvatar)
72 videoChannelRouter.put('/:nameWithHost',
74 asyncMiddleware(videoChannelsUpdateValidator),
75 asyncRetryTransactionMiddleware(updateVideoChannel)
78 videoChannelRouter.delete('/:nameWithHost',
80 asyncMiddleware(videoChannelsRemoveValidator),
81 asyncRetryTransactionMiddleware(removeVideoChannel)
84 videoChannelRouter.get('/:nameWithHost',
85 asyncMiddleware(videoChannelsNameWithHostValidator),
86 asyncMiddleware(getVideoChannel)
89 videoChannelRouter.get('/:nameWithHost/video-playlists',
90 asyncMiddleware(videoChannelsNameWithHostValidator),
92 videoPlaylistsSortValidator,
95 commonVideoPlaylistFiltersValidator,
96 asyncMiddleware(listVideoChannelPlaylists)
99 videoChannelRouter.get('/:nameWithHost/videos',
100 asyncMiddleware(videoChannelsNameWithHostValidator),
103 setDefaultVideosSort,
104 setDefaultPagination,
105 optionalAuthenticate,
106 commonVideosFiltersValidator,
107 asyncMiddleware(listVideoChannelVideos)
110 // ---------------------------------------------------------------------------
116 // ---------------------------------------------------------------------------
118 async function listVideoChannels (req: express.Request, res: express.Response) {
119 const serverActor = await getServerActor()
120 const resultList = await VideoChannelModel.listForApi({
121 actorId: serverActor.id,
122 start: req.query.start,
123 count: req.query.count,
127 return res.json(getFormattedObjects(resultList.data, resultList.total))
130 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
131 const avatarPhysicalFile = req.files['avatarfile'][0]
132 const videoChannel = res.locals.videoChannel
133 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
135 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
137 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
141 avatar: avatar.toFormattedJSON()
146 async function addVideoChannel (req: express.Request, res: express.Response) {
147 const videoChannelInfo: VideoChannelCreate = req.body
149 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
150 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
152 return createLocalVideoChannel(videoChannelInfo, account, t)
155 setAsyncActorKeys(videoChannelCreated.Actor)
156 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.url, { err }))
158 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
159 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
163 id: videoChannelCreated.id
168 async function updateVideoChannel (req: express.Request, res: express.Response) {
169 const videoChannelInstance = res.locals.videoChannel
170 const videoChannelFieldsSave = videoChannelInstance.toJSON()
171 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
172 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
173 let doBulkVideoUpdate = false
176 await sequelizeTypescript.transaction(async t => {
177 const sequelizeOptions = {
181 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
182 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
184 if (videoChannelInfoToUpdate.support !== undefined) {
185 const oldSupportField = videoChannelInstance.support
186 videoChannelInstance.support = videoChannelInfoToUpdate.support
188 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
189 doBulkVideoUpdate = true
190 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
194 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
195 await sendUpdateActor(videoChannelInstanceUpdated, t)
198 getAuditIdFromRes(res),
199 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
200 oldVideoChannelAuditKeys
203 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
206 logger.debug('Cannot update the video channel.', { err })
208 // Force fields we want to update
209 // If the transaction is retried, sequelize will think the object has not changed
210 // So it will skip the SQL request, even if the last one was ROLLBACKed!
211 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
216 res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
218 // Don't process in a transaction, and after the response because it could be long
219 if (doBulkVideoUpdate) {
220 await federateAllVideosOfChannel(videoChannelInstance)
224 async function removeVideoChannel (req: express.Request, res: express.Response) {
225 const videoChannelInstance = res.locals.videoChannel
227 await sequelizeTypescript.transaction(async t => {
228 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
230 await videoChannelInstance.destroy({ transaction: t })
232 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
233 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
236 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
239 async function getVideoChannel (req: express.Request, res: express.Response) {
240 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
242 if (videoChannelWithVideos.isOutdated()) {
243 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
246 return res.json(videoChannelWithVideos.toFormattedJSON())
249 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
250 const serverActor = await getServerActor()
252 const resultList = await VideoPlaylistModel.listForApi({
253 followerActorId: serverActor.id,
254 start: req.query.start,
255 count: req.query.count,
256 sort: req.query.sort,
257 videoChannelId: res.locals.videoChannel.id,
258 type: req.query.playlistType
261 return res.json(getFormattedObjects(resultList.data, resultList.total))
264 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
265 const videoChannelInstance = res.locals.videoChannel
266 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
267 const countVideos = getCountVideos(req)
269 const resultList = await VideoModel.listForApi({
271 start: req.query.start,
272 count: req.query.count,
273 sort: req.query.sort,
274 includeLocalVideos: true,
275 categoryOneOf: req.query.categoryOneOf,
276 licenceOneOf: req.query.licenceOneOf,
277 languageOneOf: req.query.languageOneOf,
278 tagsOneOf: req.query.tagsOneOf,
279 tagsAllOf: req.query.tagsAllOf,
280 filter: req.query.filter,
281 nsfw: buildNSFWFilter(res, req.query.nsfw),
283 videoChannelId: videoChannelInstance.id,
284 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
288 return res.json(getFormattedObjects(resultList.data, resultList.total))