Upgrade sequelize
[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 { MIMETYPES, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants'
10 import {
11   changeVideoChannelShare,
12   federateVideoIfNeeded,
13   fetchRemoteVideoDescription,
14   getVideoActivityPubUrl
15 } from '../../../lib/activitypub'
16 import { JobQueue } from '../../../lib/job-queue'
17 import { Redis } from '../../../lib/redis'
18 import {
19   asyncMiddleware,
20   asyncRetryTransactionMiddleware,
21   authenticate,
22   checkVideoFollowConstraints,
23   commonVideosFiltersValidator,
24   optionalAuthenticate,
25   paginationValidator,
26   setDefaultPagination,
27   setDefaultSort,
28   videosAddValidator,
29   videosCustomGetValidator,
30   videosGetValidator,
31   videosRemoveValidator,
32   videosSortValidator,
33   videosUpdateValidator
34 } from '../../../middlewares'
35 import { TagModel } from '../../../models/video/tag'
36 import { VideoModel } from '../../../models/video/video'
37 import { VideoFileModel } from '../../../models/video/video-file'
38 import { abuseVideoRouter } from './abuse'
39 import { blacklistRouter } from './blacklist'
40 import { videoCommentRouter } from './comment'
41 import { rateVideoRouter } from './rate'
42 import { ownershipVideoRouter } from './ownership'
43 import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
44 import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
45 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
46 import { videoCaptionsRouter } from './captions'
47 import { videoImportsRouter } from './import'
48 import { resetSequelizeInstance } from '../../../helpers/database-utils'
49 import { move } from 'fs-extra'
50 import { watchingRouter } from './watching'
51 import { Notifier } from '../../../lib/notifier'
52 import { sendView } from '../../../lib/activitypub/send/send-view'
53 import { CONFIG } from '../../../initializers/config'
54 import { sequelizeTypescript } from '../../../initializers/database'
55 import { createVideoMiniatureFromExisting, generateVideoMiniature } from '../../../lib/thumbnail'
56 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
57
58 const auditLogger = auditLoggerFactory('videos')
59 const videosRouter = express.Router()
60
61 const reqVideoFileAdd = createReqFiles(
62   [ 'videofile', 'thumbnailfile', 'previewfile' ],
63   Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
64   {
65     videofile: CONFIG.STORAGE.TMP_DIR,
66     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
67     previewfile: CONFIG.STORAGE.TMP_DIR
68   }
69 )
70 const reqVideoFileUpdate = createReqFiles(
71   [ 'thumbnailfile', 'previewfile' ],
72   MIMETYPES.IMAGE.MIMETYPE_EXT,
73   {
74     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
75     previewfile: CONFIG.STORAGE.TMP_DIR
76   }
77 )
78
79 videosRouter.use('/', abuseVideoRouter)
80 videosRouter.use('/', blacklistRouter)
81 videosRouter.use('/', rateVideoRouter)
82 videosRouter.use('/', videoCommentRouter)
83 videosRouter.use('/', videoCaptionsRouter)
84 videosRouter.use('/', videoImportsRouter)
85 videosRouter.use('/', ownershipVideoRouter)
86 videosRouter.use('/', watchingRouter)
87
88 videosRouter.get('/categories', listVideoCategories)
89 videosRouter.get('/licences', listVideoLicences)
90 videosRouter.get('/languages', listVideoLanguages)
91 videosRouter.get('/privacies', listVideoPrivacies)
92
93 videosRouter.get('/',
94   paginationValidator,
95   videosSortValidator,
96   setDefaultSort,
97   setDefaultPagination,
98   optionalAuthenticate,
99   commonVideosFiltersValidator,
100   asyncMiddleware(listVideos)
101 )
102 videosRouter.put('/:id',
103   authenticate,
104   reqVideoFileUpdate,
105   asyncMiddleware(videosUpdateValidator),
106   asyncRetryTransactionMiddleware(updateVideo)
107 )
108 videosRouter.post('/upload',
109   authenticate,
110   reqVideoFileAdd,
111   asyncMiddleware(videosAddValidator),
112   asyncRetryTransactionMiddleware(addVideo)
113 )
114
115 videosRouter.get('/:id/description',
116   asyncMiddleware(videosGetValidator),
117   asyncMiddleware(getVideoDescription)
118 )
119 videosRouter.get('/:id',
120   optionalAuthenticate,
121   asyncMiddleware(videosCustomGetValidator('only-video-with-rights')),
122   asyncMiddleware(checkVideoFollowConstraints),
123   asyncMiddleware(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   // Processing the video could be long
162   // Set timeout to 10 minutes
163   req.setTimeout(1000 * 60 * 10, () => {
164     logger.error('Upload video has timed out.')
165     return res.sendStatus(408)
166   })
167
168   const videoPhysicalFile = req.files['videofile'][0]
169   const videoInfo: VideoCreate = req.body
170
171   // Prepare data so we don't block the transaction
172   const videoData = {
173     name: videoInfo.name,
174     remote: false,
175     category: videoInfo.category,
176     licence: videoInfo.licence,
177     language: videoInfo.language,
178     commentsEnabled: videoInfo.commentsEnabled || false,
179     downloadEnabled: videoInfo.downloadEnabled || true,
180     waitTranscoding: videoInfo.waitTranscoding || false,
181     state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
182     nsfw: videoInfo.nsfw || false,
183     description: videoInfo.description,
184     support: videoInfo.support,
185     privacy: videoInfo.privacy,
186     duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
187     channelId: res.locals.videoChannel.id,
188     originallyPublishedAt: videoInfo.originallyPublishedAt
189   }
190
191   const video = new VideoModel(videoData)
192   video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
193
194   // Build the file object
195   const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
196   const fps = await getVideoFileFPS(videoPhysicalFile.path)
197
198   const videoFileData = {
199     extname: extname(videoPhysicalFile.filename),
200     resolution: videoFileResolution,
201     size: videoPhysicalFile.size,
202     fps
203   }
204   const videoFile = new VideoFileModel(videoFileData)
205
206   // Move physical file
207   const videoDir = CONFIG.STORAGE.VIDEOS_DIR
208   const destination = join(videoDir, video.getVideoFilename(videoFile))
209   await move(videoPhysicalFile.path, destination)
210   // This is important in case if there is another attempt in the retry process
211   videoPhysicalFile.filename = video.getVideoFilename(videoFile)
212   videoPhysicalFile.path = destination
213
214   // Process thumbnail or create it from the video
215   const thumbnailField = req.files['thumbnailfile']
216   const thumbnailModel = thumbnailField
217     ? await createVideoMiniatureFromExisting(thumbnailField[0].path, video, ThumbnailType.MINIATURE)
218     : await generateVideoMiniature(video, videoFile, ThumbnailType.MINIATURE)
219
220   // Process preview or create it from the video
221   const previewField = req.files['previewfile']
222   const previewModel = previewField
223     ? await createVideoMiniatureFromExisting(previewField[0].path, video, ThumbnailType.PREVIEW)
224     : await generateVideoMiniature(video, videoFile, ThumbnailType.PREVIEW)
225
226   // Create the torrent file
227   await video.createTorrentAndSetInfoHash(videoFile)
228
229   const { videoCreated, videoWasAutoBlacklisted } = await sequelizeTypescript.transaction(async t => {
230     const sequelizeOptions = { transaction: t }
231
232     const videoCreated = await video.save(sequelizeOptions)
233
234     await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
235     await videoCreated.addAndSaveThumbnail(previewModel, t)
236
237     // Do not forget to add video channel information to the created video
238     videoCreated.VideoChannel = res.locals.videoChannel
239
240     videoFile.videoId = video.id
241     await videoFile.save(sequelizeOptions)
242
243     video.VideoFiles = [ videoFile ]
244
245     // Create tags
246     if (videoInfo.tags !== undefined) {
247       const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
248
249       await video.$set('Tags', tagInstances, sequelizeOptions)
250       video.Tags = tagInstances
251     }
252
253     // Schedule an update in the future?
254     if (videoInfo.scheduleUpdate) {
255       await ScheduleVideoUpdateModel.create({
256         videoId: video.id,
257         updateAt: videoInfo.scheduleUpdate.updateAt,
258         privacy: videoInfo.scheduleUpdate.privacy || null
259       }, { transaction: t })
260     }
261
262     const videoWasAutoBlacklisted = await autoBlacklistVideoIfNeeded(video, res.locals.oauth.token.User, t)
263
264     if (!videoWasAutoBlacklisted) {
265       await federateVideoIfNeeded(video, true, t)
266     }
267
268     auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
269     logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
270
271     return { videoCreated, videoWasAutoBlacklisted }
272   })
273
274   if (videoWasAutoBlacklisted) {
275     Notifier.Instance.notifyOnVideoAutoBlacklist(videoCreated)
276   } else {
277     Notifier.Instance.notifyOnNewVideo(videoCreated)
278   }
279
280   if (video.state === VideoState.TO_TRANSCODE) {
281     // Put uuid because we don't have id auto incremented for now
282     const dataInput = {
283       videoUUID: videoCreated.uuid,
284       isNewVideo: true
285     }
286
287     await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
288   }
289
290   return res.json({
291     video: {
292       id: videoCreated.id,
293       uuid: videoCreated.uuid
294     }
295   }).end()
296 }
297
298 async function updateVideo (req: express.Request, res: express.Response) {
299   const videoInstance = res.locals.video
300   const videoFieldsSave = videoInstance.toJSON()
301   const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
302   const videoInfoToUpdate: VideoUpdate = req.body
303   const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
304   const wasUnlistedVideo = videoInstance.privacy === VideoPrivacy.UNLISTED
305
306   // Process thumbnail or create it from the video
307   const thumbnailModel = req.files && req.files['thumbnailfile']
308     ? await createVideoMiniatureFromExisting(req.files['thumbnailfile'][0].path, videoInstance, ThumbnailType.MINIATURE)
309     : undefined
310
311   const previewModel = req.files && req.files['previewfile']
312     ? await createVideoMiniatureFromExisting(req.files['previewfile'][0].path, videoInstance, ThumbnailType.PREVIEW)
313     : undefined
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.downloadEnabled !== undefined) videoInstance.set('downloadEnabled', videoInfoToUpdate.downloadEnabled)
330
331       if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) {
332         videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt)
333       }
334
335       if (videoInfoToUpdate.privacy !== undefined) {
336         const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
337         videoInstance.privacy = newPrivacy
338
339         if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
340           videoInstance.publishedAt = new Date()
341         }
342       }
343
344       const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
345
346       if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t)
347       if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t)
348
349       // Video tags update?
350       if (videoInfoToUpdate.tags !== undefined) {
351         const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
352
353         await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
354         videoInstanceUpdated.Tags = tagInstances
355       }
356
357       // Video channel update?
358       if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
359         await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
360         videoInstanceUpdated.VideoChannel = res.locals.videoChannel
361
362         if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
363       }
364
365       // Schedule an update in the future?
366       if (videoInfoToUpdate.scheduleUpdate) {
367         await ScheduleVideoUpdateModel.upsert({
368           videoId: videoInstanceUpdated.id,
369           updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
370           privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
371         }, { transaction: t })
372       } else if (videoInfoToUpdate.scheduleUpdate === null) {
373         await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
374       }
375
376       const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
377
378       // Don't send update if the video was unfederated
379       if (!videoInstanceUpdated.VideoBlacklist || videoInstanceUpdated.VideoBlacklist.unfederated === false) {
380         await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
381       }
382
383       auditLogger.update(
384         getAuditIdFromRes(res),
385         new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
386         oldVideoAuditView
387       )
388       logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
389
390       return videoInstanceUpdated
391     })
392
393     if (wasUnlistedVideo || wasPrivateVideo) {
394       Notifier.Instance.notifyOnNewVideo(videoInstanceUpdated)
395     }
396   } catch (err) {
397     // Force fields we want to update
398     // If the transaction is retried, sequelize will think the object has not changed
399     // So it will skip the SQL request, even if the last one was ROLLBACKed!
400     resetSequelizeInstance(videoInstance, videoFieldsSave)
401
402     throw err
403   }
404
405   return res.type('json').status(204).end()
406 }
407
408 async function getVideo (req: express.Request, res: express.Response) {
409   // We need more attributes
410   const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null
411   const video = await VideoModel.loadForGetAPI(res.locals.video.id, undefined, userId)
412
413   if (video.isOutdated()) {
414     JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
415       .catch(err => logger.error('Cannot create AP refresher job for video %s.', video.url, { err }))
416   }
417
418   return res.json(video.toFormattedDetailsJSON())
419 }
420
421 async function viewVideo (req: express.Request, res: express.Response) {
422   const videoInstance = res.locals.video
423
424   const ip = req.ip
425   const exists = await Redis.Instance.doesVideoIPViewExist(ip, videoInstance.uuid)
426   if (exists) {
427     logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
428     return res.status(204).end()
429   }
430
431   await Promise.all([
432     Redis.Instance.addVideoView(videoInstance.id),
433     Redis.Instance.setIPVideoView(ip, videoInstance.uuid)
434   ])
435
436   const serverActor = await getServerActor()
437   await sendView(serverActor, videoInstance, undefined)
438
439   return res.status(204).end()
440 }
441
442 async function getVideoDescription (req: express.Request, res: express.Response) {
443   const videoInstance = res.locals.video
444   let description = ''
445
446   if (videoInstance.isOwned()) {
447     description = videoInstance.description
448   } else {
449     description = await fetchRemoteVideoDescription(videoInstance)
450   }
451
452   return res.json({ description })
453 }
454
455 async function listVideos (req: express.Request, res: express.Response) {
456   const resultList = await VideoModel.listForApi({
457     start: req.query.start,
458     count: req.query.count,
459     sort: req.query.sort,
460     includeLocalVideos: true,
461     categoryOneOf: req.query.categoryOneOf,
462     licenceOneOf: req.query.licenceOneOf,
463     languageOneOf: req.query.languageOneOf,
464     tagsOneOf: req.query.tagsOneOf,
465     tagsAllOf: req.query.tagsAllOf,
466     nsfw: buildNSFWFilter(res, req.query.nsfw),
467     filter: req.query.filter as VideoFilter,
468     withFiles: false,
469     user: res.locals.oauth ? res.locals.oauth.token.User : undefined
470   })
471
472   return res.json(getFormattedObjects(resultList.data, resultList.total))
473 }
474
475 async function removeVideo (req: express.Request, res: express.Response) {
476   const videoInstance = res.locals.video
477
478   await sequelizeTypescript.transaction(async t => {
479     await videoInstance.destroy({ transaction: t })
480   })
481
482   auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
483   logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
484
485   return res.type('json').status(204).end()
486 }