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 { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
6 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7 import { changeVideoChannelShare } from '@server/lib/activitypub/share'
8 import { getVideoActivityPubUrl } from '@server/lib/activitypub/url'
9 import { 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 { MVideoDetails, MVideoFullLight } from '@server/types/models'
13 import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
14 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
15 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
16 import { resetSequelizeInstance } from '../../../helpers/database-utils'
17 import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils'
18 import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
19 import { logger } from '../../../helpers/logger'
20 import { getFormattedObjects } from '../../../helpers/utils'
21 import { CONFIG } from '../../../initializers/config'
23 DEFAULT_AUDIO_RESOLUTION,
29 } from '../../../initializers/constants'
30 import { sequelizeTypescript } from '../../../initializers/database'
31 import { sendView } from '../../../lib/activitypub/send/send-view'
32 import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
33 import { JobQueue } from '../../../lib/job-queue'
34 import { Notifier } from '../../../lib/notifier'
35 import { Hooks } from '../../../lib/plugins/hooks'
36 import { Redis } from '../../../lib/redis'
37 import { generateVideoMiniature } from '../../../lib/thumbnail'
38 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
41 asyncRetryTransactionMiddleware,
43 checkVideoFollowConstraints,
44 commonVideosFiltersValidator,
49 videoFileMetadataGetValidator,
51 videosCustomGetValidator,
53 videosRemoveValidator,
56 } from '../../../middlewares'
57 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
58 import { VideoModel } from '../../../models/video/video'
59 import { VideoFileModel } from '../../../models/video/video-file'
60 import { abuseVideoRouter } from './abuse'
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('/', abuseVideoRouter)
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 // Processing the video could be long
179 // Set timeout to 10 minutes
180 req.setTimeout(1000 * 60 * 10, () => {
181 logger.error('Upload video has timed out.')
182 return res.sendStatus(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.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
195 const videoFile = new VideoFileModel({
196 extname: extname(videoPhysicalFile.filename),
197 size: videoPhysicalFile.size,
198 videoStreamingPlaylistId: null,
199 metadata: await getMetadataFromFile<any>(videoPhysicalFile.path)
202 if (videoFile.isAudio()) {
203 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
205 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
206 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
209 // Move physical file
210 const destination = getVideoFilePath(video, videoFile)
211 await move(videoPhysicalFile.path, destination)
212 // This is important in case if there is another attempt in the retry process
213 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
214 videoPhysicalFile.path = destination
216 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
219 fallback: type => generateVideoMiniature(video, videoFile, type)
222 // Create the torrent file
223 await createTorrentAndSetInfoHash(video, videoFile)
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,
259 await federateVideoIfNeeded(video, true, t)
261 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
262 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
264 return { videoCreated }
267 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
269 if (video.state === VideoState.TO_TRANSCODE) {
270 await addOptimizeOrMergeAudioJob(videoCreated, videoFile)
273 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
278 uuid: videoCreated.uuid
283 async function updateVideo (req: express.Request, res: express.Response) {
284 const videoInstance = res.locals.videoAll
285 const videoFieldsSave = videoInstance.toJSON()
286 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
287 const videoInfoToUpdate: VideoUpdate = req.body
289 const wasConfidentialVideo = videoInstance.isConfidential()
290 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
292 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
293 video: videoInstance,
295 fallback: () => Promise.resolve(undefined),
296 automaticallyGenerated: false
300 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
301 const sequelizeOptions = { transaction: t }
302 const oldVideoChannel = videoInstance.VideoChannel
304 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
305 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
306 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
307 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
308 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
309 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
310 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
311 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
312 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
313 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
315 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
316 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
319 let isNewVideo = false
320 if (videoInfoToUpdate.privacy !== undefined) {
321 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
323 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
324 videoInstance.setPrivacy(newPrivacy)
326 // Unfederate the video if the new privacy is not compatible with federation
327 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
328 await VideoModel.sendDelete(videoInstance, { transaction: t })
332 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
334 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
335 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
337 // Video tags update?
339 video: videoInstanceUpdated,
340 tags: videoInfoToUpdate.tags,
342 defaultValue: videoInstanceUpdated.Tags
345 // Video channel update?
346 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
347 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
348 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
350 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
353 // Schedule an update in the future?
354 if (videoInfoToUpdate.scheduleUpdate) {
355 await ScheduleVideoUpdateModel.upsert({
356 videoId: videoInstanceUpdated.id,
357 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
358 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
359 }, { transaction: t })
360 } else if (videoInfoToUpdate.scheduleUpdate === null) {
361 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
364 await autoBlacklistVideoIfNeeded({
365 video: videoInstanceUpdated,
366 user: res.locals.oauth.token.User,
372 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
375 getAuditIdFromRes(res),
376 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
379 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
381 return videoInstanceUpdated
384 if (wasConfidentialVideo) {
385 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
388 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
390 // Force fields we want to update
391 // If the transaction is retried, sequelize will think the object has not changed
392 // So it will skip the SQL request, even if the last one was ROLLBACKed!
393 resetSequelizeInstance(videoInstance, videoFieldsSave)
398 return res.type('json').status(204).end()
401 async function getVideo (req: express.Request, res: express.Response) {
402 // We need more attributes
403 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
405 const video = await Hooks.wrapPromiseFun(
406 VideoModel.loadForGetAPI,
407 { id: res.locals.onlyVideoWithRights.id, userId },
408 'filter:api.video.get.result'
411 if (video.isOutdated()) {
412 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
415 return res.json(video.toFormattedDetailsJSON())
418 async function viewVideo (req: express.Request, res: express.Response) {
419 const videoInstance = res.locals.onlyImmutableVideo
422 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
424 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
425 return res.status(204).end()
429 Redis.Instance.addVideoView(videoInstance.id),
430 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
433 const serverActor = await getServerActor()
434 await sendView(serverActor, videoInstance, undefined)
436 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
438 return res.status(204).end()
441 async function getVideoDescription (req: express.Request, res: express.Response) {
442 const videoInstance = res.locals.videoAll
445 if (videoInstance.isOwned()) {
446 description = videoInstance.description
448 description = await fetchRemoteVideoDescription(videoInstance)
451 return res.json({ description })
454 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
455 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
457 return res.json(videoFile.metadata)
460 async function listVideos (req: express.Request, res: express.Response) {
461 const countVideos = getCountVideos(req)
463 const apiOptions = await Hooks.wrapObject({
464 start: req.query.start,
465 count: req.query.count,
466 sort: req.query.sort,
467 includeLocalVideos: true,
468 categoryOneOf: req.query.categoryOneOf,
469 licenceOneOf: req.query.licenceOneOf,
470 languageOneOf: req.query.languageOneOf,
471 tagsOneOf: req.query.tagsOneOf,
472 tagsAllOf: req.query.tagsAllOf,
473 nsfw: buildNSFWFilter(res, req.query.nsfw),
474 filter: req.query.filter as VideoFilter,
476 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
478 }, 'filter:api.videos.list.params')
480 const resultList = await Hooks.wrapPromiseFun(
481 VideoModel.listForApi,
483 'filter:api.videos.list.result'
486 return res.json(getFormattedObjects(resultList.data, resultList.total))
489 async function removeVideo (req: express.Request, res: express.Response) {
490 const videoInstance = res.locals.videoAll
492 await sequelizeTypescript.transaction(async t => {
493 await videoInstance.destroy({ transaction: t })
496 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
497 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
499 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
501 return res.type('json').status(204).end()