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