1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
20 } from '../../../initializers'
22 changeVideoChannelShare,
23 federateVideoIfNeeded,
24 fetchRemoteVideoDescription,
25 getVideoActivityPubUrl
26 } from '../../../lib/activitypub'
27 import { sendCreateView } from '../../../lib/activitypub/send'
28 import { JobQueue } from '../../../lib/job-queue'
29 import { Redis } from '../../../lib/redis'
32 asyncRetryTransactionMiddleware,
40 videosRemoveValidator,
41 videosSearchValidator,
44 } from '../../../middlewares'
45 import { TagModel } from '../../../models/video/tag'
46 import { VideoModel } from '../../../models/video/video'
47 import { VideoFileModel } from '../../../models/video/video-file'
48 import { abuseVideoRouter } from './abuse'
49 import { blacklistRouter } from './blacklist'
50 import { videoCommentRouter } from './comment'
51 import { rateVideoRouter } from './rate'
52 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53 import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
54 import { createReqFiles, isNSFWHidden } from '../../../helpers/express-utils'
55 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
57 const videosRouter = express.Router()
59 const reqVideoFileAdd = createReqFiles(
60 [ 'videofile', 'thumbnailfile', 'previewfile' ],
61 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
63 videofile: CONFIG.STORAGE.VIDEOS_DIR,
64 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
65 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
68 const reqVideoFileUpdate = createReqFiles(
69 [ 'thumbnailfile', 'previewfile' ],
72 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
73 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
77 videosRouter.use('/', abuseVideoRouter)
78 videosRouter.use('/', blacklistRouter)
79 videosRouter.use('/', rateVideoRouter)
80 videosRouter.use('/', videoCommentRouter)
82 videosRouter.get('/categories', listVideoCategories)
83 videosRouter.get('/licences', listVideoLicences)
84 videosRouter.get('/languages', listVideoLanguages)
85 videosRouter.get('/privacies', listVideoPrivacies)
93 asyncMiddleware(listVideos)
95 videosRouter.get('/search',
96 videosSearchValidator,
100 setDefaultPagination,
101 optionalAuthenticate,
102 asyncMiddleware(searchVideos)
104 videosRouter.put('/:id',
107 asyncMiddleware(videosUpdateValidator),
108 asyncRetryTransactionMiddleware(updateVideo)
110 videosRouter.post('/upload',
113 asyncMiddleware(videosAddValidator),
114 asyncRetryTransactionMiddleware(addVideo)
117 videosRouter.get('/:id/description',
118 asyncMiddleware(videosGetValidator),
119 asyncMiddleware(getVideoDescription)
121 videosRouter.get('/:id',
122 asyncMiddleware(videosGetValidator),
125 videosRouter.post('/:id/views',
126 asyncMiddleware(videosGetValidator),
127 asyncMiddleware(viewVideo)
130 videosRouter.delete('/:id',
132 asyncMiddleware(videosRemoveValidator),
133 asyncRetryTransactionMiddleware(removeVideo)
136 // ---------------------------------------------------------------------------
142 // ---------------------------------------------------------------------------
144 function listVideoCategories (req: express.Request, res: express.Response) {
145 res.json(VIDEO_CATEGORIES)
148 function listVideoLicences (req: express.Request, res: express.Response) {
149 res.json(VIDEO_LICENCES)
152 function listVideoLanguages (req: express.Request, res: express.Response) {
153 res.json(VIDEO_LANGUAGES)
156 function listVideoPrivacies (req: express.Request, res: express.Response) {
157 res.json(VIDEO_PRIVACIES)
160 async function addVideo (req: express.Request, res: express.Response) {
161 const videoPhysicalFile = req.files['videofile'][0]
162 const videoInfo: VideoCreate = req.body
164 // Prepare data so we don't block the transaction
166 name: videoInfo.name,
168 extname: extname(videoPhysicalFile.filename),
169 category: videoInfo.category,
170 licence: videoInfo.licence,
171 language: videoInfo.language,
172 commentsEnabled: videoInfo.commentsEnabled || false,
173 waitTranscoding: videoInfo.waitTranscoding || false,
174 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
175 nsfw: videoInfo.nsfw || false,
176 description: videoInfo.description,
177 support: videoInfo.support,
178 privacy: videoInfo.privacy,
179 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
180 channelId: res.locals.videoChannel.id
182 const video = new VideoModel(videoData)
183 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
185 // Build the file object
186 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
187 const videoFileData = {
188 extname: extname(videoPhysicalFile.filename),
189 resolution: videoFileResolution,
190 size: videoPhysicalFile.size
192 const videoFile = new VideoFileModel(videoFileData)
194 // Move physical file
195 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
196 const destination = join(videoDir, video.getVideoFilename(videoFile))
197 await renamePromise(videoPhysicalFile.path, destination)
198 // This is important in case if there is another attempt in the retry process
199 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
200 videoPhysicalFile.path = destination
202 // Process thumbnail or create it from the video
203 const thumbnailField = req.files['thumbnailfile']
204 if (thumbnailField) {
205 const thumbnailPhysicalFile = thumbnailField[0]
206 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
208 await video.createThumbnail(videoFile)
211 // Process preview or create it from the video
212 const previewField = req.files['previewfile']
214 const previewPhysicalFile = previewField[0]
215 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
217 await video.createPreview(videoFile)
220 // Create the torrent file
221 await video.createTorrentAndSetInfoHash(videoFile)
223 const videoCreated = await sequelizeTypescript.transaction(async t => {
224 const sequelizeOptions = { transaction: t }
226 const videoCreated = await video.save(sequelizeOptions)
227 // Do not forget to add video channel information to the created video
228 videoCreated.VideoChannel = res.locals.videoChannel
230 videoFile.videoId = video.id
231 await videoFile.save(sequelizeOptions)
233 video.VideoFiles = [ videoFile ]
236 if (videoInfo.tags !== undefined) {
237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
239 await video.$set('Tags', tagInstances, sequelizeOptions)
240 video.Tags = tagInstances
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
252 await federateVideoIfNeeded(video, true, t)
254 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
259 if (video.state === VideoState.TO_TRANSCODE) {
260 // Put uuid because we don't have id auto incremented for now
262 videoUUID: videoCreated.uuid,
266 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
272 uuid: videoCreated.uuid
277 async function updateVideo (req: express.Request, res: express.Response) {
278 const videoInstance: VideoModel = res.locals.video
279 const videoFieldsSave = videoInstance.toJSON()
280 const videoInfoToUpdate: VideoUpdate = req.body
281 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
283 // Process thumbnail or create it from the video
284 if (req.files && req.files['thumbnailfile']) {
285 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
286 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
289 // Process preview or create it from the video
290 if (req.files && req.files['previewfile']) {
291 const previewPhysicalFile = req.files['previewfile'][0]
292 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
296 await sequelizeTypescript.transaction(async t => {
297 const sequelizeOptions = {
300 const oldVideoChannel = videoInstance.VideoChannel
302 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
303 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
304 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
305 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
306 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
307 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
308 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
311 if (videoInfoToUpdate.privacy !== undefined) {
312 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
313 videoInstance.set('privacy', newPrivacy)
315 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
316 videoInstance.set('publishedAt', new Date())
320 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
322 // Video tags update?
323 if (videoInfoToUpdate.tags !== undefined) {
324 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
326 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
327 videoInstanceUpdated.Tags = tagInstances
330 // Video channel update?
331 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
332 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
333 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
335 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
338 // Schedule an update in the future?
339 if (videoInfoToUpdate.scheduleUpdate) {
340 await ScheduleVideoUpdateModel.upsert({
341 videoId: videoInstanceUpdated.id,
342 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
343 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
344 }, { transaction: t })
345 } else if (videoInfoToUpdate.scheduleUpdate === null) {
346 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
349 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
350 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
353 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
355 // Force fields we want to update
356 // If the transaction is retried, sequelize will think the object has not changed
357 // So it will skip the SQL request, even if the last one was ROLLBACKed!
358 resetSequelizeInstance(videoInstance, videoFieldsSave)
363 return res.type('json').status(204).end()
366 function getVideo (req: express.Request, res: express.Response) {
367 const videoInstance = res.locals.video
369 return res.json(videoInstance.toFormattedDetailsJSON())
372 async function viewVideo (req: express.Request, res: express.Response) {
373 const videoInstance = res.locals.video
376 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
378 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
379 return res.status(204).end()
382 await videoInstance.increment('views')
383 await Redis.Instance.setView(ip, videoInstance.uuid)
385 const serverAccount = await getServerActor()
387 await sendCreateView(serverAccount, videoInstance, undefined)
389 return res.status(204).end()
392 async function getVideoDescription (req: express.Request, res: express.Response) {
393 const videoInstance = res.locals.video
396 if (videoInstance.isOwned()) {
397 description = videoInstance.description
399 description = await fetchRemoteVideoDescription(videoInstance)
402 return res.json({ description })
405 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
406 const resultList = await VideoModel.listForApi({
407 start: req.query.start,
408 count: req.query.count,
409 sort: req.query.sort,
410 hideNSFW: isNSFWHidden(res),
411 filter: req.query.filter as VideoFilter,
415 return res.json(getFormattedObjects(resultList.data, resultList.total))
418 async function removeVideo (req: express.Request, res: express.Response) {
419 const videoInstance: VideoModel = res.locals.video
421 await sequelizeTypescript.transaction(async t => {
422 await videoInstance.destroy({ transaction: t })
425 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
427 return res.type('json').status(204).end()
430 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
431 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
432 req.query.search as string,
433 req.query.start as number,
434 req.query.count as number,
435 req.query.sort as VideoSortField,
439 return res.json(getFormattedObjects(resultList.data, resultList.total))