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