]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
c07430e6c85589a1c71de45f4d05853dbc63f3bb
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { retryTransactionWrapper } from '../../../helpers/database-utils'
6 import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
7 import { processImage } from '../../../helpers/image-utils'
8 import { logger } from '../../../helpers/logger'
9 import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
10 import {
11 CONFIG,
12 IMAGE_MIMETYPE_EXT,
13 PREVIEWS_SIZE,
14 sequelizeTypescript,
15 THUMBNAILS_SIZE,
16 VIDEO_CATEGORIES,
17 VIDEO_LANGUAGES,
18 VIDEO_LICENCES,
19 VIDEO_MIMETYPE_EXT,
20 VIDEO_PRIVACIES
21 } from '../../../initializers'
22 import {
23 changeVideoChannelShare,
24 fetchRemoteVideoDescription,
25 getVideoActivityPubUrl,
26 shareVideoByServerAndChannel
27 } from '../../../lib/activitypub'
28 import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send'
29 import { JobQueue } from '../../../lib/job-queue'
30 import { Redis } from '../../../lib/redis'
31 import {
32 asyncMiddleware,
33 authenticate,
34 optionalAuthenticate,
35 paginationValidator,
36 setDefaultPagination,
37 setDefaultSort,
38 videosAddValidator,
39 videosGetValidator,
40 videosRemoveValidator,
41 videosSearchValidator,
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 { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53 import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
54 import { isNSFWHidden, createReqFiles } from '../../../helpers/express-utils'
55
56 const videosRouter = express.Router()
57
58 const reqVideoFileAdd = createReqFiles(
59 [ 'videofile', 'thumbnailfile', 'previewfile' ],
60 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
61 {
62 videofile: CONFIG.STORAGE.VIDEOS_DIR,
63 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
64 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
65 }
66 )
67 const reqVideoFileUpdate = createReqFiles(
68 [ 'thumbnailfile', 'previewfile' ],
69 IMAGE_MIMETYPE_EXT,
70 {
71 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
72 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
73 }
74 )
75
76 videosRouter.use('/', abuseVideoRouter)
77 videosRouter.use('/', blacklistRouter)
78 videosRouter.use('/', rateVideoRouter)
79 videosRouter.use('/', videoCommentRouter)
80
81 videosRouter.get('/categories', listVideoCategories)
82 videosRouter.get('/licences', listVideoLicences)
83 videosRouter.get('/languages', listVideoLanguages)
84 videosRouter.get('/privacies', listVideoPrivacies)
85
86 videosRouter.get('/',
87 paginationValidator,
88 videosSortValidator,
89 setDefaultSort,
90 setDefaultPagination,
91 optionalAuthenticate,
92 asyncMiddleware(listVideos)
93 )
94 videosRouter.get('/search',
95 videosSearchValidator,
96 paginationValidator,
97 videosSortValidator,
98 setDefaultSort,
99 setDefaultPagination,
100 optionalAuthenticate,
101 asyncMiddleware(searchVideos)
102 )
103 videosRouter.put('/:id',
104 authenticate,
105 reqVideoFileUpdate,
106 asyncMiddleware(videosUpdateValidator),
107 asyncMiddleware(updateVideoRetryWrapper)
108 )
109 videosRouter.post('/upload',
110 authenticate,
111 reqVideoFileAdd,
112 asyncMiddleware(videosAddValidator),
113 asyncMiddleware(addVideoRetryWrapper)
114 )
115
116 videosRouter.get('/:id/description',
117 asyncMiddleware(videosGetValidator),
118 asyncMiddleware(getVideoDescription)
119 )
120 videosRouter.get('/:id',
121 asyncMiddleware(videosGetValidator),
122 getVideo
123 )
124 videosRouter.post('/:id/views',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(viewVideo)
127 )
128
129 videosRouter.delete('/:id',
130 authenticate,
131 asyncMiddleware(videosRemoveValidator),
132 asyncMiddleware(removeVideoRetryWrapper)
133 )
134
135 // ---------------------------------------------------------------------------
136
137 export {
138 videosRouter
139 }
140
141 // ---------------------------------------------------------------------------
142
143 function listVideoCategories (req: express.Request, res: express.Response) {
144 res.json(VIDEO_CATEGORIES)
145 }
146
147 function listVideoLicences (req: express.Request, res: express.Response) {
148 res.json(VIDEO_LICENCES)
149 }
150
151 function listVideoLanguages (req: express.Request, res: express.Response) {
152 res.json(VIDEO_LANGUAGES)
153 }
154
155 function listVideoPrivacies (req: express.Request, res: express.Response) {
156 res.json(VIDEO_PRIVACIES)
157 }
158
159 // Wrapper to video add that retry the function if there is a database error
160 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
161 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
162 const options = {
163 arguments: [ req, res, req.files['videofile'][0] ],
164 errorMessage: 'Cannot insert the video with many retries.'
165 }
166
167 const video = await retryTransactionWrapper(addVideo, options)
168
169 res.json({
170 video: {
171 id: video.id,
172 uuid: video.uuid
173 }
174 }).end()
175 }
176
177 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
178 const videoInfo: VideoCreate = req.body
179
180 // Prepare data so we don't block the transaction
181 const videoData = {
182 name: videoInfo.name,
183 remote: false,
184 extname: extname(videoPhysicalFile.filename),
185 category: videoInfo.category,
186 licence: videoInfo.licence,
187 language: videoInfo.language,
188 commentsEnabled: videoInfo.commentsEnabled,
189 nsfw: videoInfo.nsfw,
190 description: videoInfo.description,
191 support: videoInfo.support,
192 privacy: videoInfo.privacy,
193 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
194 channelId: res.locals.videoChannel.id
195 }
196 const video = new VideoModel(videoData)
197 video.url = getVideoActivityPubUrl(video)
198
199 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
200
201 const videoFileData = {
202 extname: extname(videoPhysicalFile.filename),
203 resolution: videoFileResolution,
204 size: videoPhysicalFile.size
205 }
206 const videoFile = new VideoFileModel(videoFileData)
207 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
208 const destination = join(videoDir, video.getVideoFilename(videoFile))
209
210 await renamePromise(videoPhysicalFile.path, destination)
211 // This is important in case if there is another attempt in the retry process
212 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
213 videoPhysicalFile.path = destination
214
215 // Process thumbnail or create it from the video
216 const thumbnailField = req.files['thumbnailfile']
217 if (thumbnailField) {
218 const thumbnailPhysicalFile = thumbnailField[0]
219 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
220 } else {
221 await video.createThumbnail(videoFile)
222 }
223
224 // Process preview or create it from the video
225 const previewField = req.files['previewfile']
226 if (previewField) {
227 const previewPhysicalFile = previewField[0]
228 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
229 } else {
230 await video.createPreview(videoFile)
231 }
232
233 await video.createTorrentAndSetInfoHash(videoFile)
234
235 const videoCreated = await sequelizeTypescript.transaction(async t => {
236 const sequelizeOptions = { transaction: t }
237
238 const videoCreated = await video.save(sequelizeOptions)
239 // Do not forget to add video channel information to the created video
240 videoCreated.VideoChannel = res.locals.videoChannel
241
242 videoFile.videoId = video.id
243 await videoFile.save(sequelizeOptions)
244
245 video.VideoFiles = [ videoFile ]
246
247 if (videoInfo.tags) {
248 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
249
250 await video.$set('Tags', tagInstances, sequelizeOptions)
251 video.Tags = tagInstances
252 }
253
254 // Let transcoding job send the video to friends because the video file extension might change
255 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
256 // Don't send video to remote servers, it is private
257 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
258
259 await sendCreateVideo(video, t)
260 await shareVideoByServerAndChannel(video, t)
261
262 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
263
264 return videoCreated
265 })
266
267 if (CONFIG.TRANSCODING.ENABLED === true) {
268 // Put uuid because we don't have id auto incremented for now
269 const dataInput = {
270 videoUUID: videoCreated.uuid
271 }
272
273 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
274 }
275
276 return videoCreated
277 }
278
279 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
280 const options = {
281 arguments: [ req, res ],
282 errorMessage: 'Cannot update the video with many retries.'
283 }
284
285 await retryTransactionWrapper(updateVideo, options)
286
287 return res.type('json').status(204).end()
288 }
289
290 async function updateVideo (req: express.Request, res: express.Response) {
291 const videoInstance: VideoModel = res.locals.video
292 const videoFieldsSave = videoInstance.toJSON()
293 const videoInfoToUpdate: VideoUpdate = req.body
294 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
295
296 // Process thumbnail or create it from the video
297 if (req.files && req.files['thumbnailfile']) {
298 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
299 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
300 }
301
302 // Process preview or create it from the video
303 if (req.files && req.files['previewfile']) {
304 const previewPhysicalFile = req.files['previewfile'][0]
305 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
306 }
307
308 try {
309 await sequelizeTypescript.transaction(async t => {
310 const sequelizeOptions = {
311 transaction: t
312 }
313 const oldVideoChannel = videoInstance.VideoChannel
314
315 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
316 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
317 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
318 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
319 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
320 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
321 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
322 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
323 if (videoInfoToUpdate.privacy !== undefined) {
324 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
325 videoInstance.set('privacy', newPrivacy)
326
327 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
328 videoInstance.set('publishedAt', new Date())
329 }
330 }
331
332 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
333
334 // Video tags update?
335 if (videoInfoToUpdate.tags) {
336 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
337
338 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
339 videoInstanceUpdated.Tags = tagInstances
340 }
341
342 // Video channel update?
343 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
344 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel)
345 videoInstance.VideoChannel = res.locals.videoChannel
346
347 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
348 }
349
350 // Now we'll update the video's meta data to our friends
351 if (wasPrivateVideo === false) await sendUpdateVideo(videoInstanceUpdated, t)
352
353 // Video is not private anymore, send a create action to remote servers
354 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
355 await sendCreateVideo(videoInstanceUpdated, t)
356 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
357 }
358 })
359
360 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
361 } catch (err) {
362 // Force fields we want to update
363 // If the transaction is retried, sequelize will think the object has not changed
364 // So it will skip the SQL request, even if the last one was ROLLBACKed!
365 resetSequelizeInstance(videoInstance, videoFieldsSave)
366
367 throw err
368 }
369 }
370
371 function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
373
374 return res.json(videoInstance.toFormattedDetailsJSON())
375 }
376
377 async function viewVideo (req: express.Request, res: express.Response) {
378 const videoInstance = res.locals.video
379
380 const ip = req.ip
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
382 if (exists) {
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
385 }
386
387 await videoInstance.increment('views')
388 await Redis.Instance.setView(ip, videoInstance.uuid)
389
390 const serverAccount = await getServerActor()
391
392 await sendCreateView(serverAccount, videoInstance, undefined)
393
394 return res.status(204).end()
395 }
396
397 async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
399 let description = ''
400
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
403 } else {
404 description = await fetchRemoteVideoDescription(videoInstance)
405 }
406
407 return res.json({ description })
408 }
409
410 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
415 hideNSFW: isNSFWHidden(res),
416 filter: req.query.filter as VideoFilter,
417 withFiles: false
418 })
419
420 return res.json(getFormattedObjects(resultList.data, resultList.total))
421 }
422
423 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
424 const options = {
425 arguments: [ req, res ],
426 errorMessage: 'Cannot remove the video with many retries.'
427 }
428
429 await retryTransactionWrapper(removeVideo, options)
430
431 return res.type('json').status(204).end()
432 }
433
434 async function removeVideo (req: express.Request, res: express.Response) {
435 const videoInstance: VideoModel = res.locals.video
436
437 await sequelizeTypescript.transaction(async t => {
438 await videoInstance.destroy({ transaction: t })
439 })
440
441 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
442 }
443
444 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
445 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
446 req.query.search as string,
447 req.query.start as number,
448 req.query.count as number,
449 req.query.sort as VideoSortField,
450 isNSFWHidden(res)
451 )
452
453 return res.json(getFormattedObjects(resultList.data, resultList.total))
454 }