]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
advertise live streaming as a feature in readme
[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 { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
9 import { LiveManager } from '@server/lib/live-manager'
10 import { buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
11 import { getVideoFilePath } from '@server/lib/video-paths'
12 import { getServerActor } from '@server/models/application/application'
13 import { MVideoFullLight } from '@server/types/models'
14 import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared'
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 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
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('/', 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)
100
101 videosRouter.get('/categories', listVideoCategories)
102 videosRouter.get('/licences', listVideoLicences)
103 videosRouter.get('/languages', listVideoLanguages)
104 videosRouter.get('/privacies', listVideoPrivacies)
105
106 videosRouter.get('/',
107 paginationValidator,
108 videosSortValidator,
109 setDefaultVideosSort,
110 setDefaultPagination,
111 optionalAuthenticate,
112 commonVideosFiltersValidator,
113 asyncMiddleware(listVideos)
114 )
115 videosRouter.put('/:id',
116 authenticate,
117 reqVideoFileUpdate,
118 asyncMiddleware(videosUpdateValidator),
119 asyncRetryTransactionMiddleware(updateVideo)
120 )
121 videosRouter.post('/upload',
122 authenticate,
123 reqVideoFileAdd,
124 asyncMiddleware(videosAddValidator),
125 asyncRetryTransactionMiddleware(addVideo)
126 )
127
128 videosRouter.get('/:id/description',
129 asyncMiddleware(videosGetValidator),
130 asyncMiddleware(getVideoDescription)
131 )
132 videosRouter.get('/:id/metadata/:videoFileId',
133 asyncMiddleware(videoFileMetadataGetValidator),
134 asyncMiddleware(getVideoFileMetadata)
135 )
136 videosRouter.get('/:id',
137 optionalAuthenticate,
138 asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
139 asyncMiddleware(checkVideoFollowConstraints),
140 asyncMiddleware(getVideo)
141 )
142 videosRouter.post('/:id/views',
143 asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')),
144 asyncMiddleware(viewVideo)
145 )
146
147 videosRouter.delete('/:id',
148 authenticate,
149 asyncMiddleware(videosRemoveValidator),
150 asyncRetryTransactionMiddleware(removeVideo)
151 )
152
153 // ---------------------------------------------------------------------------
154
155 export {
156 videosRouter
157 }
158
159 // ---------------------------------------------------------------------------
160
161 function listVideoCategories (req: express.Request, res: express.Response) {
162 res.json(VIDEO_CATEGORIES)
163 }
164
165 function listVideoLicences (req: express.Request, res: express.Response) {
166 res.json(VIDEO_LICENCES)
167 }
168
169 function listVideoLanguages (req: express.Request, res: express.Response) {
170 res.json(VIDEO_LANGUAGES)
171 }
172
173 function listVideoPrivacies (req: express.Request, res: express.Response) {
174 res.json(VIDEO_PRIVACIES)
175 }
176
177 async function addVideo (req: express.Request, res: express.Response) {
178 // Uploading the video could be long
179 // Set timeout to 10 minutes, as Express's default is 2 minutes
180 req.setTimeout(1000 * 60 * 10, () => {
181 logger.error('Upload video has timed out.')
182 return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
183 })
184
185 const videoPhysicalFile = req.files['videofile'][0]
186 const videoInfo: VideoCreate = req.body
187
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
191
192 const video = new VideoModel(videoData) as MVideoFullLight
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 // 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
215
216 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
217 video,
218 files: req.files,
219 fallback: type => generateVideoMiniature(video, videoFile, type)
220 })
221
222 // Create the torrent file
223 await createTorrentAndSetInfoHash(video, videoFile)
224
225 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
226 const sequelizeOptions = { transaction: t }
227
228 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
229
230 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
231 await videoCreated.addAndSaveThumbnail(previewModel, t)
232
233 // Do not forget to add video channel information to the created video
234 videoCreated.VideoChannel = res.locals.videoChannel
235
236 videoFile.videoId = video.id
237 await videoFile.save(sequelizeOptions)
238
239 video.VideoFiles = [ videoFile ]
240
241 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
242
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
246 videoId: video.id,
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
250 }
251
252 await autoBlacklistVideoIfNeeded({
253 video,
254 user: res.locals.oauth.token.User,
255 isRemote: false,
256 isNew: true,
257 transaction: t
258 })
259 await federateVideoIfNeeded(video, true, t)
260
261 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
262 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
263
264 return { videoCreated }
265 })
266
267 Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
268
269 if (video.state === VideoState.TO_TRANSCODE) {
270 await addOptimizeOrMergeAudioJob(videoCreated, videoFile)
271 }
272
273 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
274
275 return res.json({
276 video: {
277 id: videoCreated.id,
278 uuid: videoCreated.uuid
279 }
280 })
281 }
282
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
288
289 const wasConfidentialVideo = videoInstance.isConfidential()
290 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
291
292 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
293 video: videoInstance,
294 files: req.files,
295 fallback: () => Promise.resolve(undefined),
296 automaticallyGenerated: false
297 })
298
299 try {
300 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
301 const sequelizeOptions = { transaction: t }
302 const oldVideoChannel = videoInstance.VideoChannel
303
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
314
315 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
316 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
317 }
318
319 let isNewVideo = false
320 if (videoInfoToUpdate.privacy !== undefined) {
321 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
322
323 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
324 videoInstance.setPrivacy(newPrivacy)
325
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 })
329 }
330 }
331
332 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
333
334 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
335 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
336
337 // Video tags update?
338 await setVideoTags({
339 video: videoInstanceUpdated,
340 tags: videoInfoToUpdate.tags,
341 transaction: t,
342 defaultValue: videoInstanceUpdated.Tags
343 })
344
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
349
350 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
351 }
352
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)
362 }
363
364 await autoBlacklistVideoIfNeeded({
365 video: videoInstanceUpdated,
366 user: res.locals.oauth.token.User,
367 isRemote: false,
368 isNew: false,
369 transaction: t
370 })
371
372 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
373
374 auditLogger.update(
375 getAuditIdFromRes(res),
376 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
377 oldVideoAuditView
378 )
379 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
380
381 return videoInstanceUpdated
382 })
383
384 if (wasConfidentialVideo) {
385 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
386 }
387
388 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
389 } catch (err) {
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)
394
395 throw err
396 }
397
398 return res.type('json')
399 .status(HttpStatusCode.NO_CONTENT_204)
400 .end()
401 }
402
403 async function getVideo (req: express.Request, res: express.Response) {
404 // We need more attributes
405 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
406
407 const video = await Hooks.wrapPromiseFun(
408 VideoModel.loadForGetAPI,
409 { id: res.locals.onlyVideoWithRights.id, userId },
410 'filter:api.video.get.result'
411 )
412
413 if (video.isOutdated()) {
414 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
415 }
416
417 return res.json(video.toFormattedDetailsJSON())
418 }
419
420 async function viewVideo (req: express.Request, res: express.Response) {
421 const immutableVideoAttrs = res.locals.onlyImmutableVideo
422
423 const ip = req.ip
424 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
425 if (exists) {
426 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
427 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
428 }
429
430 const video = await VideoModel.load(immutableVideoAttrs.id)
431
432 const promises: Promise<any>[] = [
433 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
434 ]
435
436 let federateView = true
437
438 // Increment our live manager
439 if (video.isLive && video.isOwned()) {
440 LiveManager.Instance.addViewTo(video.id)
441
442 // Views of our local live will be sent by our live manager
443 federateView = false
444 }
445
446 // Increment our video views cache counter
447 if (!video.isLive) {
448 promises.push(Redis.Instance.addVideoView(video.id))
449 }
450
451 if (federateView) {
452 const serverActor = await getServerActor()
453 promises.push(sendView(serverActor, video, undefined))
454 }
455
456 await Promise.all(promises)
457
458 Hooks.runAction('action:api.video.viewed', { video, ip })
459
460 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
461 }
462
463 async function getVideoDescription (req: express.Request, res: express.Response) {
464 const videoInstance = res.locals.videoAll
465 let description = ''
466
467 if (videoInstance.isOwned()) {
468 description = videoInstance.description
469 } else {
470 description = await fetchRemoteVideoDescription(videoInstance)
471 }
472
473 return res.json({ description })
474 }
475
476 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
477 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
478
479 return res.json(videoFile.metadata)
480 }
481
482 async function listVideos (req: express.Request, res: express.Response) {
483 const countVideos = getCountVideos(req)
484
485 const apiOptions = await Hooks.wrapObject({
486 start: req.query.start,
487 count: req.query.count,
488 sort: req.query.sort,
489 includeLocalVideos: true,
490 categoryOneOf: req.query.categoryOneOf,
491 licenceOneOf: req.query.licenceOneOf,
492 languageOneOf: req.query.languageOneOf,
493 tagsOneOf: req.query.tagsOneOf,
494 tagsAllOf: req.query.tagsAllOf,
495 nsfw: buildNSFWFilter(res, req.query.nsfw),
496 filter: req.query.filter as VideoFilter,
497 withFiles: false,
498 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
499 countVideos
500 }, 'filter:api.videos.list.params')
501
502 const resultList = await Hooks.wrapPromiseFun(
503 VideoModel.listForApi,
504 apiOptions,
505 'filter:api.videos.list.result'
506 )
507
508 return res.json(getFormattedObjects(resultList.data, resultList.total))
509 }
510
511 async function removeVideo (req: express.Request, res: express.Response) {
512 const videoInstance = res.locals.videoAll
513
514 await sequelizeTypescript.transaction(async t => {
515 await videoInstance.destroy({ transaction: t })
516 })
517
518 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
519 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
520
521 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
522
523 return res.type('json')
524 .status(HttpStatusCode.NO_CONTENT_204)
525 .end()
526 }