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 { MIMETYPES } from '../../initializers/constants'
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 { JobQueue } from '../../lib/job-queue'
34 import { VideoPlaylistModel } from '../../models/video/video-playlist'
35 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
36 import { CONFIG } from '../../initializers/config'
37 import { sequelizeTypescript } from '../../initializers/database'
39 const auditLogger = auditLoggerFactory('channels')
40 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
42 const videoChannelRouter = express.Router()
44 videoChannelRouter.get('/',
46 videoChannelsSortValidator,
49 asyncMiddleware(listVideoChannels)
52 videoChannelRouter.post('/',
54 asyncMiddleware(videoChannelsAddValidator),
55 asyncRetryTransactionMiddleware(addVideoChannel)
58 videoChannelRouter.post('/:nameWithHost/avatar/pick',
62 asyncMiddleware(videoChannelsUpdateValidator),
63 updateAvatarValidator,
64 asyncMiddleware(updateVideoChannelAvatar)
67 videoChannelRouter.put('/:nameWithHost',
69 asyncMiddleware(videoChannelsUpdateValidator),
70 asyncRetryTransactionMiddleware(updateVideoChannel)
73 videoChannelRouter.delete('/:nameWithHost',
75 asyncMiddleware(videoChannelsRemoveValidator),
76 asyncRetryTransactionMiddleware(removeVideoChannel)
79 videoChannelRouter.get('/:nameWithHost',
80 asyncMiddleware(videoChannelsNameWithHostValidator),
81 asyncMiddleware(getVideoChannel)
84 videoChannelRouter.get('/:nameWithHost/video-playlists',
85 asyncMiddleware(videoChannelsNameWithHostValidator),
87 videoPlaylistsSortValidator,
90 commonVideoPlaylistFiltersValidator,
91 asyncMiddleware(listVideoChannelPlaylists)
94 videoChannelRouter.get('/:nameWithHost/videos',
95 asyncMiddleware(videoChannelsNameWithHostValidator),
100 optionalAuthenticate,
101 commonVideosFiltersValidator,
102 asyncMiddleware(listVideoChannelVideos)
105 // ---------------------------------------------------------------------------
111 // ---------------------------------------------------------------------------
113 async function listVideoChannels (req: express.Request, res: express.Response) {
114 const serverActor = await getServerActor()
115 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
117 return res.json(getFormattedObjects(resultList.data, resultList.total))
120 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
121 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
122 const videoChannel = res.locals.videoChannel
123 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
125 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
127 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
131 avatar: avatar.toFormattedJSON()
136 async function addVideoChannel (req: express.Request, res: express.Response) {
137 const videoChannelInfo: VideoChannelCreate = req.body
139 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
140 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
142 return createVideoChannel(videoChannelInfo, account, t)
145 setAsyncActorKeys(videoChannelCreated.Actor)
146 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
148 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
149 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
153 id: videoChannelCreated.id,
154 uuid: videoChannelCreated.Actor.uuid
159 async function updateVideoChannel (req: express.Request, res: express.Response) {
160 const videoChannelInstance = res.locals.videoChannel
161 const videoChannelFieldsSave = videoChannelInstance.toJSON()
162 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
163 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
166 await sequelizeTypescript.transaction(async t => {
167 const sequelizeOptions = {
171 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
172 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
173 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
175 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
176 await sendUpdateActor(videoChannelInstanceUpdated, t)
179 getAuditIdFromRes(res),
180 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
181 oldVideoChannelAuditKeys
183 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
186 logger.debug('Cannot update the video channel.', { err })
188 // Force fields we want to update
189 // If the transaction is retried, sequelize will think the object has not changed
190 // So it will skip the SQL request, even if the last one was ROLLBACKed!
191 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
196 return res.type('json').status(204).end()
199 async function removeVideoChannel (req: express.Request, res: express.Response) {
200 const videoChannelInstance = res.locals.videoChannel
202 await sequelizeTypescript.transaction(async t => {
203 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
205 await videoChannelInstance.destroy({ transaction: t })
207 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
208 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
211 return res.type('json').status(204).end()
214 async function getVideoChannel (req: express.Request, res: express.Response) {
215 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
217 if (videoChannelWithVideos.isOutdated()) {
218 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
219 .catch(err => logger.error('Cannot create AP refresher job for actor %s.', videoChannelWithVideos.Actor.url, { err }))
222 return res.json(videoChannelWithVideos.toFormattedJSON())
225 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
226 const serverActor = await getServerActor()
228 const resultList = await VideoPlaylistModel.listForApi({
229 followerActorId: serverActor.id,
230 start: req.query.start,
231 count: req.query.count,
232 sort: req.query.sort,
233 videoChannelId: res.locals.videoChannel.id,
234 type: req.query.playlistType
237 return res.json(getFormattedObjects(resultList.data, resultList.total))
240 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
241 const videoChannelInstance = res.locals.videoChannel
242 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
244 const resultList = await VideoModel.listForApi({
246 start: req.query.start,
247 count: req.query.count,
248 sort: req.query.sort,
249 includeLocalVideos: true,
250 categoryOneOf: req.query.categoryOneOf,
251 licenceOneOf: req.query.licenceOneOf,
252 languageOneOf: req.query.languageOneOf,
253 tagsOneOf: req.query.tagsOneOf,
254 tagsAllOf: req.query.tagsAllOf,
255 filter: req.query.filter,
256 nsfw: buildNSFWFilter(res, req.query.nsfw),
258 videoChannelId: videoChannelInstance.id,
259 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
262 return res.json(getFormattedObjects(resultList.data, resultList.total))