]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Refractor retry transaction function
[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 { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { getFormattedObjects, getServerActor, resetSequelizeInstance } 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 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 asyncRetryTransactionMiddleware(updateVideo)
108 )
109 videosRouter.post('/upload',
110 authenticate,
111 reqVideoFileAdd,
112 asyncMiddleware(videosAddValidator),
113 asyncRetryTransactionMiddleware(addVideo)
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 asyncRetryTransactionMiddleware(removeVideo)
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 async function addVideo (req: express.Request, res: express.Response) {
160 const videoPhysicalFile = req.files['videofile'][0]
161 const videoInfo: VideoCreate = req.body
162
163 // Prepare data so we don't block the transaction
164 const videoData = {
165 name: videoInfo.name,
166 remote: false,
167 extname: extname(videoPhysicalFile.filename),
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 videoFileData = {
187 extname: extname(videoPhysicalFile.filename),
188 resolution: videoFileResolution,
189 size: videoPhysicalFile.size
190 }
191 const videoFile = new VideoFileModel(videoFileData)
192
193 // Move physical file
194 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
195 const destination = join(videoDir, video.getVideoFilename(videoFile))
196 await renamePromise(videoPhysicalFile.path, destination)
197 // This is important in case if there is another attempt in the retry process
198 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
199 videoPhysicalFile.path = destination
200
201 // Process thumbnail or create it from the video
202 const thumbnailField = req.files['thumbnailfile']
203 if (thumbnailField) {
204 const thumbnailPhysicalFile = thumbnailField[0]
205 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
206 } else {
207 await video.createThumbnail(videoFile)
208 }
209
210 // Process preview or create it from the video
211 const previewField = req.files['previewfile']
212 if (previewField) {
213 const previewPhysicalFile = previewField[0]
214 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
215 } else {
216 await video.createPreview(videoFile)
217 }
218
219 // Create the torrent file
220 await video.createTorrentAndSetInfoHash(videoFile)
221
222 const videoCreated = await sequelizeTypescript.transaction(async t => {
223 const sequelizeOptions = { transaction: t }
224
225 const videoCreated = await video.save(sequelizeOptions)
226 // Do not forget to add video channel information to the created video
227 videoCreated.VideoChannel = res.locals.videoChannel
228
229 videoFile.videoId = video.id
230 await videoFile.save(sequelizeOptions)
231
232 video.VideoFiles = [ videoFile ]
233
234 if (videoInfo.tags !== undefined) {
235 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
236
237 await video.$set('Tags', tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
239 }
240
241 await federateVideoIfNeeded(video, true, t)
242
243 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
244
245 return videoCreated
246 })
247
248 if (video.state === VideoState.TO_TRANSCODE) {
249 // Put uuid because we don't have id auto incremented for now
250 const dataInput = {
251 videoUUID: videoCreated.uuid,
252 isNewVideo: true
253 }
254
255 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
256 }
257
258 return res.json({
259 video: {
260 id: videoCreated.id,
261 uuid: videoCreated.uuid
262 }
263 }).end()
264 }
265
266 async function updateVideo (req: express.Request, res: express.Response) {
267 const videoInstance: VideoModel = res.locals.video
268 const videoFieldsSave = videoInstance.toJSON()
269 const videoInfoToUpdate: VideoUpdate = req.body
270 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
271
272 // Process thumbnail or create it from the video
273 if (req.files && req.files['thumbnailfile']) {
274 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
275 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
276 }
277
278 // Process preview or create it from the video
279 if (req.files && req.files['previewfile']) {
280 const previewPhysicalFile = req.files['previewfile'][0]
281 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
282 }
283
284 try {
285 await sequelizeTypescript.transaction(async t => {
286 const sequelizeOptions = {
287 transaction: t
288 }
289 const oldVideoChannel = videoInstance.VideoChannel
290
291 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
292 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
293 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
294 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
295 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
296 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
297 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
298 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
299 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
300 if (videoInfoToUpdate.privacy !== undefined) {
301 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
302 videoInstance.set('privacy', newPrivacy)
303
304 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
305 videoInstance.set('publishedAt', new Date())
306 }
307 }
308
309 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
310
311 // Video tags update?
312 if (videoInfoToUpdate.tags !== undefined) {
313 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
314
315 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
316 videoInstanceUpdated.Tags = tagInstances
317 }
318
319 // Video channel update?
320 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
321 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
322 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
323
324 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
325 }
326
327 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
328 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo)
329 })
330
331 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
332 } catch (err) {
333 // Force fields we want to update
334 // If the transaction is retried, sequelize will think the object has not changed
335 // So it will skip the SQL request, even if the last one was ROLLBACKed!
336 resetSequelizeInstance(videoInstance, videoFieldsSave)
337
338 throw err
339 }
340
341 return res.type('json').status(204).end()
342 }
343
344 function getVideo (req: express.Request, res: express.Response) {
345 const videoInstance = res.locals.video
346
347 return res.json(videoInstance.toFormattedDetailsJSON())
348 }
349
350 async function viewVideo (req: express.Request, res: express.Response) {
351 const videoInstance = res.locals.video
352
353 const ip = req.ip
354 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
355 if (exists) {
356 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
357 return res.status(204).end()
358 }
359
360 await videoInstance.increment('views')
361 await Redis.Instance.setView(ip, videoInstance.uuid)
362
363 const serverAccount = await getServerActor()
364
365 await sendCreateView(serverAccount, videoInstance, undefined)
366
367 return res.status(204).end()
368 }
369
370 async function getVideoDescription (req: express.Request, res: express.Response) {
371 const videoInstance = res.locals.video
372 let description = ''
373
374 if (videoInstance.isOwned()) {
375 description = videoInstance.description
376 } else {
377 description = await fetchRemoteVideoDescription(videoInstance)
378 }
379
380 return res.json({ description })
381 }
382
383 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
384 const resultList = await VideoModel.listForApi({
385 start: req.query.start,
386 count: req.query.count,
387 sort: req.query.sort,
388 hideNSFW: isNSFWHidden(res),
389 filter: req.query.filter as VideoFilter,
390 withFiles: false
391 })
392
393 return res.json(getFormattedObjects(resultList.data, resultList.total))
394 }
395
396 async function removeVideo (req: express.Request, res: express.Response) {
397 const videoInstance: VideoModel = res.locals.video
398
399 await sequelizeTypescript.transaction(async t => {
400 await videoInstance.destroy({ transaction: t })
401 })
402
403 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
404
405 return res.type('json').status(204).end()
406 }
407
408 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
409 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
410 req.query.search as string,
411 req.query.start as number,
412 req.query.count as number,
413 req.query.sort as VideoSortField,
414 isNSFWHidden(res)
415 )
416
417 return res.json(getFormattedObjects(resultList.data, resultList.total))
418 }