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 { getVideoFilePath } from '@server/lib/video-paths'
11 import { getServerActor } from '@server/models/application/application'
12 import { 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 } 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 } 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 auditLogger = auditLoggerFactory('videos')
71 const videosRouter = express.Router()
73 const reqVideoFileAdd = createReqFiles(
74 [ 'videofile', 'thumbnailfile', 'previewfile' ],
75 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
77 videofile: CONFIG.STORAGE.TMP_DIR,
78 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
79 previewfile: CONFIG.STORAGE.TMP_DIR
82 const reqVideoFileUpdate = createReqFiles(
83 [ 'thumbnailfile', 'previewfile' ],
84 MIMETYPES.IMAGE.MIMETYPE_EXT,
86 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
87 previewfile: CONFIG.STORAGE.TMP_DIR
91 videosRouter.use('/', blacklistRouter)
92 videosRouter.use('/', rateVideoRouter)
93 videosRouter.use('/', videoCommentRouter)
94 videosRouter.use('/', videoCaptionsRouter)
95 videosRouter.use('/', videoImportsRouter)
96 videosRouter.use('/', ownershipVideoRouter)
97 videosRouter.use('/', watchingRouter)
98 videosRouter.use('/', liveRouter)
100 videosRouter.get('/categories', listVideoCategories)
101 videosRouter.get('/licences', listVideoLicences)
102 videosRouter.get('/languages', listVideoLanguages)
103 videosRouter.get('/privacies', listVideoPrivacies)
105 videosRouter.get('/',
108 setDefaultVideosSort,
109 setDefaultPagination,
110 optionalAuthenticate,
111 commonVideosFiltersValidator,
112 asyncMiddleware(listVideos)
114 videosRouter.put('/:id',
117 asyncMiddleware(videosUpdateValidator),
118 asyncRetryTransactionMiddleware(updateVideo)
120 videosRouter.post('/upload',
123 asyncMiddleware(videosAddValidator),
124 asyncRetryTransactionMiddleware(addVideo)
127 videosRouter.get('/:id/description',
128 asyncMiddleware(videosGetValidator),
129 asyncMiddleware(getVideoDescription)
131 videosRouter.get('/:id/metadata/:videoFileId',
132 asyncMiddleware(videoFileMetadataGetValidator),
133 asyncMiddleware(getVideoFileMetadata)
135 videosRouter.get('/:id',
136 optionalAuthenticate,
137 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
138 asyncMiddleware(checkVideoFollowConstraints),
139 asyncMiddleware(getVideo)
141 videosRouter.post('/:id/views',
142 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
143 asyncMiddleware(viewVideo)
146 videosRouter.delete('/:id',
148 asyncMiddleware(videosRemoveValidator),
149 asyncRetryTransactionMiddleware(removeVideo)
152 // ---------------------------------------------------------------------------
158 // ---------------------------------------------------------------------------
160 function listVideoCategories (req: express.Request, res: express.Response) {
161 res.json(VIDEO_CATEGORIES)
164 function listVideoLicences (req: express.Request, res: express.Response) {
165 res.json(VIDEO_LICENCES)
168 function listVideoLanguages (req: express.Request, res: express.Response) {
169 res.json(VIDEO_LANGUAGES)
172 function listVideoPrivacies (req: express.Request, res: express.Response) {
173 res.json(VIDEO_PRIVACIES)
176 async function addVideo (req: express.Request, res: express.Response) {
177 // Uploading the video could be long
178 // Set timeout to 10 minutes, as Express's default is 2 minutes
179 req.setTimeout(1000 * 60 * 10, () => {
180 logger.error('Upload video has timed out.')
181 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
184 const videoPhysicalFile = req.files['videofile'][0]
185 const videoInfo: VideoCreate = req.body
187 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
188 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
189 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
191 const video = new VideoModel(videoData) as MVideoFullLight
192 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
194 const videoFile = new VideoFileModel({
195 extname: extname(videoPhysicalFile.filename),
196 size: videoPhysicalFile.size,
197 videoStreamingPlaylistId: null,
198 metadata: await getMetadataFromFile(videoPhysicalFile.path)
201 if (videoFile.isAudio()) {
202 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
204 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
205 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
208 // Move physical file
209 const destination = getVideoFilePath(video, videoFile)
210 await move(videoPhysicalFile.path, destination)
211 // This is important in case if there is another attempt in the retry process
212 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
213 videoPhysicalFile.path = destination
215 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
218 fallback: type => generateVideoMiniature(video, videoFile, type)
221 // Create the torrent file
222 await createTorrentAndSetInfoHash(video, videoFile)
224 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
225 const sequelizeOptions = { transaction: t }
227 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
229 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
230 await videoCreated.addAndSaveThumbnail(previewModel, t)
232 // Do not forget to add video channel information to the created video
233 videoCreated.VideoChannel = res.locals.videoChannel
235 videoFile.videoId = video.id
236 await videoFile.save(sequelizeOptions)
238 video.VideoFiles = [ videoFile ]
240 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
242 // Schedule an update in the future?
243 if (videoInfo.scheduleUpdate) {
244 await ScheduleVideoUpdateModel.create({
246 updateAt: videoInfo.scheduleUpdate.updateAt,
247 privacy: videoInfo.scheduleUpdate.privacy || null
248 }, { transaction: t })
251 await autoBlacklistVideoIfNeeded({
253 user: res.locals.oauth.token.User,
258 await federateVideoIfNeeded(video, true, t)
260 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
261 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
263 return { videoCreated }
266 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
268 if (video.state === VideoState.TO_TRANSCODE) {
269 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
272 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
277 uuid: videoCreated.uuid
282 async function updateVideo (req: express.Request, res: express.Response) {
283 const videoInstance = res.locals.videoAll
284 const videoFieldsSave = videoInstance.toJSON()
285 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
286 const videoInfoToUpdate: VideoUpdate = req.body
288 const wasConfidentialVideo = videoInstance.isConfidential()
289 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
291 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
292 video: videoInstance,
294 fallback: () => Promise.resolve(undefined),
295 automaticallyGenerated: false
299 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
300 const sequelizeOptions = { transaction: t }
301 const oldVideoChannel = videoInstance.VideoChannel
303 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
304 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
305 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
306 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
307 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
308 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
309 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
310 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
311 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
312 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
314 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
315 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
318 let isNewVideo = false
319 if (videoInfoToUpdate.privacy !== undefined) {
320 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
322 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
323 videoInstance.setPrivacy(newPrivacy)
325 // Unfederate the video if the new privacy is not compatible with federation
326 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
327 await VideoModel.sendDelete(videoInstance, { transaction: t })
331 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
333 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
334 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
336 // Video tags update?
338 video: videoInstanceUpdated,
339 tags: videoInfoToUpdate.tags,
341 defaultValue: videoInstanceUpdated.Tags
344 // Video channel update?
345 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
346 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
347 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
349 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
352 // Schedule an update in the future?
353 if (videoInfoToUpdate.scheduleUpdate) {
354 await ScheduleVideoUpdateModel.upsert({
355 videoId: videoInstanceUpdated.id,
356 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
357 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
358 }, { transaction: t })
359 } else if (videoInfoToUpdate.scheduleUpdate === null) {
360 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
363 await autoBlacklistVideoIfNeeded({
364 video: videoInstanceUpdated,
365 user: res.locals.oauth.token.User,
371 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
374 getAuditIdFromRes(res),
375 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
378 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
380 return videoInstanceUpdated
383 if (wasConfidentialVideo) {
384 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
387 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
389 // Force fields we want to update
390 // If the transaction is retried, sequelize will think the object has not changed
391 // So it will skip the SQL request, even if the last one was ROLLBACKed!
392 resetSequelizeInstance(videoInstance, videoFieldsSave)
397 return res.type('json')
398 .status(HttpStatusCode.NO_CONTENT_204)
402 async function getVideo (req: express.Request, res: express.Response) {
403 // We need more attributes
404 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
406 const video = await Hooks.wrapPromiseFun(
407 VideoModel.loadForGetAPI,
408 { id: res.locals.onlyVideoWithRights.id, userId },
409 'filter:api.video.get.result'
412 if (video.isOutdated()) {
413 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
416 return res.json(video.toFormattedDetailsJSON())
419 async function viewVideo (req: express.Request, res: express.Response) {
420 const immutableVideoAttrs = res.locals.onlyImmutableVideo
423 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
425 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
426 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
429 const video = await VideoModel.load(immutableVideoAttrs.id)
431 const promises: Promise<any>[] = [
432 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
435 let federateView = true
437 // Increment our live manager
438 if (video.isLive && video.isOwned()) {
439 LiveManager.Instance.addViewTo(video.id)
441 // Views of our local live will be sent by our live manager
445 // Increment our video views cache counter
447 promises.push(Redis.Instance.addVideoView(video.id))
451 const serverActor = await getServerActor()
452 promises.push(sendView(serverActor, video, undefined))
455 await Promise.all(promises)
457 Hooks.runAction('action:api.video.viewed', { video, ip })
459 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
462 async function getVideoDescription (req: express.Request, res: express.Response) {
463 const videoInstance = res.locals.videoAll
466 if (videoInstance.isOwned()) {
467 description = videoInstance.description
469 description = await fetchRemoteVideoDescription(videoInstance)
472 return res.json({ description })
475 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
476 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
478 return res.json(videoFile.metadata)
481 async function listVideos (req: express.Request, res: express.Response) {
482 const countVideos = getCountVideos(req)
484 const apiOptions = await Hooks.wrapObject({
485 start: req.query.start,
486 count: req.query.count,
487 sort: req.query.sort,
488 includeLocalVideos: true,
489 categoryOneOf: req.query.categoryOneOf,
490 licenceOneOf: req.query.licenceOneOf,
491 languageOneOf: req.query.languageOneOf,
492 tagsOneOf: req.query.tagsOneOf,
493 tagsAllOf: req.query.tagsAllOf,
494 nsfw: buildNSFWFilter(res, req.query.nsfw),
495 filter: req.query.filter as VideoFilter,
497 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
499 }, 'filter:api.videos.list.params')
501 const resultList = await Hooks.wrapPromiseFun(
502 VideoModel.listForApi,
504 'filter:api.videos.list.result'
507 return res.json(getFormattedObjects(resultList.data, resultList.total))
510 async function removeVideo (req: express.Request, res: express.Response) {
511 const videoInstance = res.locals.videoAll
513 await sequelizeTypescript.transaction(async t => {
514 await videoInstance.destroy({ transaction: t })
517 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
518 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
520 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
522 return res.type('json')
523 .status(HttpStatusCode.NO_CONTENT_204)