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 { JobQueue } from '../../lib/job-queue'
34 import { VideoPlaylistModel } from '../../models/video/video-playlist'
35 import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists'
37 const auditLogger = auditLoggerFactory('channels')
38 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
40 const videoChannelRouter = express.Router()
42 videoChannelRouter.get('/',
44 videoChannelsSortValidator,
47 asyncMiddleware(listVideoChannels)
50 videoChannelRouter.post('/',
52 asyncMiddleware(videoChannelsAddValidator),
53 asyncRetryTransactionMiddleware(addVideoChannel)
56 videoChannelRouter.post('/:nameWithHost/avatar/pick',
60 asyncMiddleware(videoChannelsUpdateValidator),
61 updateAvatarValidator,
62 asyncMiddleware(updateVideoChannelAvatar)
65 videoChannelRouter.put('/:nameWithHost',
67 asyncMiddleware(videoChannelsUpdateValidator),
68 asyncRetryTransactionMiddleware(updateVideoChannel)
71 videoChannelRouter.delete('/:nameWithHost',
73 asyncMiddleware(videoChannelsRemoveValidator),
74 asyncRetryTransactionMiddleware(removeVideoChannel)
77 videoChannelRouter.get('/:nameWithHost',
78 asyncMiddleware(videoChannelsNameWithHostValidator),
79 asyncMiddleware(getVideoChannel)
82 videoChannelRouter.get('/:nameWithHost/video-playlists',
83 asyncMiddleware(videoChannelsNameWithHostValidator),
85 videoPlaylistsSortValidator,
88 commonVideoPlaylistFiltersValidator,
89 asyncMiddleware(listVideoChannelPlaylists)
92 videoChannelRouter.get('/:nameWithHost/videos',
93 asyncMiddleware(videoChannelsNameWithHostValidator),
99 commonVideosFiltersValidator,
100 asyncMiddleware(listVideoChannelVideos)
103 // ---------------------------------------------------------------------------
109 // ---------------------------------------------------------------------------
111 async function listVideoChannels (req: express.Request, res: express.Response) {
112 const serverActor = await getServerActor()
113 const resultList = await VideoChannelModel.listForApi(serverActor.id, req.query.start, req.query.count, req.query.sort)
115 return res.json(getFormattedObjects(resultList.data, resultList.total))
118 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
119 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
120 const videoChannel = res.locals.videoChannel
121 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
123 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
125 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
129 avatar: avatar.toFormattedJSON()
134 async function addVideoChannel (req: express.Request, res: express.Response) {
135 const videoChannelInfo: VideoChannelCreate = req.body
137 const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => {
138 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
140 return createVideoChannel(videoChannelInfo, account, t)
143 setAsyncActorKeys(videoChannelCreated.Actor)
144 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err }))
146 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
147 logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid)
151 id: videoChannelCreated.id,
152 uuid: videoChannelCreated.Actor.uuid
157 async function updateVideoChannel (req: express.Request, res: express.Response) {
158 const videoChannelInstance = res.locals.videoChannel
159 const videoChannelFieldsSave = videoChannelInstance.toJSON()
160 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
161 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
164 await sequelizeTypescript.transaction(async t => {
165 const sequelizeOptions = {
169 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.displayName)
170 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description)
171 if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support)
173 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions)
174 await sendUpdateActor(videoChannelInstanceUpdated, t)
177 getAuditIdFromRes(res),
178 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
179 oldVideoChannelAuditKeys
181 logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
184 logger.debug('Cannot update the video channel.', { err })
186 // Force fields we want to update
187 // If the transaction is retried, sequelize will think the object has not changed
188 // So it will skip the SQL request, even if the last one was ROLLBACKed!
189 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
194 return res.type('json').status(204).end()
197 async function removeVideoChannel (req: express.Request, res: express.Response) {
198 const videoChannelInstance = res.locals.videoChannel
200 await sequelizeTypescript.transaction(async t => {
201 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
203 await videoChannelInstance.destroy({ transaction: t })
205 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
206 logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid)
209 return res.type('json').status(204).end()
212 async function getVideoChannel (req: express.Request, res: express.Response) {
213 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
215 if (videoChannelWithVideos.isOutdated()) {
216 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
217 .catch(err => logger.error('Cannot create AP refresher job for actor %s.', videoChannelWithVideos.Actor.url, { err }))
220 return res.json(videoChannelWithVideos.toFormattedJSON())
223 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
224 const serverActor = await getServerActor()
226 const resultList = await VideoPlaylistModel.listForApi({
227 followerActorId: serverActor.id,
228 start: req.query.start,
229 count: req.query.count,
230 sort: req.query.sort,
231 videoChannelId: res.locals.videoChannel.id,
232 type: req.query.playlistType
235 return res.json(getFormattedObjects(resultList.data, resultList.total))
238 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
239 const videoChannelInstance = res.locals.videoChannel
240 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
242 const resultList = await VideoModel.listForApi({
244 start: req.query.start,
245 count: req.query.count,
246 sort: req.query.sort,
247 includeLocalVideos: true,
248 categoryOneOf: req.query.categoryOneOf,
249 licenceOneOf: req.query.licenceOneOf,
250 languageOneOf: req.query.languageOneOf,
251 tagsOneOf: req.query.tagsOneOf,
252 tagsAllOf: req.query.tagsAllOf,
253 filter: req.query.filter,
254 nsfw: buildNSFWFilter(res, req.query.nsfw),
256 videoChannelId: videoChannelInstance.id,
257 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
260 return res.json(getFormattedObjects(resultList.data, resultList.total))