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