78948ff249fc54665858b32497bd337ba79a99df
[oweals/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 import { Hooks } from '../../../lib/plugins/hooks'
66 import { MVideoDetails, MVideoFullLight } from '@server/typings/models'
67 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
68 import { getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
69
70 const auditLogger = auditLoggerFactory('videos')
71 const videosRouter = express.Router()
72
73 const reqVideoFileAdd = createReqFiles(
74   [ 'videofile', 'thumbnailfile', 'previewfile' ],
75   Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
76   {
77     videofile: CONFIG.STORAGE.TMP_DIR,
78     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
79     previewfile: CONFIG.STORAGE.TMP_DIR
80   }
81 )
82 const reqVideoFileUpdate = createReqFiles(
83   [ 'thumbnailfile', 'previewfile' ],
84   MIMETYPES.IMAGE.MIMETYPE_EXT,
85   {
86     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
87     previewfile: CONFIG.STORAGE.TMP_DIR
88   }
89 )
90
91 videosRouter.use('/', abuseVideoRouter)
92 videosRouter.use('/', blacklistRouter)
93 videosRouter.use('/', rateVideoRouter)
94 videosRouter.use('/', videoCommentRouter)
95 videosRouter.use('/', videoCaptionsRouter)
96 videosRouter.use('/', videoImportsRouter)
97 videosRouter.use('/', ownershipVideoRouter)
98 videosRouter.use('/', watchingRouter)
99
100 videosRouter.get('/categories', listVideoCategories)
101 videosRouter.get('/licences', listVideoLicences)
102 videosRouter.get('/languages', listVideoLanguages)
103 videosRouter.get('/privacies', listVideoPrivacies)
104
105 videosRouter.get('/',
106   paginationValidator,
107   videosSortValidator,
108   setDefaultSort,
109   setDefaultPagination,
110   optionalAuthenticate,
111   commonVideosFiltersValidator,
112   asyncMiddleware(listVideos)
113 )
114 videosRouter.put('/:id',
115   authenticate,
116   reqVideoFileUpdate,
117   asyncMiddleware(videosUpdateValidator),
118   asyncRetryTransactionMiddleware(updateVideo)
119 )
120 videosRouter.post('/upload',
121   authenticate,
122   reqVideoFileAdd,
123   asyncMiddleware(videosAddValidator),
124   asyncRetryTransactionMiddleware(addVideo)
125 )
126
127 videosRouter.get('/:id/description',
128   asyncMiddleware(videosGetValidator),
129   asyncMiddleware(getVideoDescription)
130 )
131 videosRouter.get('/:id',
132   optionalAuthenticate,
133   asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
134   asyncMiddleware(checkVideoFollowConstraints),
135   asyncMiddleware(getVideo)
136 )
137 videosRouter.post('/:id/views',
138   asyncMiddleware(videosGetValidator),
139   asyncMiddleware(viewVideo)
140 )
141
142 videosRouter.delete('/:id',
143   authenticate,
144   asyncMiddleware(videosRemoveValidator),
145   asyncRetryTransactionMiddleware(removeVideo)
146 )
147
148 // ---------------------------------------------------------------------------
149
150 export {
151   videosRouter
152 }
153
154 // ---------------------------------------------------------------------------
155
156 function listVideoCategories (req: express.Request, res: express.Response) {
157   res.json(VIDEO_CATEGORIES)
158 }
159
160 function listVideoLicences (req: express.Request, res: express.Response) {
161   res.json(VIDEO_LICENCES)
162 }
163
164 function listVideoLanguages (req: express.Request, res: express.Response) {
165   res.json(VIDEO_LANGUAGES)
166 }
167
168 function listVideoPrivacies (req: express.Request, res: express.Response) {
169   res.json(VIDEO_PRIVACIES)
170 }
171
172 async function addVideo (req: express.Request, res: express.Response) {
173   // Processing the video could be long
174   // Set timeout to 10 minutes
175   req.setTimeout(1000 * 60 * 10, () => {
176     logger.error('Upload video has timed out.')
177     return res.sendStatus(408)
178   })
179
180   const videoPhysicalFile = req.files['videofile'][0]
181   const videoInfo: VideoCreate = req.body
182
183   // Prepare data so we don't block the transaction
184   const videoData = {
185     name: videoInfo.name,
186     remote: false,
187     category: videoInfo.category,
188     licence: videoInfo.licence,
189     language: videoInfo.language,
190     commentsEnabled: videoInfo.commentsEnabled !== false, // If the value is not "false", the default is "true"
191     downloadEnabled: videoInfo.downloadEnabled !== false,
192     waitTranscoding: videoInfo.waitTranscoding || false,
193     state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
194     nsfw: videoInfo.nsfw || false,
195     description: videoInfo.description,
196     support: videoInfo.support,
197     privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
198     duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
199     channelId: res.locals.videoChannel.id,
200     originallyPublishedAt: videoInfo.originallyPublishedAt
201   }
202
203   const video = new VideoModel(videoData) as MVideoDetails
204   video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
205
206   const videoFile = new VideoFileModel({
207     extname: extname(videoPhysicalFile.filename),
208     size: videoPhysicalFile.size,
209     videoStreamingPlaylistId: null
210   })
211
212   if (videoFile.isAudio()) {
213     videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
214   } else {
215     videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
216     videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
217   }
218
219   // Move physical file
220   const destination = getVideoFilePath(video, videoFile)
221   await move(videoPhysicalFile.path, destination)
222   // This is important in case if there is another attempt in the retry process
223   videoPhysicalFile.filename = getVideoFilePath(video, videoFile)
224   videoPhysicalFile.path = destination
225
226   // Process thumbnail or create it from the video
227   const thumbnailField = req.files['thumbnailfile']
228   const thumbnailModel = thumbnailField
229     ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE, false)
230     : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
231
232   // Process preview or create it from the video
233   const previewField = req.files['previewfile']
234   const previewModel = previewField
235     ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW, false)
236     : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
237
238   // Create the torrent file
239   await createTorrentAndSetInfoHash(video, videoFile)
240
241   const { videoCreated } = await sequelizeTypescript.transaction(async t => {
242     const sequelizeOptions = { transaction: t }
243
244     const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
245
246     await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
247     await videoCreated.addAndSaveThumbnail(previewModel, t)
248
249     // Do not forget to add video channel information to the created video
250     videoCreated.VideoChannel = res.locals.videoChannel
251
252     videoFile.videoId = video.id
253     await videoFile.save(sequelizeOptions)
254
255     video.VideoFiles = [ videoFile ]
256
257     // Create tags
258     if (videoInfo.tags !== undefined) {
259       const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
260
261       await video.$set('Tags', tagInstances, sequelizeOptions)
262       video.Tags = tagInstances
263     }
264
265     // Schedule an update in the future?
266     if (videoInfo.scheduleUpdate) {
267       await ScheduleVideoUpdateModel.create({
268         videoId: video.id,
269         updateAt: videoInfo.scheduleUpdate.updateAt,
270         privacy: videoInfo.scheduleUpdate.privacy || null
271       }, { transaction: t })
272     }
273
274     await autoBlacklistVideoIfNeeded({
275       video,
276       user: res.locals.oauth.token.User,
277       isRemote: false,
278       isNew: true,
279       transaction: t
280     })
281     await federateVideoIfNeeded(video, true, t)
282
283     auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
284     logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
285
286     return { videoCreated }
287   })
288
289   Notifier.Instance.notifyOnNewVideoIfNeeded(videoCreated)
290
291   if (video.state === VideoState.TO_TRANSCODE) {
292     // Put uuid because we don't have id auto incremented for now
293     let dataInput: VideoTranscodingPayload
294
295     if (videoFile.isAudio()) {
296       dataInput = {
297         type: 'merge-audio' as 'merge-audio',
298         resolution: DEFAULT_AUDIO_RESOLUTION,
299         videoUUID: videoCreated.uuid,
300         isNewVideo: true
301       }
302     } else {
303       dataInput = {
304         type: 'optimize' as 'optimize',
305         videoUUID: videoCreated.uuid,
306         isNewVideo: true
307       }
308     }
309
310     await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
311   }
312
313   Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
314
315   return res.json({
316     video: {
317       id: videoCreated.id,
318       uuid: videoCreated.uuid
319     }
320   }).end()
321 }
322
323 async function updateVideo (req: express.Request, res: express.Response) {
324   const videoInstance = res.locals.videoAll
325   const videoFieldsSave = videoInstance.toJSON()
326   const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
327   const videoInfoToUpdate: VideoUpdate = req.body
328
329   const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
330   const wasNotPrivateVideo = videoInstance.privacy !== VideoPrivacy.PRIVATE
331   const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
332
333   // Process thumbnail or create it from the video
334   const thumbnailModel = req.files && req.files['thumbnailfile']
335     ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false)
336     : undefined
337
338   const previewModel = req.files && req.files['previewfile']
339     ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
340     : undefined
341
342   try {
343     const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
344       const sequelizeOptions = { transaction: t }
345       const oldVideoChannel = videoInstance.VideoChannel
346
347       if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
348       if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
349       if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
350       if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
351       if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
352       if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
353       if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
354       if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
355       if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
356       if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
357
358       if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
359         videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
360       }
361
362       if (videoInfoToUpdate.privacy !== undefined) {
363         const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
364         videoInstance.privacy = newPrivacy
365
366         // The video was private, and is not anymore -> publish it
367         if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
368           videoInstance.publishedAt = new Date()
369         }
370
371         // The video was not private, but now it is -> we need to unfederate it
372         if (wasNotPrivateVideo === true && newPrivacy === VideoPrivacy.PRIVATE) {
373           await VideoModel.sendDelete(videoInstance, { transaction: t })
374         }
375       }
376
377       const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
378
379       if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
380       if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
381
382       // Video tags update?
383       if (videoInfoToUpdate.tags !== undefined) {
384         const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
385
386         await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
387         videoInstanceUpdated.Tags = tagInstances
388       }
389
390       // Video channel update?
391       if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
392         await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
393         videoInstanceUpdated.VideoChannel = res.locals.videoChannel
394
395         if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
396       }
397
398       // Schedule an update in the future?
399       if (videoInfoToUpdate.scheduleUpdate) {
400         await ScheduleVideoUpdateModel.upsert({
401           videoId: videoInstanceUpdated.id,
402           updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
403           privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
404         }, { transaction: t })
405       } else if (videoInfoToUpdate.scheduleUpdate === null) {
406         await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
407       }
408
409       await autoBlacklistVideoIfNeeded({
410         video: videoInstanceUpdated,
411         user: res.locals.oauth.token.User,
412         isRemote: false,
413         isNew: false,
414         transaction: t
415       })
416
417       const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
418       await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
419
420       auditLogger.update(
421         getAuditIdFromRes(res),
422         new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
423         oldVideoAuditView
424       )
425       logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
426
427       return videoInstanceUpdated
428     })
429
430     if (wasUnlistedVideo || wasPrivateVideo) {
431       Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
432     }
433
434     Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
435   } catch (err) {
436     // Force fields we want to update
437     // If the transaction is retried, sequelize will think the object has not changed
438     // So it will skip the SQL request, even if the last one was ROLLBACKed!
439     resetSequelizeInstance(videoInstance, videoFieldsSave)
440
441     throw err
442   }
443
444   return res.type('json').status(204).end()
445 }
446
447 async function getVideo (req: express.Request, res: express.Response) {
448   // We need more attributes
449   const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
450
451   const video = await Hooks.wrapPromiseFun(
452     VideoModel.loadForGetAPI,
453     { id: res.locals.onlyVideoWithRights.id, userId },
454     'filter:api.video.get.result'
455   )
456
457   if (video.isOutdated()) {
458     JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
459       .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
460   }
461
462   return res.json(video.toFormattedDetailsJSON())
463 }
464
465 async function viewVideo (req: express.Request, res: express.Response) {
466   const videoInstance = res.locals.videoAll
467
468   const ip = req.ip
469   const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
470   if (exists) {
471     logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
472     return res.status(204).end()
473   }
474
475   await Promise.all([
476     Redis.Instance.addVideoView(videoInstance.id),
477     Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
478   ])
479
480   const serverActor = await getServerActor()
481   await sendView(serverActor, videoInstance, undefined)
482
483   Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
484
485   return res.status(204).end()
486 }
487
488 async function getVideoDescription (req: express.Request, res: express.Response) {
489   const videoInstance = res.locals.videoAll
490   let description = ''
491
492   if (videoInstance.isOwned()) {
493     description = videoInstance.description
494   } else {
495     description = await fetchRemoteVideoDescription(videoInstance)
496   }
497
498   return res.json({ description })
499 }
500
501 async function listVideos (req: express.Request, res: express.Response) {
502   const apiOptions = await Hooks.wrapObject({
503     start: req.query.start,
504     count: req.query.count,
505     sort: req.query.sort,
506     includeLocalVideos: true,
507     categoryOneOf: req.query.categoryOneOf,
508     licenceOneOf: req.query.licenceOneOf,
509     languageOneOf: req.query.languageOneOf,
510     tagsOneOf: req.query.tagsOneOf,
511     tagsAllOf: req.query.tagsAllOf,
512     nsfw: buildNSFWFilter(res, req.query.nsfw),
513     filter: req.query.filter as VideoFilter,
514     withFiles: false,
515     user: res.locals.oauth ? res.locals.oauth.token.User : undefined
516   }, 'filter:api.videos.list.params')
517
518   const resultList = await Hooks.wrapPromiseFun(
519     VideoModel.listForApi,
520     apiOptions,
521     'filter:api.videos.list.result'
522   )
523
524   return res.json(getFormattedObjects(resultList.data, resultList.total))
525 }
526
527 async function removeVideo (req: express.Request, res: express.Response) {
528   const videoInstance = res.locals.videoAll
529
530   await sequelizeTypescript.transaction(async t => {
531     await videoInstance.destroy({ transaction: t })
532   })
533
534   auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
535   logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
536
537   Hooks.runAction('action:api.video.deleted', { video: videoInstance })
538
539   return res.type('json').status(204).end()
540 }