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