1 import * as express from 'express'
2 import { move } from 'fs-extra'
3 import { extname } from 'path'
4 import toInt from 'validator/lib/toInt'
5 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
6 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
7 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
8 import { LiveManager } from '@server/lib/live-manager'
9 import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
10 import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
11 import { getServerActor } from '@server/models/application/application'
12 import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
13 import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
14 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
15 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
16 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
17 import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils'
18 import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
19 import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
20 import { logger, loggerTagsFactory } from '../../../helpers/logger'
21 import { getFormattedObjects } from '../../../helpers/utils'
22 import { CONFIG } from '../../../initializers/config'
24 DEFAULT_AUDIO_RESOLUTION,
30 } from '../../../initializers/constants'
31 import { sequelizeTypescript } from '../../../initializers/database'
32 import { sendView } from '../../../lib/activitypub/send/send-view'
33 import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
34 import { JobQueue } from '../../../lib/job-queue'
35 import { Notifier } from '../../../lib/notifier'
36 import { Hooks } from '../../../lib/plugins/hooks'
37 import { Redis } from '../../../lib/redis'
38 import { generateVideoMiniature } from '../../../lib/thumbnail'
39 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
42 asyncRetryTransactionMiddleware,
44 checkVideoFollowConstraints,
45 commonVideosFiltersValidator,
50 videoFileMetadataGetValidator,
52 videosCustomGetValidator,
54 videosRemoveValidator,
57 } from '../../../middlewares'
58 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
59 import { VideoModel } from '../../../models/video/video'
60 import { VideoFileModel } from '../../../models/video/video-file'
61 import { blacklistRouter } from './blacklist'
62 import { videoCaptionsRouter } from './captions'
63 import { videoCommentRouter } from './comment'
64 import { videoImportsRouter } from './import'
65 import { liveRouter } from './live'
66 import { ownershipVideoRouter } from './ownership'
67 import { rateVideoRouter } from './rate'
68 import { watchingRouter } from './watching'
70 const lTags = loggerTagsFactory('api', 'video')
71 const auditLogger = auditLoggerFactory('videos')
72 const videosRouter = express.Router()
74 const reqVideoFileAdd = createReqFiles(
75 [ 'videofile', 'thumbnailfile', 'previewfile' ],
76 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
78 videofile: CONFIG.STORAGE.TMP_DIR,
79 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
80 previewfile: CONFIG.STORAGE.TMP_DIR
83 const reqVideoFileUpdate = createReqFiles(
84 [ 'thumbnailfile', 'previewfile' ],
85 MIMETYPES.IMAGE.MIMETYPE_EXT,
87 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
88 previewfile: CONFIG.STORAGE.TMP_DIR
92 videosRouter.use('/', blacklistRouter)
93 videosRouter.use('/', rateVideoRouter)
94 videosRouter.use('/', videoCommentRouter)
95 videosRouter.use('/', videoCaptionsRouter)
96 videosRouter.use('/', videoImportsRouter)
97 videosRouter.use('/', ownershipVideoRouter)
98 videosRouter.use('/', watchingRouter)
99 videosRouter.use('/', liveRouter)
101 videosRouter.get('/categories', listVideoCategories)
102 videosRouter.get('/licences', listVideoLicences)
103 videosRouter.get('/languages', listVideoLanguages)
104 videosRouter.get('/privacies', listVideoPrivacies)
106 videosRouter.get('/',
109 setDefaultVideosSort,
110 setDefaultPagination,
111 optionalAuthenticate,
112 commonVideosFiltersValidator,
113 asyncMiddleware(listVideos)
115 videosRouter.put('/:id',
118 asyncMiddleware(videosUpdateValidator),
119 asyncRetryTransactionMiddleware(updateVideo)
121 videosRouter.post('/upload',
124 asyncMiddleware(videosAddValidator),
125 asyncRetryTransactionMiddleware(addVideo)
128 videosRouter.get('/:id/description',
129 asyncMiddleware(videosGetValidator),
130 asyncMiddleware(getVideoDescription)
132 videosRouter.get('/:id/metadata/:videoFileId',
133 asyncMiddleware(videoFileMetadataGetValidator),
134 asyncMiddleware(getVideoFileMetadata)
136 videosRouter.get('/:id',
137 optionalAuthenticate,
138 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
139 asyncMiddleware(checkVideoFollowConstraints),
140 asyncMiddleware(getVideo)
142 videosRouter.post('/:id/views',
143 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
144 asyncMiddleware(viewVideo)
147 videosRouter.delete('/:id',
149 asyncMiddleware(videosRemoveValidator),
150 asyncRetryTransactionMiddleware(removeVideo)
153 // ---------------------------------------------------------------------------
159 // ---------------------------------------------------------------------------
161 function listVideoCategories (req: express.Request, res: express.Response) {
162 res.json(VIDEO_CATEGORIES)
165 function listVideoLicences (req: express.Request, res: express.Response) {
166 res.json(VIDEO_LICENCES)
169 function listVideoLanguages (req: express.Request, res: express.Response) {
170 res.json(VIDEO_LANGUAGES)
173 function listVideoPrivacies (req: express.Request, res: express.Response) {
174 res.json(VIDEO_PRIVACIES)
177 async function addVideo (req: express.Request, res: express.Response) {
178 // Uploading the video could be long
179 // Set timeout to 10 minutes, as Express's default is 2 minutes
180 req.setTimeout(1000 * 60 * 10, () => {
181 logger.error('Upload video has timed out.')
182 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
185 const videoPhysicalFile = req.files['videofile'][0]
186 const videoInfo: VideoCreate = req.body
188 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
189 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
190 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
192 const video = new VideoModel(videoData) as MVideoFullLight
193 video.VideoChannel = res.locals.videoChannel
194 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
196 const videoFile = new VideoFileModel({
197 extname: extname(videoPhysicalFile.filename),
198 size: videoPhysicalFile.size,
199 videoStreamingPlaylistId: null,
200 metadata: await getMetadataFromFile(videoPhysicalFile.path)
203 if (videoFile.isAudio()) {
204 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
206 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
207 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
210 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
212 // Move physical file
213 const destination = getVideoFilePath(video, videoFile)
214 await move(videoPhysicalFile.path, destination)
215 // This is important in case if there is another attempt in the retry process
216 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
217 videoPhysicalFile.path = destination
219 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
222 fallback: type => generateVideoMiniature({ video, videoFile, type })
225 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
226 const sequelizeOptions = { transaction: t }
228 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
230 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
231 await videoCreated.addAndSaveThumbnail(previewModel, t)
233 // Do not forget to add video channel information to the created video
234 videoCreated.VideoChannel = res.locals.videoChannel
236 videoFile.videoId = video.id
237 await videoFile.save(sequelizeOptions)
239 video.VideoFiles = [ videoFile ]
241 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
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 autoBlacklistVideoIfNeeded({
254 user: res.locals.oauth.token.User,
260 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
261 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
263 return { videoCreated }
266 // Create the torrent file in async way because it could be long
267 createTorrentAndSetInfoHashAsync(video, videoFile)
268 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
269 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
270 .then(refreshedVideo => {
271 if (!refreshedVideo) return
273 // Only federate and notify after the torrent creation
274 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
276 return retryTransactionWrapper(() => {
277 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
280 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
282 if (video.state === VideoState.TO_TRANSCODE) {
283 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
286 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
291 uuid: videoCreated.uuid
296 async function updateVideo (req: express.Request, res: express.Response) {
297 const videoInstance = res.locals.videoAll
298 const videoFieldsSave = videoInstance.toJSON()
299 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
300 const videoInfoToUpdate: VideoUpdate = req.body
302 const wasConfidentialVideo = videoInstance.isConfidential()
303 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
305 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
306 video: videoInstance,
308 fallback: () => Promise.resolve(undefined),
309 automaticallyGenerated: false
313 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
314 const sequelizeOptions = { transaction: t }
315 const oldVideoChannel = videoInstance.VideoChannel
317 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
318 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
319 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
320 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
321 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
322 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
323 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
324 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
325 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
326 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
328 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
329 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
332 let isNewVideo = false
333 if (videoInfoToUpdate.privacy !== undefined) {
334 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
336 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
337 videoInstance.setPrivacy(newPrivacy)
339 // Unfederate the video if the new privacy is not compatible with federation
340 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
341 await VideoModel.sendDelete(videoInstance, { transaction: t })
345 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
347 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
348 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
350 // Video tags update?
351 if (videoInfoToUpdate.tags !== undefined) {
353 video: videoInstanceUpdated,
354 tags: videoInfoToUpdate.tags,
359 // Video channel update?
360 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
361 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
362 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
364 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
367 // Schedule an update in the future?
368 if (videoInfoToUpdate.scheduleUpdate) {
369 await ScheduleVideoUpdateModel.upsert({
370 videoId: videoInstanceUpdated.id,
371 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
372 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
373 }, { transaction: t })
374 } else if (videoInfoToUpdate.scheduleUpdate === null) {
375 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
378 await autoBlacklistVideoIfNeeded({
379 video: videoInstanceUpdated,
380 user: res.locals.oauth.token.User,
386 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
389 getAuditIdFromRes(res),
390 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
393 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
395 return videoInstanceUpdated
398 if (wasConfidentialVideo) {
399 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
402 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
404 // Force fields we want to update
405 // If the transaction is retried, sequelize will think the object has not changed
406 // So it will skip the SQL request, even if the last one was ROLLBACKed!
407 resetSequelizeInstance(videoInstance, videoFieldsSave)
412 return res.type('json')
413 .status(HttpStatusCode.NO_CONTENT_204)
417 async function getVideo (req: express.Request, res: express.Response) {
418 // We need more attributes
419 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
421 const video = await Hooks.wrapPromiseFun(
422 VideoModel.loadForGetAPI,
423 { id: res.locals.onlyVideoWithRights.id, userId },
424 'filter:api.video.get.result'
427 if (video.isOutdated()) {
428 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
431 return res.json(video.toFormattedDetailsJSON())
434 async function viewVideo (req: express.Request, res: express.Response) {
435 const immutableVideoAttrs = res.locals.onlyImmutableVideo
438 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
440 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
441 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
444 const video = await VideoModel.load(immutableVideoAttrs.id)
446 const promises: Promise<any>[] = [
447 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
450 let federateView = true
452 // Increment our live manager
453 if (video.isLive && video.isOwned()) {
454 LiveManager.Instance.addViewTo(video.id)
456 // Views of our local live will be sent by our live manager
460 // Increment our video views cache counter
462 promises.push(Redis.Instance.addVideoView(video.id))
466 const serverActor = await getServerActor()
467 promises.push(sendView(serverActor, video, undefined))
470 await Promise.all(promises)
472 Hooks.runAction('action:api.video.viewed', { video, ip })
474 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
477 async function getVideoDescription (req: express.Request, res: express.Response) {
478 const videoInstance = res.locals.videoAll
481 if (videoInstance.isOwned()) {
482 description = videoInstance.description
484 description = await fetchRemoteVideoDescription(videoInstance)
487 return res.json({ description })
490 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
491 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
493 return res.json(videoFile.metadata)
496 async function listVideos (req: express.Request, res: express.Response) {
497 const countVideos = getCountVideos(req)
499 const apiOptions = await Hooks.wrapObject({
500 start: req.query.start,
501 count: req.query.count,
502 sort: req.query.sort,
503 includeLocalVideos: true,
504 categoryOneOf: req.query.categoryOneOf,
505 licenceOneOf: req.query.licenceOneOf,
506 languageOneOf: req.query.languageOneOf,
507 tagsOneOf: req.query.tagsOneOf,
508 tagsAllOf: req.query.tagsAllOf,
509 nsfw: buildNSFWFilter(res, req.query.nsfw),
510 filter: req.query.filter as VideoFilter,
512 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
514 }, 'filter:api.videos.list.params')
516 const resultList = await Hooks.wrapPromiseFun(
517 VideoModel.listForApi,
519 'filter:api.videos.list.result'
522 return res.json(getFormattedObjects(resultList.data, resultList.total))
525 async function removeVideo (req: express.Request, res: express.Response) {
526 const videoInstance = res.locals.videoAll
528 await sequelizeTypescript.transaction(async t => {
529 await videoInstance.destroy({ transaction: t })
532 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
533 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
535 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
537 return res.type('json')
538 .status(HttpStatusCode.NO_CONTENT_204)
542 async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
543 await createTorrentAndSetInfoHash(video, fileArg)
545 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
546 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
547 // File does not exist anymore, remove the generated torrent
548 if (!refreshedFile) return fileArg.removeTorrent()
550 refreshedFile.infoHash = fileArg.infoHash
551 refreshedFile.torrentFilename = fileArg.torrentFilename
553 return refreshedFile.save()