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