]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Fix concurrency error when deleting a video
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
6fcd19ba 2import * as Promise from 'bluebird'
4d4e5cd4 3import * as multer from 'multer'
93e1258c 4import { extname, join } from 'path'
9f10b292 5
e02643f3 6import { database as db } from '../../../initializers/database'
65fcc311
C
7import {
8 CONFIG,
9 REQUEST_VIDEO_QADU_TYPES,
10 REQUEST_VIDEO_EVENT_TYPES,
11 VIDEO_CATEGORIES,
12 VIDEO_LICENCES,
13 VIDEO_LANGUAGES
14} from '../../../initializers'
15import {
16 addEventToRemoteVideo,
17 quickAndDirtyUpdateVideoToFriends,
18 addVideoToFriends,
93e1258c
C
19 updateVideoToFriends,
20 JobScheduler
65fcc311
C
21} from '../../../lib'
22import {
23 authenticate,
24 paginationValidator,
25 videosSortValidator,
26 setVideosSort,
27 setPagination,
28 setVideosSearch,
29 videosUpdateValidator,
30 videosSearchValidator,
31 videosAddValidator,
32 videosGetValidator,
33 videosRemoveValidator
34} from '../../../middlewares'
35import {
36 logger,
65fcc311 37 retryTransactionWrapper,
65fcc311 38 generateRandomString,
0aef76c4 39 getFormattedObjects,
6fcd19ba 40 renamePromise
65fcc311 41} from '../../../helpers'
6fcd19ba 42import { TagInstance } from '../../../models'
4771e000 43import { VideoCreate, VideoUpdate } from '../../../../shared'
65fcc311
C
44
45import { abuseVideoRouter } from './abuse'
46import { blacklistRouter } from './blacklist'
47import { rateVideoRouter } from './rate'
91f6f169 48import { VideoInstance } from '../../../models/video/video-interface'
65fcc311
C
49
50const videosRouter = express.Router()
9f10b292
C
51
52// multer configuration
f0f5567b 53const storage = multer.diskStorage({
075f16ca 54 destination: (req, file, cb) => {
65fcc311 55 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
56 },
57
075f16ca 58 filename: (req, file, cb) => {
f0f5567b 59 let extension = ''
9f10b292
C
60 if (file.mimetype === 'video/webm') extension = 'webm'
61 else if (file.mimetype === 'video/mp4') extension = 'mp4'
62 else if (file.mimetype === 'video/ogg') extension = 'ogv'
6fcd19ba
C
63 generateRandomString(16)
64 .then(randomString => {
556ddc31 65 cb(null, randomString + '.' + extension)
6fcd19ba
C
66 })
67 .catch(err => {
ad0997ad 68 logger.error('Cannot generate random string for file name.', err)
6fcd19ba
C
69 throw err
70 })
9f10b292
C
71 }
72})
73
8c9c1942 74const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 75
65fcc311
C
76videosRouter.use('/', abuseVideoRouter)
77videosRouter.use('/', blacklistRouter)
78videosRouter.use('/', rateVideoRouter)
d33242b0 79
65fcc311
C
80videosRouter.get('/categories', listVideoCategories)
81videosRouter.get('/licences', listVideoLicences)
82videosRouter.get('/languages', listVideoLanguages)
6e07c3de 83
65fcc311
C
84videosRouter.get('/',
85 paginationValidator,
86 videosSortValidator,
87 setVideosSort,
88 setPagination,
fbf1134e
C
89 listVideos
90)
65fcc311
C
91videosRouter.put('/:id',
92 authenticate,
65fcc311 93 videosUpdateValidator,
ed04d94f 94 updateVideoRetryWrapper
7b1f49de 95)
e95561cd 96videosRouter.post('/upload',
65fcc311 97 authenticate,
fbf1134e 98 reqFiles,
65fcc311 99 videosAddValidator,
ed04d94f 100 addVideoRetryWrapper
fbf1134e 101)
65fcc311
C
102videosRouter.get('/:id',
103 videosGetValidator,
68ce3ae0 104 getVideo
fbf1134e 105)
198b205c 106
65fcc311
C
107videosRouter.delete('/:id',
108 authenticate,
109 videosRemoveValidator,
91f6f169 110 removeVideoRetryWrapper
fbf1134e 111)
198b205c 112
65fcc311
C
113videosRouter.get('/search/:value',
114 videosSearchValidator,
115 paginationValidator,
116 videosSortValidator,
117 setVideosSort,
118 setPagination,
119 setVideosSearch,
fbf1134e
C
120 searchVideos
121)
8c308c2b 122
9f10b292 123// ---------------------------------------------------------------------------
c45f7f84 124
65fcc311
C
125export {
126 videosRouter
127}
c45f7f84 128
9f10b292 129// ---------------------------------------------------------------------------
c45f7f84 130
556ddc31 131function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 132 res.json(VIDEO_CATEGORIES)
6e07c3de
C
133}
134
556ddc31 135function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 136 res.json(VIDEO_LICENCES)
6f0c39e2
C
137}
138
556ddc31 139function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 140 res.json(VIDEO_LANGUAGES)
3092476e
C
141}
142
ed04d94f
C
143// Wrapper to video add that retry the function if there is a database error
144// We need this because we run the transaction in SERIALIZABLE isolation that can fail
69818c93 145function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 146 const options = {
556ddc31 147 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
148 errorMessage: 'Cannot insert the video with many retries.'
149 }
ed04d94f 150
6fcd19ba
C
151 retryTransactionWrapper(addVideo, options)
152 .then(() => {
153 // TODO : include Location of the new video -> 201
154 res.type('json').status(204).end()
155 })
156 .catch(err => next(err))
ed04d94f
C
157}
158
93e1258c 159function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 160 const videoInfo: VideoCreate = req.body
6d33593a 161 let videoUUID = ''
9f10b292 162
6fcd19ba
C
163 return db.sequelize.transaction(t => {
164 const user = res.locals.oauth.token.User
7920c273 165
6fcd19ba
C
166 const name = user.username
167 // null because it is OUR pod
168 const podId = null
169 const userId = user.id
feb4bdfd 170
6fcd19ba
C
171 return db.Author.findOrCreateAuthor(name, podId, userId, t)
172 .then(author => {
556ddc31 173 const tags = videoInfo.tags
6fcd19ba 174 if (!tags) return { author, tagInstances: undefined }
4712081f 175
6fcd19ba 176 return db.Tag.findOrCreateTags(tags, t).then(tagInstances => ({ author, tagInstances }))
7920c273 177 })
6fcd19ba
C
178 .then(({ author, tagInstances }) => {
179 const videoData = {
556ddc31 180 name: videoInfo.name,
0a6658fd 181 remote: false,
93e1258c 182 extname: extname(videoPhysicalFile.filename),
556ddc31
C
183 category: videoInfo.category,
184 licence: videoInfo.licence,
185 language: videoInfo.language,
186 nsfw: videoInfo.nsfw,
187 description: videoInfo.description,
93e1258c 188 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
6fcd19ba
C
189 authorId: author.id
190 }
191
192 const video = db.Video.build(videoData)
193 return { author, tagInstances, video }
feb4bdfd 194 })
6fcd19ba 195 .then(({ author, tagInstances, video }) => {
93e1258c
C
196 const videoFileData = {
197 extname: extname(videoPhysicalFile.filename),
198 resolution: 0, // TODO: improve readability,
199 size: videoPhysicalFile.size
200 }
201
202 const videoFile = db.VideoFile.build(videoFileData)
203 return { author, tagInstances, video, videoFile }
204 })
205 .then(({ author, tagInstances, video, videoFile }) => {
6fcd19ba 206 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
93e1258c
C
207 const source = join(videoDir, videoPhysicalFile.filename)
208 const destination = join(videoDir, video.getVideoFilename(videoFile))
6fcd19ba
C
209
210 return renamePromise(source, destination)
211 .then(() => {
212 // This is important in case if there is another attempt in the retry process
93e1258c
C
213 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
214 return { author, tagInstances, video, videoFile }
6fcd19ba 215 })
558d7c23 216 })
93e1258c
C
217 .then(({ author, tagInstances, video, videoFile }) => {
218 const tasks = []
219
220 tasks.push(
221 video.createTorrentAndSetInfoHash(videoFile),
222 video.createThumbnail(videoFile),
223 video.createPreview(videoFile)
224 )
225
226 if (CONFIG.TRANSCODING.ENABLED === true) {
227 // Put uuid because we don't have id auto incremented for now
228 const dataInput = {
229 videoUUID: video.uuid
230 }
231
232 tasks.push(
233 JobScheduler.Instance.createJob(t, 'videoTranscoder', dataInput)
234 )
235 }
236
237 return Promise.all(tasks).then(() => ({ author, tagInstances, video, videoFile }))
238 })
239 .then(({ author, tagInstances, video, videoFile }) => {
6fcd19ba 240 const options = { transaction: t }
7920c273 241
6fcd19ba
C
242 return video.save(options)
243 .then(videoCreated => {
556ddc31 244 // Do not forget to add Author information to the created video
6fcd19ba 245 videoCreated.Author = author
6d33593a 246 videoUUID = videoCreated.uuid
feb4bdfd 247
93e1258c 248 return { tagInstances, video: videoCreated, videoFile }
6fcd19ba 249 })
3a8a8b51 250 })
93e1258c
C
251 .then(({ tagInstances, video, videoFile }) => {
252 const options = { transaction: t }
253 videoFile.videoId = video.id
254
255 return videoFile.save(options)
256 .then(() => video.VideoFiles = [ videoFile ])
257 .then(() => ({ tagInstances, video }))
258 })
6fcd19ba
C
259 .then(({ tagInstances, video }) => {
260 if (!tagInstances) return video
7920c273 261
6fcd19ba
C
262 const options = { transaction: t }
263 return video.setTags(tagInstances, options)
264 .then(() => {
265 video.Tags = tagInstances
266 return video
267 })
7920c273 268 })
6fcd19ba 269 .then(video => {
556ddc31 270 // Let transcoding job send the video to friends because the video file extension might change
6fcd19ba
C
271 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
272
273 return video.toAddRemoteJSON()
274 .then(remoteVideo => {
275 // Now we'll add the video's meta data to our friends
276 return addVideoToFriends(remoteVideo, t)
277 })
528a9efa 278 })
6fcd19ba 279 })
6d33593a 280 .then(() => logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID))
6fcd19ba 281 .catch((err: Error) => {
93e1258c 282 logger.debug('Cannot insert the video.', err)
6fcd19ba 283 throw err
7b1f49de
C
284 })
285}
286
69818c93 287function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
288 const options = {
289 arguments: [ req, res ],
290 errorMessage: 'Cannot update the video with many retries.'
291 }
ed04d94f 292
6fcd19ba
C
293 retryTransactionWrapper(updateVideo, options)
294 .then(() => {
6fcd19ba
C
295 return res.type('json').status(204).end()
296 })
297 .catch(err => next(err))
ed04d94f
C
298}
299
6fcd19ba 300function updateVideo (req: express.Request, res: express.Response) {
818f7987 301 const videoInstance = res.locals.video
7f4e7c36 302 const videoFieldsSave = videoInstance.toJSON()
556ddc31 303 const videoInfoToUpdate: VideoUpdate = req.body
7b1f49de 304
6fcd19ba
C
305 return db.sequelize.transaction(t => {
306 let tagsPromise: Promise<TagInstance[]>
556ddc31 307 if (!videoInfoToUpdate.tags) {
6fcd19ba
C
308 tagsPromise = Promise.resolve(null)
309 } else {
556ddc31 310 tagsPromise = db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
6fcd19ba 311 }
7b1f49de 312
6fcd19ba
C
313 return tagsPromise
314 .then(tagInstances => {
315 const options = {
316 transaction: t
317 }
7b1f49de 318
556ddc31
C
319 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
320 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
321 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
322 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
323 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
324 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
7b1f49de 325
6fcd19ba 326 return videoInstance.save(options).then(() => tagInstances)
ed04d94f 327 })
6fcd19ba
C
328 .then(tagInstances => {
329 if (!tagInstances) return
7b1f49de 330
6fcd19ba
C
331 const options = { transaction: t }
332 return videoInstance.setTags(tagInstances, options)
333 .then(() => {
334 videoInstance.Tags = tagInstances
7920c273 335
6fcd19ba
C
336 return
337 })
7f4e7c36 338 })
6fcd19ba
C
339 .then(() => {
340 const json = videoInstance.toUpdateRemoteJSON()
7f4e7c36 341
6fcd19ba
C
342 // Now we'll update the video's meta data to our friends
343 return updateVideoToFriends(json, t)
344 })
345 })
346 .then(() => {
6d33593a 347 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
6fcd19ba
C
348 })
349 .catch(err => {
ad0997ad 350 logger.debug('Cannot update the video.', err)
6fcd19ba
C
351
352 // Force fields we want to update
353 // If the transaction is retried, sequelize will think the object has not changed
354 // So it will skip the SQL request, even if the last one was ROLLBACKed!
075f16ca 355 Object.keys(videoFieldsSave).forEach(key => {
6fcd19ba
C
356 const value = videoFieldsSave[key]
357 videoInstance.set(key, value)
358 })
359
360 throw err
9f10b292
C
361 })
362}
8c308c2b 363
556ddc31 364function getVideo (req: express.Request, res: express.Response) {
818f7987 365 const videoInstance = res.locals.video
9e167724
C
366
367 if (videoInstance.isOwned()) {
368 // The increment is done directly in the database, not using the instance value
6fcd19ba
C
369 videoInstance.increment('views')
370 .then(() => {
371 // FIXME: make a real view system
372 // For example, only add a view when a user watch a video during 30s etc
373 const qaduParams = {
374 videoId: videoInstance.id,
375 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
376 }
377 return quickAndDirtyUpdateVideoToFriends(qaduParams)
378 })
ad0997ad 379 .catch(err => logger.error('Cannot add view to video %d.', videoInstance.id, err))
e4c87ec2
C
380 } else {
381 // Just send the event to our friends
d38b8281
C
382 const eventParams = {
383 videoId: videoInstance.id,
65fcc311 384 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
d38b8281 385 }
65fcc311 386 addEventToRemoteVideo(eventParams)
9e167724
C
387 }
388
389 // Do not wait the view system
0aef76c4 390 res.json(videoInstance.toFormattedJSON())
9f10b292 391}
8c308c2b 392
69818c93 393function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
6fcd19ba 394 db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
0aef76c4 395 .then(result => res.json(getFormattedObjects(result.data, result.total)))
6fcd19ba 396 .catch(err => next(err))
9f10b292 397}
c45f7f84 398
91f6f169
C
399function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
400 const options = {
401 arguments: [ req, res ],
402 errorMessage: 'Cannot remove the video with many retries.'
403 }
8c308c2b 404
91f6f169 405 retryTransactionWrapper(removeVideo, options)
6d33593a 406 .then(() => {
91f6f169 407 return res.type('json').status(204).end()
6fcd19ba 408 })
91f6f169
C
409 .catch(err => next(err))
410}
411
412function removeVideo (req: express.Request, res: express.Response) {
413 const videoInstance: VideoInstance = res.locals.video
414
415 return db.sequelize.transaction(t => {
416 return videoInstance.destroy({ transaction: t })
417 })
418 .then(() => {
419 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
420 })
421 .catch(err => {
422 logger.error('Errors when removed the video.', err)
423 throw err
424 })
9f10b292 425}
8c308c2b 426
69818c93 427function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
6fcd19ba 428 db.Video.searchAndPopulateAuthorAndPodAndTags(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort)
0aef76c4 429 .then(result => res.json(getFormattedObjects(result.data, result.total)))
6fcd19ba 430 .catch(err => next(err))
9f10b292 431}