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, MIMETYPES, 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'
33 import { JobQueue } from '../../lib/job-queue'
35 const auditLogger = auditLoggerFactory('channels')
36 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
38 const videoChannelRouter = express.Router()
40 videoChannelRouter.get('/',
42 videoChannelsSortValidator,
45 asyncMiddleware(listVideoChannels)
48 videoChannelRouter.post('/',
50 asyncMiddleware(videoChannelsAddValidator),
51 asyncRetryTransactionMiddleware(addVideoChannel)
54 videoChannelRouter.post('/:nameWithHost/avatar/pick',
58 asyncMiddleware(videoChannelsUpdateValidator),
59 updateAvatarValidator,
60 asyncMiddleware(updateVideoChannelAvatar)
63 videoChannelRouter.put('/:nameWithHost',
65 asyncMiddleware(videoChannelsUpdateValidator),
66 asyncRetryTransactionMiddleware(updateVideoChannel)
69 videoChannelRouter.delete('/:nameWithHost',
71 asyncMiddleware(videoChannelsRemoveValidator),
72 asyncRetryTransactionMiddleware(removeVideoChannel)
75 videoChannelRouter.get('/:nameWithHost',
76 asyncMiddleware(videoChannelsNameWithHostValidator),
77 asyncMiddleware(getVideoChannel)
80 videoChannelRouter.get('/:nameWithHost/videos',
81 asyncMiddleware(videoChannelsNameWithHostValidator),
87 commonVideosFiltersValidator,
88 asyncMiddleware(listVideoChannelVideos)
91 // ---------------------------------------------------------------------------
97 // ---------------------------------------------------------------------------
99 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
100 const serverActor = await getServerActor()
101 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
103 return res.json(getFormattedObjects(resultList.data, resultList.total))
106 async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
107 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
108 const videoChannel = res.locals.videoChannel as VideoChannelModel
109 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
111 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
113 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
117 avatar: avatar.toFormattedJSON()
122 async function addVideoChannel (req: express.Request, res: express.Response) {
123 const videoChannelInfo: VideoChannelCreate = req.body
125 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
126 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
128 return createVideoChannel(videoChannelInfo, account, t)
131 setAsyncActorKeys(videoChannelCreated.Actor)
132 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
134 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
135 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
139 id: videoChannelCreated.id,
140 uuid: videoChannelCreated.Actor.uuid
145 async function updateVideoChannel (req: express.Request, res: express.Response) {
146 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
147 const videoChannelFieldsSave = videoChannelInstance.toJSON()
148 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
149 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
152 await sequelizeTypescript.transaction(async t => {
153 const sequelizeOptions = {
157 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
158 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
159 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
161 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
162 await sendUpdateActor(videoChannelInstanceUpdated, t)
165 getAuditIdFromRes(res),
166 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
167 oldVideoChannelAuditKeys
169 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
172 logger.debug('Cannot update the video channel.', { err })
174 // Force fields we want to update
175 // If the transaction is retried, sequelize will think the object has not changed
176 // So it will skip the SQL request, even if the last one was ROLLBACKed!
177 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
182 return res.type('json').status(204).end()
185 async function removeVideoChannel (req: express.Request, res: express.Response) {
186 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
188 await sequelizeTypescript.transaction(async t => {
189 await videoChannelInstance.destroy({ transaction: t })
191 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
192 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
195 return res.type('json').status(204).end()
198 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
199 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
201 if (videoChannelWithVideos.isOutdated()) {
202 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
203 .catch(err => logger.error('Cannot create AP refresher job for actor %s.', videoChannelWithVideos.Actor.url, { err }))
206 return res.json(videoChannelWithVideos.toFormattedJSON())
209 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
210 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
211 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
213 const resultList = await VideoModel.listForApi({
215 start: req.query.start,
216 count: req.query.count,
217 sort: req.query.sort,
218 includeLocalVideos: true,
219 categoryOneOf: req.query.categoryOneOf,
220 licenceOneOf: req.query.licenceOneOf,
221 languageOneOf: req.query.languageOneOf,
222 tagsOneOf: req.query.tagsOneOf,
223 tagsAllOf: req.query.tagsAllOf,
224 filter: req.query.filter,
225 nsfw: buildNSFWFilter(res, req.query.nsfw),
227 videoChannelId: videoChannelInstance.id,
228 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
231 return res.json(getFormattedObjects(resultList.data, resultList.total))