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