]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
9d9b2b0e19d2acb7083835205aa3698e98d1630b
[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, VideoState, 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 federateVideoIfNeeded,
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl
27 } from '../../../lib/activitypub'
28 import { sendCreateView } 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 { createReqFiles, isNSFWHidden } 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 || false,
189 waitTranscoding: videoInfo.waitTranscoding || false,
190 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
191 nsfw: videoInfo.nsfw || false,
192 description: videoInfo.description,
193 support: videoInfo.support,
194 privacy: videoInfo.privacy,
195 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
196 channelId: res.locals.videoChannel.id
197 }
198 const video = new VideoModel(videoData)
199 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
200
201 // Build the file object
202 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
203 const videoFileData = {
204 extname: extname(videoPhysicalFile.filename),
205 resolution: videoFileResolution,
206 size: videoPhysicalFile.size
207 }
208 const videoFile = new VideoFileModel(videoFileData)
209
210 // Move physical file
211 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
212 const destination = join(videoDir, video.getVideoFilename(videoFile))
213 await renamePromise(videoPhysicalFile.path, destination)
214 // This is important in case if there is another attempt in the retry process
215 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
216 videoPhysicalFile.path = destination
217
218 // Process thumbnail or create it from the video
219 const thumbnailField = req.files['thumbnailfile']
220 if (thumbnailField) {
221 const thumbnailPhysicalFile = thumbnailField[0]
222 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
223 } else {
224 await video.createThumbnail(videoFile)
225 }
226
227 // Process preview or create it from the video
228 const previewField = req.files['previewfile']
229 if (previewField) {
230 const previewPhysicalFile = previewField[0]
231 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
232 } else {
233 await video.createPreview(videoFile)
234 }
235
236 // Create the torrent file
237 await video.createTorrentAndSetInfoHash(videoFile)
238
239 const videoCreated = await sequelizeTypescript.transaction(async t => {
240 const sequelizeOptions = { transaction: t }
241
242 const videoCreated = await video.save(sequelizeOptions)
243 // Do not forget to add video channel information to the created video
244 videoCreated.VideoChannel = res.locals.videoChannel
245
246 videoFile.videoId = video.id
247 await videoFile.save(sequelizeOptions)
248
249 video.VideoFiles = [ videoFile ]
250
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 await federateVideoIfNeeded(video, true, t)
259
260 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
261
262 return videoCreated
263 })
264
265 if (video.state === VideoState.TO_TRANSCODE) {
266 // Put uuid because we don't have id auto incremented for now
267 const dataInput = {
268 videoUUID: videoCreated.uuid,
269 isNewVideo: true
270 }
271
272 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
273 }
274
275 return videoCreated
276 }
277
278 async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
279 const options = {
280 arguments: [ req, res ],
281 errorMessage: 'Cannot update the video with many retries.'
282 }
283
284 await retryTransactionWrapper(updateVideo, options)
285
286 return res.type('json').status(204).end()
287 }
288
289 async function updateVideo (req: express.Request, res: express.Response) {
290 const videoInstance: VideoModel = res.locals.video
291 const videoFieldsSave = videoInstance.toJSON()
292 const videoInfoToUpdate: VideoUpdate = req.body
293 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
294
295 // Process thumbnail or create it from the video
296 if (req.files && req.files['thumbnailfile']) {
297 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
298 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
299 }
300
301 // Process preview or create it from the video
302 if (req.files && req.files['previewfile']) {
303 const previewPhysicalFile = req.files['previewfile'][0]
304 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
305 }
306
307 try {
308 await sequelizeTypescript.transaction(async t => {
309 const sequelizeOptions = {
310 transaction: t
311 }
312 const oldVideoChannel = videoInstance.VideoChannel
313
314 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
315 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
316 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
317 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
318 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
319 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
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 !== undefined) {
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, { transaction: t })
345 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
346
347 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
348 }
349
350 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
351 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo)
352 })
353
354 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
355 } catch (err) {
356 // Force fields we want to update
357 // If the transaction is retried, sequelize will think the object has not changed
358 // So it will skip the SQL request, even if the last one was ROLLBACKed!
359 resetSequelizeInstance(videoInstance, videoFieldsSave)
360
361 throw err
362 }
363 }
364
365 function getVideo (req: express.Request, res: express.Response) {
366 const videoInstance = res.locals.video
367
368 return res.json(videoInstance.toFormattedDetailsJSON())
369 }
370
371 async function viewVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
373
374 const ip = req.ip
375 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
376 if (exists) {
377 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
378 return res.status(204).end()
379 }
380
381 await videoInstance.increment('views')
382 await Redis.Instance.setView(ip, videoInstance.uuid)
383
384 const serverAccount = await getServerActor()
385
386 await sendCreateView(serverAccount, videoInstance, undefined)
387
388 return res.status(204).end()
389 }
390
391 async function getVideoDescription (req: express.Request, res: express.Response) {
392 const videoInstance = res.locals.video
393 let description = ''
394
395 if (videoInstance.isOwned()) {
396 description = videoInstance.description
397 } else {
398 description = await fetchRemoteVideoDescription(videoInstance)
399 }
400
401 return res.json({ description })
402 }
403
404 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
405 const resultList = await VideoModel.listForApi({
406 start: req.query.start,
407 count: req.query.count,
408 sort: req.query.sort,
409 hideNSFW: isNSFWHidden(res),
410 filter: req.query.filter as VideoFilter,
411 withFiles: false
412 })
413
414 return res.json(getFormattedObjects(resultList.data, resultList.total))
415 }
416
417 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
418 const options = {
419 arguments: [ req, res ],
420 errorMessage: 'Cannot remove the video with many retries.'
421 }
422
423 await retryTransactionWrapper(removeVideo, options)
424
425 return res.type('json').status(204).end()
426 }
427
428 async function removeVideo (req: express.Request, res: express.Response) {
429 const videoInstance: VideoModel = res.locals.video
430
431 await sequelizeTypescript.transaction(async t => {
432 await videoInstance.destroy({ transaction: t })
433 })
434
435 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
436 }
437
438 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
439 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
440 req.query.search as string,
441 req.query.start as number,
442 req.query.count as number,
443 req.query.sort as VideoSortField,
444 isNSFWHidden(res)
445 )
446
447 return res.json(getFormattedObjects(resultList.data, resultList.total))
448 }