]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Dissociate video file names and video uuid
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
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 { 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'
23 import {
24 DEFAULT_AUDIO_RESOLUTION,
25 MIMETYPES,
26 VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES,
28 VIDEO_LICENCES,
29 VIDEO_PRIVACIES
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'
40 import {
41 asyncMiddleware,
42 asyncRetryTransactionMiddleware,
43 authenticate,
44 checkVideoFollowConstraints,
45 commonVideosFiltersValidator,
46 optionalAuthenticate,
47 paginationValidator,
48 setDefaultPagination,
49 setDefaultVideosSort,
50 videoFileMetadataGetValidator,
51 videosAddValidator,
52 videosCustomGetValidator,
53 videosGetValidator,
54 videosRemoveValidator,
55 videosSortValidator,
56 videosUpdateValidator
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'
69
70 const auditLogger = auditLoggerFactory('videos')
71 const videosRouter = express.Router()
72
73 const reqVideoFileAdd = createReqFiles(
74 [ 'videofile', 'thumbnailfile', 'previewfile' ],
75 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
76 {
77 videofile: CONFIG.STORAGE.TMP_DIR,
78 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
79 previewfile: CONFIG.STORAGE.TMP_DIR
80 }
81 )
82 const reqVideoFileUpdate = createReqFiles(
83 [ 'thumbnailfile', 'previewfile' ],
84 MIMETYPES.IMAGE.MIMETYPE_EXT,
85 {
86 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
87 previewfile: CONFIG.STORAGE.TMP_DIR
88 }
89 )
90
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)
99
100 videosRouter.get('/categories', listVideoCategories)
101 videosRouter.get('/licences', listVideoLicences)
102 videosRouter.get('/languages', listVideoLanguages)
103 videosRouter.get('/privacies', listVideoPrivacies)
104
105 videosRouter.get('/',
106 paginationValidator,
107 videosSortValidator,
108 setDefaultVideosSort,
109 setDefaultPagination,
110 optionalAuthenticate,
111 commonVideosFiltersValidator,
112 asyncMiddleware(listVideos)
113 )
114 videosRouter.put('/:id',
115 authenticate,
116 reqVideoFileUpdate,
117 asyncMiddleware(videosUpdateValidator),
118 asyncRetryTransactionMiddleware(updateVideo)
119 )
120 videosRouter.post('/upload',
121 authenticate,
122 reqVideoFileAdd,
123 asyncMiddleware(videosAddValidator),
124 asyncRetryTransactionMiddleware(addVideo)
125 )
126
127 videosRouter.get('/:id/description',
128 asyncMiddleware(videosGetValidator),
129 asyncMiddleware(getVideoDescription)
130 )
131 videosRouter.get('/:id/metadata/:videoFileId',
132 asyncMiddleware(videoFileMetadataGetValidator),
133 asyncMiddleware(getVideoFileMetadata)
134 )
135 videosRouter.get('/:id',
136 optionalAuthenticate,
137 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
138 asyncMiddleware(checkVideoFollowConstraints),
139 asyncMiddleware(getVideo)
140 )
141 videosRouter.post('/:id/views',
142 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
143 asyncMiddleware(viewVideo)
144 )
145
146 videosRouter.delete('/:id',
147 authenticate,
148 asyncMiddleware(videosRemoveValidator),
149 asyncRetryTransactionMiddleware(removeVideo)
150 )
151
152 // ---------------------------------------------------------------------------
153
154 export {
155 videosRouter
156 }
157
158 // ---------------------------------------------------------------------------
159
160 function listVideoCategories (req: express.Request, res: express.Response) {
161 res.json(VIDEO_CATEGORIES)
162 }
163
164 function listVideoLicences (req: express.Request, res: express.Response) {
165 res.json(VIDEO_LICENCES)
166 }
167
168 function listVideoLanguages (req: express.Request, res: express.Response) {
169 res.json(VIDEO_LANGUAGES)
170 }
171
172 function listVideoPrivacies (req: express.Request, res: express.Response) {
173 res.json(VIDEO_PRIVACIES)
174 }
175
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)
182 })
183
184 const videoPhysicalFile = req.files['videofile'][0]
185 const videoInfo: VideoCreate = req.body
186
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
190
191 const video = new VideoModel(videoData) as MVideoFullLight
192 video.VideoChannel = res.locals.videoChannel
193 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
194
195 const videoFile = new VideoFileModel({
196 extname: extname(videoPhysicalFile.filename),
197 size: videoPhysicalFile.size,
198 videoStreamingPlaylistId: null,
199 metadata: await getMetadataFromFile(videoPhysicalFile.path)
200 })
201
202 if (videoFile.isAudio()) {
203 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
204 } else {
205 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
206 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
207 }
208
209 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
210
211 // Move physical file
212 const destination = getVideoFilePath(video, videoFile)
213 await move(videoPhysicalFile.path, destination)
214 // This is important in case if there is another attempt in the retry process
215 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
216 videoPhysicalFile.path = destination
217
218 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
219 video,
220 files: req.files,
221 fallback: type => generateVideoMiniature({ video, videoFile, type })
222 })
223
224 // Create the torrent file
225 await createTorrentAndSetInfoHash(video, video, videoFile)
226
227 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
228 const sequelizeOptions = { transaction: t }
229
230 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
231
232 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
233 await videoCreated.addAndSaveThumbnail(previewModel, t)
234
235 // Do not forget to add video channel information to the created video
236 videoCreated.VideoChannel = res.locals.videoChannel
237
238 videoFile.videoId = video.id
239 await videoFile.save(sequelizeOptions)
240
241 video.VideoFiles = [ videoFile ]
242
243 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
244
245 // Schedule an update in the future?
246 if (videoInfo.scheduleUpdate) {
247 await ScheduleVideoUpdateModel.create({
248 videoId: video.id,
249 updateAt: videoInfo.scheduleUpdate.updateAt,
250 privacy: videoInfo.scheduleUpdate.privacy || null
251 }, { transaction: t })
252 }
253
254 await autoBlacklistVideoIfNeeded({
255 video,
256 user: res.locals.oauth.token.User,
257 isRemote: false,
258 isNew: true,
259 transaction: t
260 })
261 await federateVideoIfNeeded(video, true, t)
262
263 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
264 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
265
266 return { videoCreated }
267 })
268
269 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
270
271 if (video.state === VideoState.TO_TRANSCODE) {
272 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
273 }
274
275 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
276
277 return res.json({
278 video: {
279 id: videoCreated.id,
280 uuid: videoCreated.uuid
281 }
282 })
283 }
284
285 async function updateVideo (req: express.Request, res: express.Response) {
286 const videoInstance = res.locals.videoAll
287 const videoFieldsSave = videoInstance.toJSON()
288 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
289 const videoInfoToUpdate: VideoUpdate = req.body
290
291 const wasConfidentialVideo = videoInstance.isConfidential()
292 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
293
294 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
295 video: videoInstance,
296 files: req.files,
297 fallback: () => Promise.resolve(undefined),
298 automaticallyGenerated: false
299 })
300
301 try {
302 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
303 const sequelizeOptions = { transaction: t }
304 const oldVideoChannel = videoInstance.VideoChannel
305
306 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
307 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
308 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
309 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
310 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
311 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
312 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
313 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
314 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
315 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
316
317 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
318 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
319 }
320
321 let isNewVideo = false
322 if (videoInfoToUpdate.privacy !== undefined) {
323 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
324
325 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
326 videoInstance.setPrivacy(newPrivacy)
327
328 // Unfederate the video if the new privacy is not compatible with federation
329 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
330 await VideoModel.sendDelete(videoInstance, { transaction: t })
331 }
332 }
333
334 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
335
336 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
337 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
338
339 // Video tags update?
340 await setVideoTags({
341 video: videoInstanceUpdated,
342 tags: videoInfoToUpdate.tags,
343 transaction: t,
344 defaultValue: videoInstanceUpdated.Tags
345 })
346
347 // Video channel update?
348 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
349 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
350 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
351
352 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
353 }
354
355 // Schedule an update in the future?
356 if (videoInfoToUpdate.scheduleUpdate) {
357 await ScheduleVideoUpdateModel.upsert({
358 videoId: videoInstanceUpdated.id,
359 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
360 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
361 }, { transaction: t })
362 } else if (videoInfoToUpdate.scheduleUpdate === null) {
363 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
364 }
365
366 await autoBlacklistVideoIfNeeded({
367 video: videoInstanceUpdated,
368 user: res.locals.oauth.token.User,
369 isRemote: false,
370 isNew: false,
371 transaction: t
372 })
373
374 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
375
376 auditLogger.update(
377 getAuditIdFromRes(res),
378 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
379 oldVideoAuditView
380 )
381 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
382
383 return videoInstanceUpdated
384 })
385
386 if (wasConfidentialVideo) {
387 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
388 }
389
390 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
391 } catch (err) {
392 // Force fields we want to update
393 // If the transaction is retried, sequelize will think the object has not changed
394 // So it will skip the SQL request, even if the last one was ROLLBACKed!
395 resetSequelizeInstance(videoInstance, videoFieldsSave)
396
397 throw err
398 }
399
400 return res.type('json')
401 .status(HttpStatusCode.NO_CONTENT_204)
402 .end()
403 }
404
405 async function getVideo (req: express.Request, res: express.Response) {
406 // We need more attributes
407 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
408
409 const video = await Hooks.wrapPromiseFun(
410 VideoModel.loadForGetAPI,
411 { id: res.locals.onlyVideoWithRights.id, userId },
412 'filter:api.video.get.result'
413 )
414
415 if (video.isOutdated()) {
416 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
417 }
418
419 return res.json(video.toFormattedDetailsJSON())
420 }
421
422 async function viewVideo (req: express.Request, res: express.Response) {
423 const immutableVideoAttrs = res.locals.onlyImmutableVideo
424
425 const ip = req.ip
426 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
427 if (exists) {
428 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
429 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
430 }
431
432 const video = await VideoModel.load(immutableVideoAttrs.id)
433
434 const promises: Promise<any>[] = [
435 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
436 ]
437
438 let federateView = true
439
440 // Increment our live manager
441 if (video.isLive && video.isOwned()) {
442 LiveManager.Instance.addViewTo(video.id)
443
444 // Views of our local live will be sent by our live manager
445 federateView = false
446 }
447
448 // Increment our video views cache counter
449 if (!video.isLive) {
450 promises.push(Redis.Instance.addVideoView(video.id))
451 }
452
453 if (federateView) {
454 const serverActor = await getServerActor()
455 promises.push(sendView(serverActor, video, undefined))
456 }
457
458 await Promise.all(promises)
459
460 Hooks.runAction('action:api.video.viewed', { video, ip })
461
462 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
463 }
464
465 async function getVideoDescription (req: express.Request, res: express.Response) {
466 const videoInstance = res.locals.videoAll
467 let description = ''
468
469 if (videoInstance.isOwned()) {
470 description = videoInstance.description
471 } else {
472 description = await fetchRemoteVideoDescription(videoInstance)
473 }
474
475 return res.json({ description })
476 }
477
478 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
479 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
480
481 return res.json(videoFile.metadata)
482 }
483
484 async function listVideos (req: express.Request, res: express.Response) {
485 const countVideos = getCountVideos(req)
486
487 const apiOptions = await Hooks.wrapObject({
488 start: req.query.start,
489 count: req.query.count,
490 sort: req.query.sort,
491 includeLocalVideos: true,
492 categoryOneOf: req.query.categoryOneOf,
493 licenceOneOf: req.query.licenceOneOf,
494 languageOneOf: req.query.languageOneOf,
495 tagsOneOf: req.query.tagsOneOf,
496 tagsAllOf: req.query.tagsAllOf,
497 nsfw: buildNSFWFilter(res, req.query.nsfw),
498 filter: req.query.filter as VideoFilter,
499 withFiles: false,
500 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
501 countVideos
502 }, 'filter:api.videos.list.params')
503
504 const resultList = await Hooks.wrapPromiseFun(
505 VideoModel.listForApi,
506 apiOptions,
507 'filter:api.videos.list.result'
508 )
509
510 return res.json(getFormattedObjects(resultList.data, resultList.total))
511 }
512
513 async function removeVideo (req: express.Request, res: express.Response) {
514 const videoInstance = res.locals.videoAll
515
516 await sequelizeTypescript.transaction(async t => {
517 await videoInstance.destroy({ transaction: t })
518 })
519
520 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
521 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
522
523 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
524
525 return res.type('json')
526 .status(HttpStatusCode.NO_CONTENT_204)
527 .end()
528 }