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 { TagModel } from '../../../models/video/tag'
59 import { VideoModel } from '../../../models/video/video'
60 import { VideoFileModel } from '../../../models/video/video-file'
61 import { abuseVideoRouter } from './abuse'
62 import { blacklistRouter } from './blacklist'
63 import { videoCaptionsRouter } from './captions'
64 import { videoCommentRouter } from './comment'
65 import { videoImportsRouter } from './import'
66 import { liveRouter } from './live'
67 import { ownershipVideoRouter } from './ownership'
68 import { rateVideoRouter } from './rate'
69 import { watchingRouter } from './watching'
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('/', abuseVideoRouter)
93 videosRouter.use('/', blacklistRouter)
94 videosRouter.use('/', rateVideoRouter)
95 videosRouter.use('/', videoCommentRouter)
96 videosRouter.use('/', videoCaptionsRouter)
97 videosRouter.use('/', videoImportsRouter)
98 videosRouter.use('/', ownershipVideoRouter)
99 videosRouter.use('/', watchingRouter)
100 videosRouter.use('/', liveRouter)
102 videosRouter.get('/categories', listVideoCategories)
103 videosRouter.get('/licences', listVideoLicences)
104 videosRouter.get('/languages', listVideoLanguages)
105 videosRouter.get('/privacies', listVideoPrivacies)
107 videosRouter.get('/',
110 setDefaultVideosSort,
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 const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
190 videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
191 videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware
193 const video = new VideoModel(videoData) as MVideoDetails
194 video.url = getVideoActivityPubUrl(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<any>(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 // Move physical file
211 const destination = getVideoFilePath(video, videoFile)
212 await move(videoPhysicalFile.path, destination)
213 // This is important in case if there is another attempt in the retry process
214 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
215 videoPhysicalFile.path = destination
217 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
220 fallback: type => generateVideoMiniature(video, videoFile, type)
223 // Create the torrent file
224 await createTorrentAndSetInfoHash(video, videoFile)
226 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
227 const sequelizeOptions = { transaction: t }
229 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
231 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
232 await videoCreated.addAndSaveThumbnail(previewModel, t)
234 // Do not forget to add video channel information to the created video
235 videoCreated.VideoChannel = res.locals.videoChannel
237 videoFile.videoId = video.id
238 await videoFile.save(sequelizeOptions)
240 video.VideoFiles = [ videoFile ]
242 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
244 // Schedule an update in the future?
245 if (videoInfo.scheduleUpdate) {
246 await ScheduleVideoUpdateModel.create({
248 updateAt: videoInfo.scheduleUpdate.updateAt,
249 privacy: videoInfo.scheduleUpdate.privacy || null
250 }, { transaction: t })
253 await autoBlacklistVideoIfNeeded({
255 user: res.locals.oauth.token.User,
260 await federateVideoIfNeeded(video, true, t)
262 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
263 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
265 return { videoCreated }
268 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
270 if (video.state === VideoState.TO_TRANSCODE) {
271 await addOptimizeOrMergeAudioJob(videoCreated, videoFile)
274 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
279 uuid: videoCreated.uuid
284 async function updateVideo (req: express.Request, res: express.Response) {
285 const videoInstance = res.locals.videoAll
286 const videoFieldsSave = videoInstance.toJSON()
287 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
288 const videoInfoToUpdate: VideoUpdate = req.body
290 const wasConfidentialVideo = videoInstance.isConfidential()
291 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
293 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
294 video: videoInstance,
296 fallback: () => Promise.resolve(undefined),
297 automaticallyGenerated: false
301 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
302 const sequelizeOptions = { transaction: t }
303 const oldVideoChannel = videoInstance.VideoChannel
305 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
306 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
307 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
308 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
309 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
310 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
311 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
312 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
313 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
314 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
316 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
317 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
320 let isNewVideo = false
321 if (videoInfoToUpdate.privacy !== undefined) {
322 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
324 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
325 videoInstance.setPrivacy(newPrivacy)
327 // Unfederate the video if the new privacy is not compatible with federation
328 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
329 await VideoModel.sendDelete(videoInstance, { transaction: t })
333 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
335 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
336 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
338 // Video tags update?
340 video: videoInstanceUpdated,
341 tags: videoInfoToUpdate.tags,
343 defaultValue: videoInstanceUpdated.Tags
346 // Video channel update?
347 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
348 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
349 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
351 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
354 // Schedule an update in the future?
355 if (videoInfoToUpdate.scheduleUpdate) {
356 await ScheduleVideoUpdateModel.upsert({
357 videoId: videoInstanceUpdated.id,
358 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
359 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
360 }, { transaction: t })
361 } else if (videoInfoToUpdate.scheduleUpdate === null) {
362 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
365 await autoBlacklistVideoIfNeeded({
366 video: videoInstanceUpdated,
367 user: res.locals.oauth.token.User,
373 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
376 getAuditIdFromRes(res),
377 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
380 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
382 return videoInstanceUpdated
385 if (wasConfidentialVideo) {
386 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
389 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
391 // Force fields we want to update
392 // If the transaction is retried, sequelize will think the object has not changed
393 // So it will skip the SQL request, even if the last one was ROLLBACKed!
394 resetSequelizeInstance(videoInstance, videoFieldsSave)
399 return res.type('json').status(204).end()
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 videoInstance = res.locals.onlyImmutableVideo
423 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
425 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
426 return res.status(204).end()
430 Redis.Instance.addVideoView(videoInstance.id),
431 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
434 const serverActor = await getServerActor()
435 await sendView(serverActor, videoInstance, undefined)
437 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
439 return res.status(204).end()
442 async function getVideoDescription (req: express.Request, res: express.Response) {
443 const videoInstance = res.locals.videoAll
446 if (videoInstance.isOwned()) {
447 description = videoInstance.description
449 description = await fetchRemoteVideoDescription(videoInstance)
452 return res.json({ description })
455 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
456 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
458 return res.json(videoFile.metadata)
461 async function listVideos (req: express.Request, res: express.Response) {
462 const countVideos = getCountVideos(req)
464 const apiOptions = await Hooks.wrapObject({
465 start: req.query.start,
466 count: req.query.count,
467 sort: req.query.sort,
468 includeLocalVideos: true,
469 categoryOneOf: req.query.categoryOneOf,
470 licenceOneOf: req.query.licenceOneOf,
471 languageOneOf: req.query.languageOneOf,
472 tagsOneOf: req.query.tagsOneOf,
473 tagsAllOf: req.query.tagsAllOf,
474 nsfw: buildNSFWFilter(res, req.query.nsfw),
475 filter: req.query.filter as VideoFilter,
477 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
479 }, 'filter:api.videos.list.params')
481 const resultList = await Hooks.wrapPromiseFun(
482 VideoModel.listForApi,
484 'filter:api.videos.list.result'
487 return res.json(getFormattedObjects(resultList.data, resultList.total))
490 async function removeVideo (req: express.Request, res: express.Response) {
491 const videoInstance = res.locals.videoAll
493 await sequelizeTypescript.transaction(async t => {
494 await videoInstance.destroy({ transaction: t })
497 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
498 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
500 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
502 return res.type('json').status(204).end()