1 import * as express from 'express'
2 import { getFormattedObjects } 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, videoChannelsOwnSearchValidator } from '../../middlewares/validators'
20 import { sendUpdateActor } from '../../lib/activitypub/send'
21 import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared'
22 import { createLocalVideoChannel, federateAllVideosOfChannel } from '../../lib/video-channel'
23 import { buildNSFWFilter, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
24 import { setAsyncActorKeys } from '../../lib/activitypub/actor'
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'
38 import { MChannelAccountDefault } from '@server/types/models'
39 import { getServerActor } from '@server/models/application/application'
41 const auditLogger = auditLoggerFactory('channels')
42 const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR })
44 const videoChannelRouter = express.Router()
46 videoChannelRouter.get('/',
48 videoChannelsSortValidator,
51 videoChannelsOwnSearchValidator,
52 asyncMiddleware(listVideoChannels)
55 videoChannelRouter.post('/',
57 asyncMiddleware(videoChannelsAddValidator),
58 asyncRetryTransactionMiddleware(addVideoChannel)
61 videoChannelRouter.post('/:nameWithHost/avatar/pick',
65 asyncMiddleware(videoChannelsUpdateValidator),
66 updateAvatarValidator,
67 asyncMiddleware(updateVideoChannelAvatar)
70 videoChannelRouter.put('/:nameWithHost',
72 asyncMiddleware(videoChannelsUpdateValidator),
73 asyncRetryTransactionMiddleware(updateVideoChannel)
76 videoChannelRouter.delete('/:nameWithHost',
78 asyncMiddleware(videoChannelsRemoveValidator),
79 asyncRetryTransactionMiddleware(removeVideoChannel)
82 videoChannelRouter.get('/:nameWithHost',
83 asyncMiddleware(videoChannelsNameWithHostValidator),
84 asyncMiddleware(getVideoChannel)
87 videoChannelRouter.get('/:nameWithHost/video-playlists',
88 asyncMiddleware(videoChannelsNameWithHostValidator),
90 videoPlaylistsSortValidator,
93 commonVideoPlaylistFiltersValidator,
94 asyncMiddleware(listVideoChannelPlaylists)
97 videoChannelRouter.get('/:nameWithHost/videos',
98 asyncMiddleware(videoChannelsNameWithHostValidator),
102 setDefaultPagination,
103 optionalAuthenticate,
104 commonVideosFiltersValidator,
105 asyncMiddleware(listVideoChannelVideos)
108 // ---------------------------------------------------------------------------
114 // ---------------------------------------------------------------------------
116 async function listVideoChannels (req: express.Request, res: express.Response) {
117 const serverActor = await getServerActor()
118 const resultList = await VideoChannelModel.listForApi({
119 actorId: serverActor.id,
120 start: req.query.start,
121 count: req.query.count,
122 sort: req.query.sort,
123 search: req.query.search
126 return res.json(getFormattedObjects(resultList.data, resultList.total))
129 async function updateVideoChannelAvatar (req: express.Request, res: express.Response) {
130 const avatarPhysicalFile = req.files['avatarfile'][0]
131 const videoChannel = res.locals.videoChannel
132 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON())
134 const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel)
136 auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys)
140 avatar: avatar.toFormattedJSON()
145 async function addVideoChannel (req: express.Request, res: express.Response) {
146 const videoChannelInfo: VideoChannelCreate = req.body
148 const videoChannelCreated = await sequelizeTypescript.transaction(async t => {
149 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
151 return createLocalVideoChannel(videoChannelInfo, account, t)
154 setAsyncActorKeys(videoChannelCreated.Actor)
155 .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.url, { err }))
157 auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()))
158 logger.info('Video channel %s created.', videoChannelCreated.Actor.url)
162 id: videoChannelCreated.id
167 async function updateVideoChannel (req: express.Request, res: express.Response) {
168 const videoChannelInstance = res.locals.videoChannel
169 const videoChannelFieldsSave = videoChannelInstance.toJSON()
170 const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())
171 const videoChannelInfoToUpdate = req.body as VideoChannelUpdate
172 let doBulkVideoUpdate = false
175 await sequelizeTypescript.transaction(async t => {
176 const sequelizeOptions = {
180 if (videoChannelInfoToUpdate.displayName !== undefined) videoChannelInstance.name = videoChannelInfoToUpdate.displayName
181 if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.description = videoChannelInfoToUpdate.description
183 if (videoChannelInfoToUpdate.support !== undefined) {
184 const oldSupportField = videoChannelInstance.support
185 videoChannelInstance.support = videoChannelInfoToUpdate.support
187 if (videoChannelInfoToUpdate.bulkVideosSupportUpdate === true && oldSupportField !== videoChannelInfoToUpdate.support) {
188 doBulkVideoUpdate = true
189 await VideoModel.bulkUpdateSupportField(videoChannelInstance, t)
193 const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) as MChannelAccountDefault
194 await sendUpdateActor(videoChannelInstanceUpdated, t)
197 getAuditIdFromRes(res),
198 new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()),
199 oldVideoChannelAuditKeys
202 logger.info('Video channel %s updated.', videoChannelInstance.Actor.url)
205 logger.debug('Cannot update the video channel.', { err })
207 // Force fields we want to update
208 // If the transaction is retried, sequelize will think the object has not changed
209 // So it will skip the SQL request, even if the last one was ROLLBACKed!
210 resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave)
215 res.type('json').status(204).end()
217 // Don't process in a transaction, and after the response because it could be long
218 if (doBulkVideoUpdate) {
219 await federateAllVideosOfChannel(videoChannelInstance)
223 async function removeVideoChannel (req: express.Request, res: express.Response) {
224 const videoChannelInstance = res.locals.videoChannel
226 await sequelizeTypescript.transaction(async t => {
227 await VideoPlaylistModel.resetPlaylistsOfChannel(videoChannelInstance.id, t)
229 await videoChannelInstance.destroy({ transaction: t })
231 auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()))
232 logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url)
235 return res.type('json').status(204).end()
238 async function getVideoChannel (req: express.Request, res: express.Response) {
239 const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id)
241 if (videoChannelWithVideos.isOutdated()) {
242 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: videoChannelWithVideos.Actor.url } })
245 return res.json(videoChannelWithVideos.toFormattedJSON())
248 async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {
249 const serverActor = await getServerActor()
251 const resultList = await VideoPlaylistModel.listForApi({
252 followerActorId: serverActor.id,
253 start: req.query.start,
254 count: req.query.count,
255 sort: req.query.sort,
256 videoChannelId: res.locals.videoChannel.id,
257 type: req.query.playlistType
260 return res.json(getFormattedObjects(resultList.data, resultList.total))
263 async function listVideoChannelVideos (req: express.Request, res: express.Response) {
264 const videoChannelInstance = res.locals.videoChannel
265 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
266 const countVideos = getCountVideos(req)
268 const resultList = await VideoModel.listForApi({
270 start: req.query.start,
271 count: req.query.count,
272 sort: req.query.sort,
273 includeLocalVideos: true,
274 categoryOneOf: req.query.categoryOneOf,
275 licenceOneOf: req.query.licenceOneOf,
276 languageOneOf: req.query.languageOneOf,
277 tagsOneOf: req.query.tagsOneOf,
278 tagsAllOf: req.query.tagsAllOf,
279 filter: req.query.filter,
280 nsfw: buildNSFWFilter(res, req.query.nsfw),
282 videoChannelId: videoChannelInstance.id,
283 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
287 return res.json(getFormattedObjects(resultList.data, resultList.total))