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 videoPlaylistsSortValidator
17 } from '../../middlewares'
18 import { VideoChannelModel } from '../../models/video/video-channel'
19 import { videoChannelsNameWithHostValidator, videosSortValidator } from '../../middlewares/validators'
20 import { sendUpdateActor } from '../../lib/activitypub/send'
21 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
22 import { createVideoChannel } from '../../lib/video-channel'
23 import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
24 import { setAsyncActorKeys } from '../../lib/activitypub'
25 import { AccountModel } from '../../models/account/account'
26 import { CONFIG, MIMETYPES, sequelizeTypescript } from '../../initializers'
27 import { logger } from '../../helpers/logger'
28 import { VideoModel } from '../../models/video/video'
29 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
30 import { updateActorAvatarFile } from '../../lib/avatar'
31 import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger'
32 import { resetSequelizeInstance } from '../../helpers/database-utils'
33 import { UserModel } from '../../models/account/user'
34 import { JobQueue } from '../../lib/job-queue'
35 import { VideoPlaylistModel } from '../../models/video/video-playlist'
36 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
38 const auditLogger = auditLoggerFactory('channels')
39 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
41 const videoChannelRouter = express.Router()
43 videoChannelRouter.get('/',
45 videoChannelsSortValidator,
48 asyncMiddleware(listVideoChannels)
51 videoChannelRouter.post('/',
53 asyncMiddleware(videoChannelsAddValidator),
54 asyncRetryTransactionMiddleware(addVideoChannel)
57 videoChannelRouter.post('/:nameWithHost/avatar/pick',
61 asyncMiddleware(videoChannelsUpdateValidator),
62 updateAvatarValidator,
63 asyncMiddleware(updateVideoChannelAvatar)
66 videoChannelRouter.put('/:nameWithHost',
68 asyncMiddleware(videoChannelsUpdateValidator),
69 asyncRetryTransactionMiddleware(updateVideoChannel)
72 videoChannelRouter.delete('/:nameWithHost',
74 asyncMiddleware(videoChannelsRemoveValidator),
75 asyncRetryTransactionMiddleware(removeVideoChannel)
78 videoChannelRouter.get('/:nameWithHost',
79 asyncMiddleware(videoChannelsNameWithHostValidator),
80 asyncMiddleware(getVideoChannel)
83 videoChannelRouter.get('/:nameWithHost/video-playlists',
84 asyncMiddleware(videoChannelsNameWithHostValidator),
86 videoPlaylistsSortValidator,
89 commonVideoPlaylistFiltersValidator,
90 asyncMiddleware(listVideoChannelPlaylists)
93 videoChannelRouter.get('/:nameWithHost/videos',
94 asyncMiddleware(videoChannelsNameWithHostValidator),
100 commonVideosFiltersValidator,
101 asyncMiddleware(listVideoChannelVideos)
104 // ---------------------------------------------------------------------------
110 // ---------------------------------------------------------------------------
112 async function listVideoChannels (req: express.Request, res: express.Response, next: express.NextFunction) {
113 const serverActor = await getServerActor()
114 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
116 return res.json(getFormattedObjects(resultList.data, resultList.total))
119 async function updateVideoChannelAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
120 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
121 const videoChannel = res.locals.videoChannel as VideoChannelModel
122 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
124 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
126 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
130 avatar: avatar.toFormattedJSON()
135 async function addVideoChannel (req: express.Request, res: express.Response) {
136 const videoChannelInfo: VideoChannelCreate = req.body
138 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
139 const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t)
141 return createVideoChannel(videoChannelInfo, account, t)
144 setAsyncActorKeys(videoChannelCreated.Actor)
145 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
147 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
148 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
152 id: videoChannelCreated.id,
153 uuid: videoChannelCreated.Actor.uuid
158 async function updateVideoChannel (req: express.Request, res: express.Response) {
159 const videoChannelInstance = res.locals.videoChannel as VideoChannelModel
160 const videoChannelFieldsSave = videoChannelInstance.toJSON()
161 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
162 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
165 await sequelizeTypescript.transaction(async t => {
166 const sequelizeOptions = {
170 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
171 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
172 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
174 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
175 await sendUpdateActor(videoChannelInstanceUpdated, t)
178 getAuditIdFromRes(res),
179 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
180 oldVideoChannelAuditKeys
182 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
185 logger.debug('Cannot update the video channel.', { err })
187 // Force fields we want to update
188 // If the transaction is retried, sequelize will think the object has not changed
189 // So it will skip the SQL request, even if the last one was ROLLBACKed!
190 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
195 return res.type('json').status(204).end()
198 async function removeVideoChannel (req: express.Request, res: express.Response) {
199 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
201 await sequelizeTypescript.transaction(async t => {
202 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
204 await videoChannelInstance.destroy({ transaction: t })
206 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
207 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
210 return res.type('json').status(204).end()
213 async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) {
214 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
216 if (videoChannelWithVideos.isOutdated()) {
217 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
218 .catch(err => logger.error('Cannot create AP refresher job for actor %s.', videoChannelWithVideos.Actor.url, { err }))
221 return res.json(videoChannelWithVideos.toFormattedJSON())
224 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
225 const serverActor = await getServerActor()
227 const resultList = await VideoPlaylistModel.listForApi({
228 followerActorId: serverActor.id,
229 start: req.query.start,
230 count: req.query.count,
231 sort: req.query.sort,
232 videoChannelId: res.locals.videoChannel.id,
233 type: req.query.playlistType
236 return res.json(getFormattedObjects(resultList.data, resultList.total))
239 async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
240 const videoChannelInstance: VideoChannelModel = res.locals.videoChannel
241 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
243 const resultList = await VideoModel.listForApi({
245 start: req.query.start,
246 count: req.query.count,
247 sort: req.query.sort,
248 includeLocalVideos: true,
249 categoryOneOf: req.query.categoryOneOf,
250 licenceOneOf: req.query.licenceOneOf,
251 languageOneOf: req.query.languageOneOf,
252 tagsOneOf: req.query.tagsOneOf,
253 tagsAllOf: req.query.tagsAllOf,
254 filter: req.query.filter,
255 nsfw: buildNSFWFilter(res, req.query.nsfw),
257 videoChannelId: videoChannelInstance.id,
258 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
261 return res.json(getFormattedObjects(resultList.data, resultList.total))