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