]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Fix notification scrollbar color
[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 { MVideo, MVideoFile, 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, retryTransactionWrapper } 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, loggerTagsFactory } 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 lTags = loggerTagsFactory('api', 'video')
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.VideoChannel = res.locals.videoChannel
194 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
195
196 const videoFile = new VideoFileModel({
197 extname: extname(videoPhysicalFile.filename),
198 size: videoPhysicalFile.size,
199 videoStreamingPlaylistId: null,
200 metadata: await getMetadataFromFile(videoPhysicalFile.path)
201 })
202
203 if (videoFile.isAudio()) {
204 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
205 } else {
206 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
207 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
208 }
209
210 videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname)
211
212 // Move physical file
213 const destination = getVideoFilePath(video, videoFile)
214 await move(videoPhysicalFile.path, destination)
215 // This is important in case if there is another attempt in the retry process
216 videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
217 videoPhysicalFile.path = destination
218
219 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
220 video,
221 files: req.files,
222 fallback: type => generateVideoMiniature({ video, videoFile, type })
223 })
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
260 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
261 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
262
263 return { videoCreated }
264 })
265
266 // Create the torrent file in async way because it could be long
267 createTorrentAndSetInfoHashAsync(video, videoFile)
268 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
269 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
270 .then(refreshedVideo => {
271 if (!refreshedVideo) return
272
273 // Only federate and notify after the torrent creation
274 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
275
276 return retryTransactionWrapper(() => {
277 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
278 })
279 })
280 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
281
282 if (video.state === VideoState.TO_TRANSCODE) {
283 await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User)
284 }
285
286 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
287
288 return res.json({
289 video: {
290 id: videoCreated.id,
291 uuid: videoCreated.uuid
292 }
293 })
294 }
295
296 async function updateVideo (req: express.Request, res: express.Response) {
297 const videoInstance = res.locals.videoAll
298 const videoFieldsSave = videoInstance.toJSON()
299 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
300 const videoInfoToUpdate: VideoUpdate = req.body
301
302 const wasConfidentialVideo = videoInstance.isConfidential()
303 const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
304
305 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
306 video: videoInstance,
307 files: req.files,
308 fallback: () => Promise.resolve(undefined),
309 automaticallyGenerated: false
310 })
311
312 try {
313 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
314 const sequelizeOptions = { transaction: t }
315 const oldVideoChannel = videoInstance.VideoChannel
316
317 if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
318 if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
319 if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
320 if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
321 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
322 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
323 if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
324 if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
325 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
326 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
327
328 if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
329 videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
330 }
331
332 let isNewVideo = false
333 if (videoInfoToUpdate.privacy !== undefined) {
334 isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
335
336 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
337 videoInstance.setPrivacy(newPrivacy)
338
339 // Unfederate the video if the new privacy is not compatible with federation
340 if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
341 await VideoModel.sendDelete(videoInstance, { transaction: t })
342 }
343 }
344
345 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
346
347 if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
348 if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
349
350 // Video tags update?
351 if (videoInfoToUpdate.tags !== undefined) {
352 await setVideoTags({
353 video: videoInstanceUpdated,
354 tags: videoInfoToUpdate.tags,
355 transaction: t
356 })
357 }
358
359 // Video channel update?
360 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
361 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
362 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
363
364 if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
365 }
366
367 // Schedule an update in the future?
368 if (videoInfoToUpdate.scheduleUpdate) {
369 await ScheduleVideoUpdateModel.upsert({
370 videoId: videoInstanceUpdated.id,
371 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
372 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
373 }, { transaction: t })
374 } else if (videoInfoToUpdate.scheduleUpdate === null) {
375 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
376 }
377
378 await autoBlacklistVideoIfNeeded({
379 video: videoInstanceUpdated,
380 user: res.locals.oauth.token.User,
381 isRemote: false,
382 isNew: false,
383 transaction: t
384 })
385
386 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
387
388 auditLogger.update(
389 getAuditIdFromRes(res),
390 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
391 oldVideoAuditView
392 )
393 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid))
394
395 return videoInstanceUpdated
396 })
397
398 if (wasConfidentialVideo) {
399 Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
400 }
401
402 Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body })
403 } catch (err) {
404 // Force fields we want to update
405 // If the transaction is retried, sequelize will think the object has not changed
406 // So it will skip the SQL request, even if the last one was ROLLBACKed!
407 resetSequelizeInstance(videoInstance, videoFieldsSave)
408
409 throw err
410 }
411
412 return res.type('json')
413 .status(HttpStatusCode.NO_CONTENT_204)
414 .end()
415 }
416
417 async function getVideo (req: express.Request, res: express.Response) {
418 // We need more attributes
419 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
420
421 const video = await Hooks.wrapPromiseFun(
422 VideoModel.loadForGetAPI,
423 { id: res.locals.onlyVideoWithRights.id, userId },
424 'filter:api.video.get.result'
425 )
426
427 if (video.isOutdated()) {
428 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
429 }
430
431 return res.json(video.toFormattedDetailsJSON())
432 }
433
434 async function viewVideo (req: express.Request, res: express.Response) {
435 const immutableVideoAttrs = res.locals.onlyImmutableVideo
436
437 const ip = req.ip
438 const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
439 if (exists) {
440 logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid)
441 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
442 }
443
444 const video = await VideoModel.load(immutableVideoAttrs.id)
445
446 const promises: Promise<any>[] = [
447 Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive)
448 ]
449
450 let federateView = true
451
452 // Increment our live manager
453 if (video.isLive && video.isOwned()) {
454 LiveManager.Instance.addViewTo(video.id)
455
456 // Views of our local live will be sent by our live manager
457 federateView = false
458 }
459
460 // Increment our video views cache counter
461 if (!video.isLive) {
462 promises.push(Redis.Instance.addVideoView(video.id))
463 }
464
465 if (federateView) {
466 const serverActor = await getServerActor()
467 promises.push(sendView(serverActor, video, undefined))
468 }
469
470 await Promise.all(promises)
471
472 Hooks.runAction('action:api.video.viewed', { video, ip })
473
474 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
475 }
476
477 async function getVideoDescription (req: express.Request, res: express.Response) {
478 const videoInstance = res.locals.videoAll
479 let description = ''
480
481 if (videoInstance.isOwned()) {
482 description = videoInstance.description
483 } else {
484 description = await fetchRemoteVideoDescription(videoInstance)
485 }
486
487 return res.json({ description })
488 }
489
490 async function getVideoFileMetadata (req: express.Request, res: express.Response) {
491 const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId))
492
493 return res.json(videoFile.metadata)
494 }
495
496 async function listVideos (req: express.Request, res: express.Response) {
497 const countVideos = getCountVideos(req)
498
499 const apiOptions = await Hooks.wrapObject({
500 start: req.query.start,
501 count: req.query.count,
502 sort: req.query.sort,
503 includeLocalVideos: true,
504 categoryOneOf: req.query.categoryOneOf,
505 licenceOneOf: req.query.licenceOneOf,
506 languageOneOf: req.query.languageOneOf,
507 tagsOneOf: req.query.tagsOneOf,
508 tagsAllOf: req.query.tagsAllOf,
509 nsfw: buildNSFWFilter(res, req.query.nsfw),
510 filter: req.query.filter as VideoFilter,
511 withFiles: false,
512 user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
513 countVideos
514 }, 'filter:api.videos.list.params')
515
516 const resultList = await Hooks.wrapPromiseFun(
517 VideoModel.listForApi,
518 apiOptions,
519 'filter:api.videos.list.result'
520 )
521
522 return res.json(getFormattedObjects(resultList.data, resultList.total))
523 }
524
525 async function removeVideo (req: express.Request, res: express.Response) {
526 const videoInstance = res.locals.videoAll
527
528 await sequelizeTypescript.transaction(async t => {
529 await videoInstance.destroy({ transaction: t })
530 })
531
532 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
533 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
534
535 Hooks.runAction('action:api.video.deleted', { video: videoInstance })
536
537 return res.type('json')
538 .status(HttpStatusCode.NO_CONTENT_204)
539 .end()
540 }
541
542 async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
543 await createTorrentAndSetInfoHash(video, fileArg)
544
545 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
546 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
547 // File does not exist anymore, remove the generated torrent
548 if (!refreshedFile) return fileArg.removeTorrent()
549
550 refreshedFile.infoHash = fileArg.infoHash
551 refreshedFile.torrentFilename = fileArg.torrentFilename
552
553 return refreshedFile.save()
554 }