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