]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
76a318d13b0951282bde551b61339becd1836e6b
[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 }
195 const video = new VideoModel(videoData)
196 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
197
198 // Build the file object
199 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
200 const fps = await getVideoFileFPS(videoPhysicalFile.path)
201
202 const videoFileData = {
203 extname: extname(videoPhysicalFile.filename),
204 resolution: videoFileResolution,
205 size: videoPhysicalFile.size,
206 fps
207 }
208 const videoFile = new VideoFileModel(videoFileData)
209
210 // Move physical file
211 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
212 const destination = join(videoDir, video.getVideoFilename(videoFile))
213 await move(videoPhysicalFile.path, destination)
214 // This is important in case if there is another attempt in the retry process
215 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
216 videoPhysicalFile.path = destination
217
218 // Process thumbnail or create it from the video
219 const thumbnailField = req.files['thumbnailfile']
220 if (thumbnailField) {
221 const thumbnailPhysicalFile = thumbnailField[0]
222 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
223 } else {
224 await video.createThumbnail(videoFile)
225 }
226
227 // Process preview or create it from the video
228 const previewField = req.files['previewfile']
229 if (previewField) {
230 const previewPhysicalFile = previewField[0]
231 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
232 } else {
233 await video.createPreview(videoFile)
234 }
235
236 // Create the torrent file
237 await video.createTorrentAndSetInfoHash(videoFile)
238
239 const videoCreated = await sequelizeTypescript.transaction(async t => {
240 const sequelizeOptions = { transaction: t }
241
242 const videoCreated = await video.save(sequelizeOptions)
243 // Do not forget to add video channel information to the created video
244 videoCreated.VideoChannel = res.locals.videoChannel
245
246 videoFile.videoId = video.id
247 await videoFile.save(sequelizeOptions)
248
249 video.VideoFiles = [ videoFile ]
250
251 // Create tags
252 if (videoInfo.tags !== undefined) {
253 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
254
255 await video.$set('Tags', tagInstances, sequelizeOptions)
256 video.Tags = tagInstances
257 }
258
259 // Schedule an update in the future?
260 if (videoInfo.scheduleUpdate) {
261 await ScheduleVideoUpdateModel.create({
262 videoId: video.id,
263 updateAt: videoInfo.scheduleUpdate.updateAt,
264 privacy: videoInfo.scheduleUpdate.privacy || null
265 }, { transaction: t })
266 }
267
268 await federateVideoIfNeeded(video, true, t)
269
270 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
271 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
272
273 return videoCreated
274 })
275
276 Notifier.Instance.notifyOnNewVideo(videoCreated)
277
278 if (video.state === VideoState.TO_TRANSCODE) {
279 // Put uuid because we don't have id auto incremented for now
280 const dataInput = {
281 videoUUID: videoCreated.uuid,
282 isNewVideo: true
283 }
284
285 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
286 }
287
288 return res.json({
289 video: {
290 id: videoCreated.id,
291 uuid: videoCreated.uuid
292 }
293 }).end()
294 }
295
296 async function updateVideo (req: express.Request, res: express.Response) {
297 const videoInstance: VideoModel = res.locals.video
298 const videoFieldsSave = videoInstance.toJSON()
299 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
300 const videoInfoToUpdate: VideoUpdate = req.body
301 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
302 const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
303
304 // Process thumbnail or create it from the video
305 if (req.files && req.files['thumbnailfile']) {
306 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
307 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
308 }
309
310 // Process preview or create it from the video
311 if (req.files && req.files['previewfile']) {
312 const previewPhysicalFile = req.files['previewfile'][0]
313 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
314 }
315
316 try {
317 const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
318 const sequelizeOptions = { transaction: t }
319 const oldVideoChannel = videoInstance.VideoChannel
320
321 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
322 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
323 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
324 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
325 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
326 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
327 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
328 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
329 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
330 if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.set('downloadEnabled', videoInfoToUpdate.downloadEnabled)
331 if (videoInfoToUpdate.privacy !== undefined) {
332 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
333 videoInstance.set('privacy', newPrivacy)
334
335 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
336 videoInstance.set('publishedAt', new Date())
337 }
338 }
339
340 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
341
342 // Video tags update?
343 if (videoInfoToUpdate.tags !== undefined) {
344 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
345
346 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
347 videoInstanceUpdated.Tags = tagInstances
348 }
349
350 // Video channel update?
351 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
352 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
353 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
354
355 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
356 }
357
358 // Schedule an update in the future?
359 if (videoInfoToUpdate.scheduleUpdate) {
360 await ScheduleVideoUpdateModel.upsert({
361 videoId: videoInstanceUpdated.id,
362 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
363 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
364 }, { transaction: t })
365 } else if (videoInfoToUpdate.scheduleUpdate === null) {
366 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
367 }
368
369 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
370
371 // Don't send update if the video was unfederated
372 if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
373 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
374 }
375
376 auditLogger.update(
377 getAuditIdFromRes(res),
378 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
379 oldVideoAuditView
380 )
381 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
382
383 return videoInstanceUpdated
384 })
385
386 if (wasUnlistedVideo || wasPrivateVideo) {
387 Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
388 }
389 } catch (err) {
390 // Force fields we want to update
391 // If the transaction is retried, sequelize will think the object has not changed
392 // So it will skip the SQL request, even if the last one was ROLLBACKed!
393 resetSequelizeInstance(videoInstance, videoFieldsSave)
394
395 throw err
396 }
397
398 return res.type('json').status(204).end()
399 }
400
401 async function getVideo (req: express.Request, res: express.Response) {
402 // We need more attributes
403 const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
404 const video: VideoModel = await VideoModel.loadForGetAPI(res.locals.video.id, undefined, userId)
405
406 if (video.isOutdated()) {
407 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
408 .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
409 }
410
411 return res.json(video.toFormattedDetailsJSON())
412 }
413
414 async function viewVideo (req: express.Request, res: express.Response) {
415 const videoInstance = res.locals.video
416
417 const ip = req.ip
418 const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid)
419 if (exists) {
420 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
421 return res.status(204).end()
422 }
423
424 await Promise.all([
425 Redis.Instance.addVideoView(videoInstance.id),
426 Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
427 ])
428
429 const serverActor = await getServerActor()
430 await sendView(serverActor, videoInstance, undefined)
431
432 return res.status(204).end()
433 }
434
435 async function getVideoDescription (req: express.Request, res: express.Response) {
436 const videoInstance = res.locals.video
437 let description = ''
438
439 if (videoInstance.isOwned()) {
440 description = videoInstance.description
441 } else {
442 description = await fetchRemoteVideoDescription(videoInstance)
443 }
444
445 return res.json({ description })
446 }
447
448 async function listVideos (req: express.Request, res: express.Response) {
449 const resultList = await VideoModel.listForApi({
450 start: req.query.start,
451 count: req.query.count,
452 sort: req.query.sort,
453 includeLocalVideos: true,
454 categoryOneOf: req.query.categoryOneOf,
455 licenceOneOf: req.query.licenceOneOf,
456 languageOneOf: req.query.languageOneOf,
457 tagsOneOf: req.query.tagsOneOf,
458 tagsAllOf: req.query.tagsAllOf,
459 nsfw: buildNSFWFilter(res, req.query.nsfw),
460 filter: req.query.filter as VideoFilter,
461 withFiles: false,
462 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
463 })
464
465 return res.json(getFormattedObjects(resultList.data, resultList.total))
466 }
467
468 async function removeVideo (req: express.Request, res: express.Response) {
469 const videoInstance: VideoModel = res.locals.video
470
471 await sequelizeTypescript.transaction(async t => {
472 await videoInstance.destroy({ transaction: t })
473 })
474
475 auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
476 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
477
478 return res.type('json').status(204).end()
479 }