Move to eslint
[oweals/peertube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import { extname } 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, getCountVideos } 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 { 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.createJobWithPromise({ 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 wasConfidentialVideo = videoInstance.isConfidential()
330   const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation()
331
332   // Process thumbnail or create it from the video
333   const thumbnailModel = req.files && req.files['thumbnailfile']
334     ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE, false)
335     : undefined
336
337   const previewModel = req.files && req.files['previewfile']
338     ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW, false)
339     : undefined
340
341   try {
342     const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => {
343       const sequelizeOptions = { transaction: t }
344       const oldVideoChannel = videoInstance.VideoChannel
345
346       if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name
347       if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category
348       if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence
349       if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language
350       if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw
351       if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding
352       if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support
353       if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description
354       if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled
355       if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled
356
357       if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
358         videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
359       }
360
361       let isNewVideo = false
362       if (videoInfoToUpdate.privacy !== undefined) {
363         isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy)
364
365         const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
366         videoInstance.setPrivacy(newPrivacy)
367
368         // Unfederate the video if the new privacy is not compatible with federation
369         if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) {
370           await VideoModel.sendDelete(videoInstance, { transaction: t })
371         }
372       }
373
374       const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight
375
376       if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
377       if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
378
379       // Video tags update?
380       if (videoInfoToUpdate.tags !== undefined) {
381         const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
382
383         await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
384         videoInstanceUpdated.Tags = tagInstances
385       }
386
387       // Video channel update?
388       if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
389         await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
390         videoInstanceUpdated.VideoChannel = res.locals.videoChannel
391
392         if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
393       }
394
395       // Schedule an update in the future?
396       if (videoInfoToUpdate.scheduleUpdate) {
397         await ScheduleVideoUpdateModel.upsert({
398           videoId: videoInstanceUpdated.id,
399           updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
400           privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
401         }, { transaction: t })
402       } else if (videoInfoToUpdate.scheduleUpdate === null) {
403         await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
404       }
405
406       await autoBlacklistVideoIfNeeded({
407         video: videoInstanceUpdated,
408         user: res.locals.oauth.token.User,
409         isRemote: false,
410         isNew: false,
411         transaction: t
412       })
413
414       await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
415
416       auditLogger.update(
417         getAuditIdFromRes(res),
418         new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
419         oldVideoAuditView
420       )
421       logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
422
423       return videoInstanceUpdated
424     })
425
426     if (wasConfidentialVideo) {
427       Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated)
428     }
429
430     Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated })
431   } catch (err) {
432     // Force fields we want to update
433     // If the transaction is retried, sequelize will think the object has not changed
434     // So it will skip the SQL request, even if the last one was ROLLBACKed!
435     resetSequelizeInstance(videoInstance, videoFieldsSave)
436
437     throw err
438   }
439
440   return res.type('json').status(204).end()
441 }
442
443 async function getVideo (req: express.Request, res: express.Response) {
444   // We need more attributes
445   const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
446
447   const video = await Hooks.wrapPromiseFun(
448     VideoModel.loadForGetAPI,
449     { id: res.locals.onlyVideoWithRights.id, userId },
450     'filter:api.video.get.result'
451   )
452
453   if (video.isOutdated()) {
454     JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
455   }
456
457   return res.json(video.toFormattedDetailsJSON())
458 }
459
460 async function viewVideo (req: express.Request, res: express.Response) {
461   const videoInstance = res.locals.videoAll
462
463   const ip = req.ip
464   const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
465   if (exists) {
466     logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
467     return res.status(204).end()
468   }
469
470   await Promise.all([
471     Redis.Instance.addVideoView(videoInstance.id),
472     Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
473   ])
474
475   const serverActor = await getServerActor()
476   await sendView(serverActor, videoInstance, undefined)
477
478   Hooks.runAction('action:api.video.viewed', { video: videoInstance, ip })
479
480   return res.status(204).end()
481 }
482
483 async function getVideoDescription (req: express.Request, res: express.Response) {
484   const videoInstance = res.locals.videoAll
485   let description = ''
486
487   if (videoInstance.isOwned()) {
488     description = videoInstance.description
489   } else {
490     description = await fetchRemoteVideoDescription(videoInstance)
491   }
492
493   return res.json({ description })
494 }
495
496 async function listVideos (req: express.Request, res: express.Response) {
497   const countVideos = getCountVideos(req)
498
499   const apiOptions = await Hooks.wrapObject({
500     start: req.query.start,
501     count: req.query.count,
502     sort: req.query.sort,
503     includeLocalVideos: true,
504     categoryOneOf: req.query.categoryOneOf,
505     licenceOneOf: req.query.licenceOneOf,
506     languageOneOf: req.query.languageOneOf,
507     tagsOneOf: req.query.tagsOneOf,
508     tagsAllOf: req.query.tagsAllOf,
509     nsfw: buildNSFWFilter(res, req.query.nsfw),
510     filter: req.query.filter as VideoFilter,
511     withFiles: false,
512     user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
513     countVideos
514   }, 'filter:api.videos.list.params')
515
516   const resultList = await Hooks.wrapPromiseFun(
517     VideoModel.listForApi,
518     apiOptions,
519     'filter:api.videos.list.result'
520   )
521
522   return res.json(getFormattedObjects(resultList.data, resultList.total))
523 }
524
525 async function removeVideo (req: express.Request, res: express.Response) {
526   const videoInstance = res.locals.videoAll
527
528   await sequelizeTypescript.transaction(async t => {
529     await videoInstance.destroy({ transaction: t })
530   })
531
532   auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
533   logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
534
535   Hooks.runAction('action:api.video.deleted', { video: videoInstance })
536
537   return res.type('json').status(204).end()
538 }