1 import * as express from 'express'
2 import { getFormattedObjects, getServerActor } from '../../helpers/utils'
5 asyncRetryTransactionMiddleware,
7 commonVideosFiltersValidator,
12 videoChannelsAddValidator,
13 videoChannelsRemoveValidator,
14 videoChannelsSortValidator,
15 videoChannelsUpdateValidator
16 } from '../../middlewares'
17 import { VideoChannelModel } from '../../models/video/video-channel'
18 import { videoChannelsNameWithHostValidator, videosSortValidator } from '../../middlewares/validators'
19 import { sendUpdateActor } from '../../lib/activitypub/send'
20 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
21 import { createVideoChannel } from '../../lib/video-channel'
22 import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
23 import { setAsyncActorKeys } from '../../lib/activitypub'
24 import { AccountModel } from '../../models/account/account'
25 import { CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
26 import { logger } from '../../helpers/logger'
27 import { VideoModel } from '../../models/video/video'
28 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
29 import { updateActorAvatarFile } from '../../lib/avatar'
30 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
31 import { resetSequelizeInstance } from '../../helpers/database-utils'
32 import { UserModel } from '../../models/account/user'
34 const auditLogger = auditLoggerFactory('channels')
35 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
37 const videoChannelRouter = express.Router()
39 videoChannelRouter.get('/',
41 videoChannelsSortValidator,
44 asyncMiddleware(listVideoChannels)
47 videoChannelRouter.post('/',
49 videoChannelsAddValidator,
50 asyncRetryTransactionMiddleware(addVideoChannel)
53 videoChannelRouter.post('/:nameWithHost/avatar/pick',
57 asyncMiddleware(videoChannelsUpdateValidator),
58 updateAvatarValidator,
59 asyncMiddleware(updateVideoChannelAvatar)
62 videoChannelRouter.put('/:nameWithHost',
64 asyncMiddleware(videoChannelsUpdateValidator),
65 asyncRetryTransactionMiddleware(updateVideoChannel)
68 videoChannelRouter.delete('/:nameWithHost',
70 asyncMiddleware(videoChannelsRemoveValidator),
71 asyncRetryTransactionMiddleware(removeVideoChannel)
74 videoChannelRouter.get('/:nameWithHost',
75 asyncMiddleware(videoChannelsNameWithHostValidator),
76 asyncMiddleware(getVideoChannel)
79 videoChannelRouter.get('/:nameWithHost/videos',
80 asyncMiddleware(videoChannelsNameWithHostValidator),
86 commonVideosFiltersValidator,
87 asyncMiddleware(listVideoChannelVideos)
90 // ---------------------------------------------------------------------------
96 // ---------------------------------------------------------------------------
98 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
99 const serverActor = await getServerActor()
100 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
102 return res.json(getFormattedObjects(resultList.data, resultList.total))
105 async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
106 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
107 const videoChannel = res.locals.videoChannel as VideoChannelModel
108 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
110 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel)
113 getAuditIdFromRes(res),
114 new VideoChannelAuditView(videoChannel.toFormattedJSON()),
115 oldVideoChannelAuditKeys
120 avatar: avatar.toFormattedJSON()
125 async function addVideoChannel (req: express.Request, res: express.Response) {
126 const videoChannelInfo: VideoChannelCreate = req.body
128 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
129 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
131 return createVideoChannel(videoChannelInfo, account, t)
134 setAsyncActorKeys(videoChannelCreated.Actor)
135 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
137 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
138 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
142 id: videoChannelCreated.id,
143 uuid: videoChannelCreated.Actor.uuid
148 async function updateVideoChannel (req: express.Request, res: express.Response) {
149 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
150 const videoChannelFieldsSave = videoChannelInstance.toJSON()
151 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
152 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
155 await sequelizeTypescript.transaction(async t => {
156 const sequelizeOptions = {
160 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
161 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
162 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
164 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
165 await sendUpdateActor(videoChannelInstanceUpdated, t)
168 getAuditIdFromRes(res),
169 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
170 oldVideoChannelAuditKeys
172 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
175 logger.debug('Cannot update the video channel.', { err })
177 // Force fields we want to update
178 // If the transaction is retried, sequelize will think the object has not changed
179 // So it will skip the SQL request, even if the last one was ROLLBACKed!
180 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
185 return res.type('json').status(204).end()
188 async function removeVideoChannel (req: express.Request, res: express.Response) {
189 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
191 await sequelizeTypescript.transaction(async t => {
192 await videoChannelInstance.destroy({ transaction: t })
194 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
195 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
198 return res.type('json').status(204).end()
201 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
202 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
204 return res.json(videoChannelWithVideos.toFormattedJSON())
207 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
208 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
209 const actorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
211 const resultList = await VideoModel.listForApi({
213 start: req.query.start,
214 count: req.query.count,
215 sort: req.query.sort,
216 includeLocalVideos: true,
217 categoryOneOf: req.query.categoryOneOf,
218 licenceOneOf: req.query.licenceOneOf,
219 languageOneOf: req.query.languageOneOf,
220 tagsOneOf: req.query.tagsOneOf,
221 tagsAllOf: req.query.tagsAllOf,
222 nsfw: buildNSFWFilter(res, req.query.nsfw),
224 videoChannelId: videoChannelInstance.id
227 return res.json(getFormattedObjects(resultList.data, resultList.total))