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