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'
34 const auditLogger = auditLoggerFactory('channels')
35 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
37 const videoChannelRouter = express.Router()
39 videoChannelRouter.get('/',
41 videoChannelsSortValidator,
44 asyncMiddleware(listVideoChannels)
47 videoChannelRouter.post('/',
49 asyncMiddleware(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)
112 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
116 avatar: avatar.toFormattedJSON()
121 async function addVideoChannel (req: express.Request, res: express.Response) {
122 const videoChannelInfo: VideoChannelCreate = req.body
124 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
125 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
127 return createVideoChannel(videoChannelInfo, account, t)
130 setAsyncActorKeys(videoChannelCreated.Actor)
131 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
133 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
134 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
138 id: videoChannelCreated.id,
139 uuid: videoChannelCreated.Actor.uuid
144 async function updateVideoChannel (req: express.Request, res: express.Response) {
145 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
146 const videoChannelFieldsSave = videoChannelInstance.toJSON()
147 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
148 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
151 await sequelizeTypescript.transaction(async t => {
152 const sequelizeOptions = {
156 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
157 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
158 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
160 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
161 await sendUpdateActor(videoChannelInstanceUpdated, t)
164 getAuditIdFromRes(res),
165 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
166 oldVideoChannelAuditKeys
168 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
171 logger.debug('Cannot update the video channel.', { err })
173 // Force fields we want to update
174 // If the transaction is retried, sequelize will think the object has not changed
175 // So it will skip the SQL request, even if the last one was ROLLBACKed!
176 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
181 return res.type('json').status(204).end()
184 async function removeVideoChannel (req: express.Request, res: express.Response) {
185 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
187 await sequelizeTypescript.transaction(async t => {
188 await videoChannelInstance.destroy({ transaction: t })
190 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
191 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
194 return res.type('json').status(204).end()
197 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
198 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
200 return res.json(videoChannelWithVideos.toFormattedJSON())
203 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
204 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
205 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
207 const resultList = await VideoModel.listForApi({
209 start: req.query.start,
210 count: req.query.count,
211 sort: req.query.sort,
212 includeLocalVideos: true,
213 categoryOneOf: req.query.categoryOneOf,
214 licenceOneOf: req.query.licenceOneOf,
215 languageOneOf: req.query.languageOneOf,
216 tagsOneOf: req.query.tagsOneOf,
217 tagsAllOf: req.query.tagsAllOf,
218 filter: req.query.filter,
219 nsfw: buildNSFWFilter(res, req.query.nsfw),
221 videoChannelId: videoChannelInstance.id,
222 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
225 return res.json(getFormattedObjects(resultList.data, resultList.total))