]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Handle live federation
[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 { 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'
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 { 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 { 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'
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('/', 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)
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 // 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)
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 MVideoDetails
193 video.url = getVideoActivityPubUrl(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<any>(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').status(204).end()
399 }
400
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
404
405 const video = await Hooks.wrapPromiseFun(
406 VideoModel.loadForGetAPI,
407 { id: res.locals.onlyVideoWithRights.id, userId },
408 'filter:api.video.get.result'
409 )
410
411 if (video.isOutdated()) {
412 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
413 }
414
415 return res.json(video.toFormattedDetailsJSON())
416 }
417
418 async function viewVideo (req: express.Request, res: express.Response) {
419 const videoInstance = res.locals.onlyImmutableVideo
420
421 const ip = req.ip
422 const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
423 if (exists) {
424 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
425 return res.status(204).end()
426 }
427
428 await Promise.all([
429 Redis.Instance.addVideoView(videoInstance.id),
430 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
431 ])
432
433 const serverActor = await getServerActor()
434 await sendView(serverActor, videoInstance, undefined)
435
436 Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
437
438 return res.status(204).end()
439 }
440
441 async function getVideoDescription (req: express.Request, res: express.Response) {
442 const videoInstance = res.locals.videoAll
443 let description = ''
444
445 if (videoInstance.isOwned()) {
446 description = videoInstance.description
447 } else {
448 description = await fetchRemoteVideoDescription(videoInstance)
449 }
450
451 return res.json({ description })
452 }
453
454 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
455 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
456
457 return res.json(videoFile.metadata)
458 }
459
460 async function listVideos (req: express.Request, res: express.Response) {
461 const countVideos = getCountVideos(req)
462
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,
475 withFiles: false,
476 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
477 countVideos
478 }, 'filter:api.videos.list.params')
479
480 const resultList = await Hooks.wrapPromiseFun(
481 VideoModel.listForApi,
482 apiOptions,
483 'filter:api.videos.list.result'
484 )
485
486 return res.json(getFormattedObjects(resultList.data, resultList.total))
487 }
488
489 async function removeVideo (req: express.Request, res: express.Response) {
490 const videoInstance = res.locals.videoAll
491
492 await sequelizeTypescript.transaction(async t => {
493 await videoInstance.destroy({ transaction: t })
494 })
495
496 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
497 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
498
499 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
500
501 return res.type('json').status(204).end()
502 }