1 import * as express from 'express'
2 import { extname } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { getVideoFileFPS, getVideoFileResolution, getMetadataFromFile } from '../../../helpers/ffmpeg-utils'
5 import { logger } from '../../../helpers/logger'
6 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
7 import { getFormattedObjects, getServerActor } from '../../../helpers/utils'
8 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
10 DEFAULT_AUDIO_RESOLUTION,
16 } from '../../../initializers/constants'
18 changeVideoChannelShare,
19 federateVideoIfNeeded,
20 fetchRemoteVideoDescription,
21 getVideoActivityPubUrl
22 } from '../../../lib/activitypub'
23 import { JobQueue } from '../../../lib/job-queue'
24 import { Redis } from '../../../lib/redis'
27 asyncRetryTransactionMiddleware,
29 checkVideoFollowConstraints,
30 commonVideosFiltersValidator,
36 videosCustomGetValidator,
38 videosRemoveValidator,
40 videosUpdateValidator,
41 videoFileMetadataGetValidator
42 } from '../../../middlewares'
43 import { TagModel } from '../../../models/video/tag'
44 import { VideoModel } from '../../../models/video/video'
45 import { VideoFileModel } from '../../../models/video/video-file'
46 import { abuseVideoRouter } from './abuse'
47 import { blacklistRouter } from './blacklist'
48 import { videoCommentRouter } from './comment'
49 import { rateVideoRouter } from './rate'
50 import { ownershipVideoRouter } from './ownership'
51 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
52 import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
53 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
54 import { videoCaptionsRouter } from './captions'
55 import { videoImportsRouter } from './import'
56 import { resetSequelizeInstance } from '../../../helpers/database-utils'
57 import { move } from 'fs-extra'
58 import { watchingRouter } from './watching'
59 import { Notifier } from '../../../lib/notifier'
60 import { sendView } from '../../../lib/activitypub/send/send-view'
61 import { CONFIG } from '../../../initializers/config'
62 import { sequelizeTypescript } from '../../../initializers/database'
63 import { createVideoMiniatureFromExisting, generateVideoMiniature } from '../../../lib/thumbnail'
64 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
65 import { VideoTranscodingPayload } from '../../../lib/job-queue/handlers/video-transcoding'
66 import { Hooks } from '../../../lib/plugins/hooks'
67 import { MVideoDetails, MVideoFullLight } from '@server/typings/models'
68 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
69 import { getVideoFilePath } from '@server/lib/video-paths'
70 import toInt from 'validator/lib/toInt'
72 const auditLogger = auditLoggerFactory('videos')
73 const videosRouter = express.Router()
75 const reqVideoFileAdd = createReqFiles(
76 [ 'videofile', 'thumbnailfile', 'previewfile' ],
77 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
79 videofile: CONFIG.STORAGE.TMP_DIR,
80 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
81 previewfile: CONFIG.STORAGE.TMP_DIR
84 const reqVideoFileUpdate = createReqFiles(
85 [ 'thumbnailfile', 'previewfile' ],
86 MIMETYPES.IMAGE.MIMETYPE_EXT,
88 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
89 previewfile: CONFIG.STORAGE.TMP_DIR
93 videosRouter.use('/', abuseVideoRouter)
94 videosRouter.use('/', blacklistRouter)
95 videosRouter.use('/', rateVideoRouter)
96 videosRouter.use('/', videoCommentRouter)
97 videosRouter.use('/', videoCaptionsRouter)
98 videosRouter.use('/', videoImportsRouter)
99 videosRouter.use('/', ownershipVideoRouter)
100 videosRouter.use('/', watchingRouter)
102 videosRouter.get('/categories', listVideoCategories)
103 videosRouter.get('/licences', listVideoLicences)
104 videosRouter.get('/languages', listVideoLanguages)
105 videosRouter.get('/privacies', listVideoPrivacies)
107 videosRouter.get('/',
111 setDefaultPagination,
112 optionalAuthenticate,
113 commonVideosFiltersValidator,
114 asyncMiddleware(listVideos)
116 videosRouter.put('/:id',
119 asyncMiddleware(videosUpdateValidator),
120 asyncRetryTransactionMiddleware(updateVideo)
122 videosRouter.post('/upload',
125 asyncMiddleware(videosAddValidator),
126 asyncRetryTransactionMiddleware(addVideo)
129 videosRouter.get('/:id/description',
130 asyncMiddleware(videosGetValidator),
131 asyncMiddleware(getVideoDescription)
133 videosRouter.get('/:id/metadata/:videoFileId',
134 asyncMiddleware(videoFileMetadataGetValidator),
135 asyncMiddleware(getVideoFileMetadata)
137 videosRouter.get('/:id',
138 optionalAuthenticate,
139 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
140 asyncMiddleware(checkVideoFollowConstraints),
141 asyncMiddleware(getVideo)
143 videosRouter.post('/:id/views',
144 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
145 asyncMiddleware(viewVideo)
148 videosRouter.delete('/:id',
150 asyncMiddleware(videosRemoveValidator),
151 asyncRetryTransactionMiddleware(removeVideo)
154 // ---------------------------------------------------------------------------
160 // ---------------------------------------------------------------------------
162 function listVideoCategories (req: express.Request, res: express.Response) {
163 res.json(VIDEO_CATEGORIES)
166 function listVideoLicences (req: express.Request, res: express.Response) {
167 res.json(VIDEO_LICENCES)
170 function listVideoLanguages (req: express.Request, res: express.Response) {
171 res.json(VIDEO_LANGUAGES)
174 function listVideoPrivacies (req: express.Request, res: express.Response) {
175 res.json(VIDEO_PRIVACIES)
178 async function addVideo (req: express.Request, res: express.Response) {
179 // Processing the video could be long
180 // Set timeout to 10 minutes
181 req.setTimeout(1000 * 60 * 10, () => {
182 logger.error('Upload video has timed out.')
183 return res.sendStatus(408)
186 const videoPhysicalFile = req.files['videofile'][0]
187 const videoInfo: VideoCreate = req.body
189 // Prepare data so we don't block the transaction
191 name: videoInfo.name,
193 category: videoInfo.category,
194 licence: videoInfo.licence,
195 language: videoInfo.language,
196 commentsEnabled: videoInfo.commentsEnabled !== false, // If the value is not "false", the default is "true"
197 downloadEnabled: videoInfo.downloadEnabled !== false,
198 waitTranscoding: videoInfo.waitTranscoding || false,
199 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
200 nsfw: videoInfo.nsfw || false,
201 description: videoInfo.description,
202 support: videoInfo.support,
203 privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
204 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
205 channelId: res.locals.videoChannel.id,
206 originallyPublishedAt: videoInfo.originallyPublishedAt
209 const video = new VideoModel(videoData) as MVideoDetails
210 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
212 const videoFile = new VideoFileModel({
213 extname: extname(videoPhysicalFile.filename),
214 size: videoPhysicalFile.size,
215 videoStreamingPlaylistId: null,
216 metadata: await getMetadataFromFile<any>(videoPhysicalFile.path)
219 if (videoFile.isAudio()) {
220 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
222 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
223 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
226 // Move physical file
227 const destination = getVideoFilePath(video, videoFile)
228 await move(videoPhysicalFile.path, destination)
229 // This is important in case if there is another attempt in the retry process
230 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
231 videoPhysicalFile.path = destination
233 // Process thumbnail or create it from the video
234 const thumbnailField = req.files['thumbnailfile']
235 const thumbnailModel = thumbnailField
236 ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
237 : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
239 // Process preview or create it from the video
240 const previewField = req.files['previewfile']
241 const previewModel = previewField
242 ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
243 : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
245 // Create the torrent file
246 await createTorrentAndSetInfoHash(video, videoFile)
248 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
249 const sequelizeOptions = { transaction: t }
251 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
253 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
254 await videoCreated.addAndSaveThumbnail(previewModel, t)
256 // Do not forget to add video channel information to the created video
257 videoCreated.VideoChannel = res.locals.videoChannel
259 videoFile.videoId = video.id
260 await videoFile.save(sequelizeOptions)
262 video.VideoFiles = [ videoFile ]
265 if (videoInfo.tags !== undefined) {
266 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
268 await video.$set('Tags', tagInstances, sequelizeOptions)
269 video.Tags = tagInstances
272 // Schedule an update in the future?
273 if (videoInfo.scheduleUpdate) {
274 await ScheduleVideoUpdateModel.create({
276 updateAt: videoInfo.scheduleUpdate.updateAt,
277 privacy: videoInfo.scheduleUpdate.privacy || null
278 }, { transaction: t })
281 await autoBlacklistVideoIfNeeded({
283 user: res.locals.oauth.token.User,
288 await federateVideoIfNeeded(video, true, t)
290 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
291 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
293 return { videoCreated }
296 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
298 if (video.state === VideoState.TO_TRANSCODE) {
299 // Put uuid because we don't have id auto incremented for now
300 let dataInput: VideoTranscodingPayload
302 if (videoFile.isAudio()) {
304 type: 'merge-audio' as 'merge-audio',
305 resolution: DEFAULT_AUDIO_RESOLUTION,
306 videoUUID: videoCreated.uuid,
311 type: 'optimize' as 'optimize',
312 videoUUID: videoCreated.uuid,
317 await JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: dataInput })
320 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
325 uuid: videoCreated.uuid
330 async function updateVideo (req: express.Request, res: express.Response) {
331 const videoInstance = res.locals.videoAll
332 const videoFieldsSave = videoInstance.toJSON()
333 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
334 const videoInfoToUpdate: VideoUpdate = req.body
336 const wasConfidentialVideo = videoInstance.isConfidential()
337 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
339 // Process thumbnail or create it from the video
340 const thumbnailModel = req.files && req.files['thumbnailfile']
341 ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false)
344 const previewModel = req.files && req.files['previewfile']
345 ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
349 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
350 const sequelizeOptions = { transaction: t }
351 const oldVideoChannel = videoInstance.VideoChannel
353 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
354 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
355 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
356 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
357 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
358 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
359 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
360 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
361 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
362 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
364 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
365 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
368 let isNewVideo = false
369 if (videoInfoToUpdate.privacy !== undefined) {
370 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
372 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
373 videoInstance.setPrivacy(newPrivacy)
375 // Unfederate the video if the new privacy is not compatible with federation
376 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
377 await VideoModel.sendDelete(videoInstance, { transaction: t })
381 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
383 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
384 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
386 // Video tags update?
387 if (videoInfoToUpdate.tags !== undefined) {
388 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
390 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
391 videoInstanceUpdated.Tags = tagInstances
394 // Video channel update?
395 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
396 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
397 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
399 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
402 // Schedule an update in the future?
403 if (videoInfoToUpdate.scheduleUpdate) {
404 await ScheduleVideoUpdateModel.upsert({
405 videoId: videoInstanceUpdated.id,
406 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
407 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
408 }, { transaction: t })
409 } else if (videoInfoToUpdate.scheduleUpdate === null) {
410 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
413 await autoBlacklistVideoIfNeeded({
414 video: videoInstanceUpdated,
415 user: res.locals.oauth.token.User,
421 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
424 getAuditIdFromRes(res),
425 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
428 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
430 return videoInstanceUpdated
433 if (wasConfidentialVideo) {
434 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
437 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
439 // Force fields we want to update
440 // If the transaction is retried, sequelize will think the object has not changed
441 // So it will skip the SQL request, even if the last one was ROLLBACKed!
442 resetSequelizeInstance(videoInstance, videoFieldsSave)
447 return res.type('json').status(204).end()
450 async function getVideo (req: express.Request, res: express.Response) {
451 // We need more attributes
452 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
454 const video = await Hooks.wrapPromiseFun(
455 VideoModel.loadForGetAPI,
456 { id: res.locals.onlyVideoWithRights.id, userId },
457 'filter:api.video.get.result'
460 if (video.isOutdated()) {
461 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
464 return res.json(video.toFormattedDetailsJSON())
467 async function viewVideo (req: express.Request, res: express.Response) {
468 const videoInstance = res.locals.onlyImmutableVideo
471 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
473 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
474 return res.status(204).end()
478 Redis.Instance.addVideoView(videoInstance.id),
479 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
482 const serverActor = await getServerActor()
483 await sendView(serverActor, videoInstance, undefined)
485 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
487 return res.status(204).end()
490 async function getVideoDescription (req: express.Request, res: express.Response) {
491 const videoInstance = res.locals.videoAll
494 if (videoInstance.isOwned()) {
495 description = videoInstance.description
497 description = await fetchRemoteVideoDescription(videoInstance)
500 return res.json({ description })
503 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
504 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
505 return res.json(videoFile.metadata)
508 async function listVideos (req: express.Request, res: express.Response) {
509 const countVideos = getCountVideos(req)
511 const apiOptions = await Hooks.wrapObject({
512 start: req.query.start,
513 count: req.query.count,
514 sort: req.query.sort,
515 includeLocalVideos: true,
516 categoryOneOf: req.query.categoryOneOf,
517 licenceOneOf: req.query.licenceOneOf,
518 languageOneOf: req.query.languageOneOf,
519 tagsOneOf: req.query.tagsOneOf,
520 tagsAllOf: req.query.tagsAllOf,
521 nsfw: buildNSFWFilter(res, req.query.nsfw),
522 filter: req.query.filter as VideoFilter,
524 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
526 }, 'filter:api.videos.list.params')
528 const resultList = await Hooks.wrapPromiseFun(
529 VideoModel.listForApi,
531 'filter:api.videos.list.result'
534 return res.json(getFormattedObjects(resultList.data, resultList.total))
537 async function removeVideo (req: express.Request, res: express.Response) {
538 const videoInstance = res.locals.videoAll
540 await sequelizeTypescript.transaction(async t => {
541 await videoInstance.destroy({ transaction: t })
544 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
545 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
547 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
549 return res.type('json').status(204).end()