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