]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos.js
Client: add support for video licences
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos.js
CommitLineData
9f10b292
C
1'use strict'
2
f0f5567b 3const express = require('express')
558d7c23 4const fs = require('fs')
f0f5567b 5const multer = require('multer')
558d7c23 6const path = require('path')
1a42c9e2 7const waterfall = require('async/waterfall')
f0f5567b 8
f253b1c1 9const constants = require('../../initializers/constants')
feb4bdfd 10const db = require('../../initializers/database')
f253b1c1
C
11const logger = require('../../helpers/logger')
12const friends = require('../../lib/friends')
13const middlewares = require('../../middlewares')
55fa55a9 14const admin = middlewares.admin
69b0a27c 15const oAuth = middlewares.oauth
fbf1134e 16const pagination = middlewares.pagination
fc51fde0
C
17const validators = middlewares.validators
18const validatorsPagination = validators.pagination
19const validatorsSort = validators.sort
20const validatorsVideos = validators.videos
46246b5f 21const search = middlewares.search
a877d5ac 22const sort = middlewares.sort
4df023f2 23const databaseUtils = require('../../helpers/database-utils')
f253b1c1 24const utils = require('../../helpers/utils')
f0f5567b
C
25
26const router = express.Router()
9f10b292
C
27
28// multer configuration
f0f5567b 29const storage = multer.diskStorage({
9f10b292 30 destination: function (req, file, cb) {
b3d92510 31 cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
32 },
33
34 filename: function (req, file, cb) {
f0f5567b 35 let extension = ''
9f10b292
C
36 if (file.mimetype === 'video/webm') extension = 'webm'
37 else if (file.mimetype === 'video/mp4') extension = 'mp4'
38 else if (file.mimetype === 'video/ogg') extension = 'ogv'
bc503c2a
C
39 utils.generateRandomString(16, function (err, randomString) {
40 const fieldname = err ? undefined : randomString
9f10b292
C
41 cb(null, fieldname + '.' + extension)
42 })
43 }
44})
45
8c9c1942 46const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 47
6e07c3de 48router.get('/categories', listVideoCategories)
6f0c39e2 49router.get('/licences', listVideoLicences)
6e07c3de 50
55fa55a9
C
51router.get('/abuse',
52 oAuth.authenticate,
53 admin.ensureIsAdmin,
54 validatorsPagination.pagination,
55 validatorsSort.videoAbusesSort,
56 sort.setVideoAbusesSort,
57 pagination.setPagination,
58 listVideoAbuses
59)
60router.post('/:id/abuse',
61 oAuth.authenticate,
62 validatorsVideos.videoAbuseReport,
bf4ff8fe 63 reportVideoAbuseRetryWrapper
55fa55a9
C
64)
65
d38b8281
C
66router.put('/:id/rate',
67 oAuth.authenticate,
68 validatorsVideos.videoRate,
69 rateVideoRetryWrapper
70)
71
fbf1134e 72router.get('/',
fc51fde0
C
73 validatorsPagination.pagination,
74 validatorsSort.videosSort,
a877d5ac 75 sort.setVideosSort,
fbf1134e
C
76 pagination.setPagination,
77 listVideos
78)
7b1f49de
C
79router.put('/:id',
80 oAuth.authenticate,
81 reqFiles,
82 validatorsVideos.videosUpdate,
ed04d94f 83 updateVideoRetryWrapper
7b1f49de 84)
fbf1134e 85router.post('/',
69b0a27c 86 oAuth.authenticate,
fbf1134e 87 reqFiles,
fc51fde0 88 validatorsVideos.videosAdd,
ed04d94f 89 addVideoRetryWrapper
fbf1134e
C
90)
91router.get('/:id',
fc51fde0 92 validatorsVideos.videosGet,
68ce3ae0 93 getVideo
fbf1134e
C
94)
95router.delete('/:id',
69b0a27c 96 oAuth.authenticate,
fc51fde0 97 validatorsVideos.videosRemove,
fbf1134e
C
98 removeVideo
99)
46246b5f 100router.get('/search/:value',
fc51fde0
C
101 validatorsVideos.videosSearch,
102 validatorsPagination.pagination,
103 validatorsSort.videosSort,
a877d5ac 104 sort.setVideosSort,
fbf1134e 105 pagination.setPagination,
46246b5f 106 search.setVideosSearch,
fbf1134e
C
107 searchVideos
108)
8c308c2b 109
9f10b292 110// ---------------------------------------------------------------------------
c45f7f84 111
9f10b292 112module.exports = router
c45f7f84 113
9f10b292 114// ---------------------------------------------------------------------------
c45f7f84 115
6e07c3de
C
116function listVideoCategories (req, res, next) {
117 res.json(constants.VIDEO_CATEGORIES)
118}
119
6f0c39e2
C
120function listVideoLicences (req, res, next) {
121 res.json(constants.VIDEO_LICENCES)
122}
123
d38b8281
C
124function rateVideoRetryWrapper (req, res, next) {
125 const options = {
126 arguments: [ req, res ],
127 errorMessage: 'Cannot update the user video rate.'
128 }
129
130 databaseUtils.retryTransactionWrapper(rateVideo, options, function (err) {
131 if (err) return next(err)
132
133 return res.type('json').status(204).end()
134 })
135}
136
137function rateVideo (req, res, finalCallback) {
138 const rateType = req.body.rating
139 const videoInstance = res.locals.video
140 const userInstance = res.locals.oauth.token.User
141
142 waterfall([
143 databaseUtils.startSerializableTransaction,
144
145 function findPreviousRate (t, callback) {
146 db.UserVideoRate.load(userInstance.id, videoInstance.id, t, function (err, previousRate) {
147 return callback(err, t, previousRate)
148 })
149 },
150
151 function insertUserRateIntoDB (t, previousRate, callback) {
152 const options = { transaction: t }
153
154 let likesToIncrement = 0
155 let dislikesToIncrement = 0
156
157 if (rateType === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement++
158 else if (rateType === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement++
159
160 // There was a previous rate, update it
161 if (previousRate) {
162 // We will remove the previous rate, so we will need to remove it from the video attribute
163 if (previousRate.type === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement--
164 else if (previousRate.type === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement--
165
166 previousRate.type = rateType
167
168 previousRate.save(options).asCallback(function (err) {
169 return callback(err, t, likesToIncrement, dislikesToIncrement)
170 })
171 } else { // There was not a previous rate, insert a new one
172 const query = {
173 userId: userInstance.id,
174 videoId: videoInstance.id,
175 type: rateType
176 }
177
178 db.UserVideoRate.create(query, options).asCallback(function (err) {
179 return callback(err, t, likesToIncrement, dislikesToIncrement)
180 })
181 }
182 },
183
184 function updateVideoAttributeDB (t, likesToIncrement, dislikesToIncrement, callback) {
185 const options = { transaction: t }
186 const incrementQuery = {
187 likes: likesToIncrement,
188 dislikes: dislikesToIncrement
189 }
190
191 // Even if we do not own the video we increment the attributes
192 // It is usefull for the user to have a feedback
193 videoInstance.increment(incrementQuery, options).asCallback(function (err) {
194 return callback(err, t, likesToIncrement, dislikesToIncrement)
195 })
196 },
197
198 function sendEventsToFriendsIfNeeded (t, likesToIncrement, dislikesToIncrement, callback) {
199 // No need for an event type, we own the video
200 if (videoInstance.isOwned()) return callback(null, t, likesToIncrement, dislikesToIncrement)
201
202 const eventsParams = []
203
204 if (likesToIncrement !== 0) {
205 eventsParams.push({
206 videoId: videoInstance.id,
207 type: constants.REQUEST_VIDEO_EVENT_TYPES.LIKES,
208 count: likesToIncrement
209 })
210 }
211
212 if (dislikesToIncrement !== 0) {
213 eventsParams.push({
214 videoId: videoInstance.id,
215 type: constants.REQUEST_VIDEO_EVENT_TYPES.DISLIKES,
216 count: dislikesToIncrement
217 })
218 }
219
220 friends.addEventsToRemoteVideo(eventsParams, t, function (err) {
221 return callback(err, t, likesToIncrement, dislikesToIncrement)
222 })
223 },
224
225 function sendQaduToFriendsIfNeeded (t, likesToIncrement, dislikesToIncrement, callback) {
226 // We do not own the video, there is no need to send a quick and dirty update to friends
227 // Our rate was already sent by the addEvent function
228 if (videoInstance.isOwned() === false) return callback(null, t)
229
230 const qadusParams = []
231
232 if (likesToIncrement !== 0) {
233 qadusParams.push({
234 videoId: videoInstance.id,
235 type: constants.REQUEST_VIDEO_QADU_TYPES.LIKES
236 })
237 }
238
239 if (dislikesToIncrement !== 0) {
240 qadusParams.push({
241 videoId: videoInstance.id,
242 type: constants.REQUEST_VIDEO_QADU_TYPES.DISLIKES
243 })
244 }
245
246 friends.quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) {
247 return callback(err, t)
248 })
249 },
250
251 databaseUtils.commitTransaction
252
253 ], function (err, t) {
254 if (err) {
255 // This is just a debug because we will retry the insert
256 logger.debug('Cannot add the user video rate.', { error: err })
257 return databaseUtils.rollbackTransaction(err, t, finalCallback)
258 }
259
260 logger.info('User video rate for video %s of user %s updated.', videoInstance.name, userInstance.username)
261 return finalCallback(null)
262 })
263}
264
ed04d94f
C
265// Wrapper to video add that retry the function if there is a database error
266// We need this because we run the transaction in SERIALIZABLE isolation that can fail
267function addVideoRetryWrapper (req, res, next) {
d6a5b018
C
268 const options = {
269 arguments: [ req, res, req.files.videofile[0] ],
270 errorMessage: 'Cannot insert the video with many retries.'
271 }
ed04d94f 272
4df023f2 273 databaseUtils.retryTransactionWrapper(addVideo, options, function (err) {
d6a5b018
C
274 if (err) return next(err)
275
276 // TODO : include Location of the new video -> 201
277 return res.type('json').status(204).end()
278 })
ed04d94f
C
279}
280
4145c1c6 281function addVideo (req, res, videoFile, finalCallback) {
bc503c2a 282 const videoInfos = req.body
9f10b292 283
1a42c9e2 284 waterfall([
807df9e6 285
4df023f2 286 databaseUtils.startSerializableTransaction,
7920c273 287
4145c1c6 288 function findOrCreateAuthor (t, callback) {
4712081f 289 const user = res.locals.oauth.token.User
feb4bdfd 290
4ff0d862
C
291 const name = user.username
292 // null because it is OUR pod
293 const podId = null
294 const userId = user.id
4712081f 295
4ff0d862 296 db.Author.findOrCreateAuthor(name, podId, userId, t, function (err, authorInstance) {
4145c1c6 297 return callback(err, t, authorInstance)
7920c273
C
298 })
299 },
300
4145c1c6 301 function findOrCreateTags (t, author, callback) {
7920c273 302 const tags = videoInfos.tags
4ff0d862
C
303
304 db.Tag.findOrCreateTags(tags, t, function (err, tagInstances) {
4145c1c6 305 return callback(err, t, author, tagInstances)
feb4bdfd
C
306 })
307 },
308
4145c1c6 309 function createVideoObject (t, author, tagInstances, callback) {
807df9e6
C
310 const videoData = {
311 name: videoInfos.name,
558d7c23
C
312 remoteId: null,
313 extname: path.extname(videoFile.filename),
6e07c3de 314 category: videoInfos.category,
6f0c39e2 315 licence: videoInfos.licence,
807df9e6 316 description: videoInfos.description,
67100f1f 317 duration: videoFile.duration,
d38b8281 318 authorId: author.id
807df9e6
C
319 }
320
feb4bdfd 321 const video = db.Video.build(videoData)
558d7c23 322
4145c1c6 323 return callback(null, t, author, tagInstances, video)
558d7c23
C
324 },
325
feb4bdfd 326 // Set the videoname the same as the id
4145c1c6 327 function renameVideoFile (t, author, tagInstances, video, callback) {
558d7c23
C
328 const videoDir = constants.CONFIG.STORAGE.VIDEOS_DIR
329 const source = path.join(videoDir, videoFile.filename)
f285faa0 330 const destination = path.join(videoDir, video.getVideoFilename())
558d7c23
C
331
332 fs.rename(source, destination, function (err) {
4145c1c6 333 if (err) return callback(err)
ed04d94f
C
334
335 // This is important in case if there is another attempt
336 videoFile.filename = video.getVideoFilename()
4145c1c6 337 return callback(null, t, author, tagInstances, video)
558d7c23
C
338 })
339 },
340
4145c1c6 341 function insertVideoIntoDB (t, author, tagInstances, video, callback) {
7920c273
C
342 const options = { transaction: t }
343
344 // Add tags association
345 video.save(options).asCallback(function (err, videoCreated) {
4145c1c6 346 if (err) return callback(err)
7920c273 347
feb4bdfd
C
348 // Do not forget to add Author informations to the created video
349 videoCreated.Author = author
350
4145c1c6 351 return callback(err, t, tagInstances, videoCreated)
3a8a8b51 352 })
807df9e6
C
353 },
354
4145c1c6 355 function associateTagsToVideo (t, tagInstances, video, callback) {
7920c273
C
356 const options = { transaction: t }
357
358 video.setTags(tagInstances, options).asCallback(function (err) {
359 video.Tags = tagInstances
360
4145c1c6 361 return callback(err, t, video)
7920c273
C
362 })
363 },
364
4145c1c6 365 function sendToFriends (t, video, callback) {
7b1f49de 366 video.toAddRemoteJSON(function (err, remoteVideo) {
4145c1c6 367 if (err) return callback(err)
807df9e6 368
528a9efa 369 // Now we'll add the video's meta data to our friends
ed04d94f 370 friends.addVideoToFriends(remoteVideo, t, function (err) {
4145c1c6 371 return callback(err, t)
ed04d94f 372 })
528a9efa 373 })
4145c1c6
C
374 },
375
376 databaseUtils.commitTransaction
807df9e6 377
7b1f49de
C
378 ], function andFinally (err, t) {
379 if (err) {
ed04d94f
C
380 // This is just a debug because we will retry the insert
381 logger.debug('Cannot insert the video.', { error: err })
4145c1c6 382 return databaseUtils.rollbackTransaction(err, t, finalCallback)
7b1f49de
C
383 }
384
4145c1c6
C
385 logger.info('Video with name %s created.', videoInfos.name)
386 return finalCallback(null)
7b1f49de
C
387 })
388}
389
ed04d94f 390function updateVideoRetryWrapper (req, res, next) {
d6a5b018
C
391 const options = {
392 arguments: [ req, res ],
393 errorMessage: 'Cannot update the video with many retries.'
394 }
ed04d94f 395
4df023f2 396 databaseUtils.retryTransactionWrapper(updateVideo, options, function (err) {
d6a5b018
C
397 if (err) return next(err)
398
399 // TODO : include Location of the new video -> 201
400 return res.type('json').status(204).end()
401 })
ed04d94f
C
402}
403
404function updateVideo (req, res, finalCallback) {
818f7987 405 const videoInstance = res.locals.video
7f4e7c36 406 const videoFieldsSave = videoInstance.toJSON()
7b1f49de
C
407 const videoInfosToUpdate = req.body
408
409 waterfall([
410
4df023f2 411 databaseUtils.startSerializableTransaction,
7b1f49de
C
412
413 function findOrCreateTags (t, callback) {
414 if (videoInfosToUpdate.tags) {
415 db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t, function (err, tagInstances) {
416 return callback(err, t, tagInstances)
417 })
418 } else {
419 return callback(null, t, null)
420 }
421 },
422
423 function updateVideoIntoDB (t, tagInstances, callback) {
7f4e7c36
C
424 const options = {
425 transaction: t
426 }
7b1f49de
C
427
428 if (videoInfosToUpdate.name) videoInstance.set('name', videoInfosToUpdate.name)
6e07c3de 429 if (videoInfosToUpdate.category) videoInstance.set('category', videoInfosToUpdate.category)
6f0c39e2 430 if (videoInfosToUpdate.licence) videoInstance.set('licence', videoInfosToUpdate.licence)
7b1f49de
C
431 if (videoInfosToUpdate.description) videoInstance.set('description', videoInfosToUpdate.description)
432
7b1f49de 433 videoInstance.save(options).asCallback(function (err) {
7b1f49de
C
434 return callback(err, t, tagInstances)
435 })
436 },
437
438 function associateTagsToVideo (t, tagInstances, callback) {
439 if (tagInstances) {
440 const options = { transaction: t }
441
442 videoInstance.setTags(tagInstances, options).asCallback(function (err) {
443 videoInstance.Tags = tagInstances
444
445 return callback(err, t)
446 })
447 } else {
448 return callback(null, t)
449 }
450 },
451
452 function sendToFriends (t, callback) {
453 const json = videoInstance.toUpdateRemoteJSON()
454
455 // Now we'll update the video's meta data to our friends
ed04d94f
C
456 friends.updateVideoToFriends(json, t, function (err) {
457 return callback(err, t)
458 })
4145c1c6
C
459 },
460
461 databaseUtils.commitTransaction
7b1f49de 462
7920c273 463 ], function andFinally (err, t) {
807df9e6 464 if (err) {
ed04d94f 465 logger.debug('Cannot update the video.', { error: err })
7920c273 466
7f4e7c36
C
467 // Force fields we want to update
468 // If the transaction is retried, sequelize will think the object has not changed
469 // So it will skip the SQL request, even if the last one was ROLLBACKed!
470 Object.keys(videoFieldsSave).forEach(function (key) {
471 const value = videoFieldsSave[key]
472 videoInstance.set(key, value)
473 })
474
4145c1c6 475 return databaseUtils.rollbackTransaction(err, t, finalCallback)
807df9e6
C
476 }
477
4145c1c6
C
478 logger.info('Video with name %s updated.', videoInfosToUpdate.name)
479 return finalCallback(null)
9f10b292
C
480 })
481}
8c308c2b 482
68ce3ae0 483function getVideo (req, res, next) {
818f7987 484 const videoInstance = res.locals.video
9e167724
C
485
486 if (videoInstance.isOwned()) {
487 // The increment is done directly in the database, not using the instance value
488 videoInstance.increment('views').asCallback(function (err) {
489 if (err) {
490 logger.error('Cannot add view to video %d.', videoInstance.id)
491 return
492 }
493
494 // FIXME: make a real view system
495 // For example, only add a view when a user watch a video during 30s etc
d38b8281
C
496 const qaduParams = {
497 videoId: videoInstance.id,
498 type: constants.REQUEST_VIDEO_QADU_TYPES.VIEWS
499 }
500 friends.quickAndDirtyUpdateVideoToFriends(qaduParams)
9e167724 501 })
e4c87ec2
C
502 } else {
503 // Just send the event to our friends
d38b8281
C
504 const eventParams = {
505 videoId: videoInstance.id,
506 type: constants.REQUEST_VIDEO_EVENT_TYPES.VIEWS
507 }
508 friends.addEventToRemoteVideo(eventParams)
9e167724
C
509 }
510
511 // Do not wait the view system
818f7987 512 res.json(videoInstance.toFormatedJSON())
9f10b292 513}
8c308c2b 514
9f10b292 515function listVideos (req, res, next) {
feb4bdfd 516 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
9f10b292 517 if (err) return next(err)
c45f7f84 518
55fa55a9 519 res.json(utils.getFormatedObjects(videosList, videosTotal))
9f10b292
C
520 })
521}
c45f7f84 522
9f10b292 523function removeVideo (req, res, next) {
818f7987 524 const videoInstance = res.locals.video
8c308c2b 525
818f7987 526 videoInstance.destroy().asCallback(function (err) {
807df9e6
C
527 if (err) {
528 logger.error('Errors when removed the video.', { error: err })
529 return next(err)
530 }
531
532 return res.type('json').status(204).end()
9f10b292
C
533 })
534}
8c308c2b 535
9f10b292 536function searchVideos (req, res, next) {
7920c273
C
537 db.Video.searchAndPopulateAuthorAndPodAndTags(
538 req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
539 function (err, videosList, videosTotal) {
540 if (err) return next(err)
8c308c2b 541
55fa55a9 542 res.json(utils.getFormatedObjects(videosList, videosTotal))
7920c273
C
543 }
544 )
9f10b292 545}
c173e565 546
55fa55a9
C
547function listVideoAbuses (req, res, next) {
548 db.VideoAbuse.listForApi(req.query.start, req.query.count, req.query.sort, function (err, abusesList, abusesTotal) {
549 if (err) return next(err)
2df82d42 550
55fa55a9 551 res.json(utils.getFormatedObjects(abusesList, abusesTotal))
2df82d42 552 })
55fa55a9 553}
2df82d42 554
bf4ff8fe 555function reportVideoAbuseRetryWrapper (req, res, next) {
4df023f2
C
556 const options = {
557 arguments: [ req, res ],
558 errorMessage: 'Cannot report abuse to the video with many retries.'
559 }
bf4ff8fe 560
4df023f2
C
561 databaseUtils.retryTransactionWrapper(reportVideoAbuse, options, function (err) {
562 if (err) return next(err)
563
564 return res.type('json').status(204).end()
565 })
bf4ff8fe
C
566}
567
568function reportVideoAbuse (req, res, finalCallback) {
55fa55a9
C
569 const videoInstance = res.locals.video
570 const reporterUsername = res.locals.oauth.token.User.username
571
572 const abuse = {
573 reporterUsername,
574 reason: req.body.reason,
575 videoId: videoInstance.id,
576 reporterPodId: null // This is our pod that reported this abuse
68ce3ae0 577 }
55fa55a9 578
bf4ff8fe
C
579 waterfall([
580
da691c46 581 databaseUtils.startSerializableTransaction,
bf4ff8fe
C
582
583 function createAbuse (t, callback) {
584 db.VideoAbuse.create(abuse).asCallback(function (err, abuse) {
585 return callback(err, t, abuse)
586 })
587 },
588
589 function sendToFriendsIfNeeded (t, abuse, callback) {
590 // We send the information to the destination pod
591 if (videoInstance.isOwned() === false) {
592 const reportData = {
593 reporterUsername,
594 reportReason: abuse.reason,
595 videoRemoteId: videoInstance.remoteId
596 }
55fa55a9 597
bf4ff8fe 598 friends.reportAbuseVideoToFriend(reportData, videoInstance)
55fa55a9
C
599 }
600
bf4ff8fe 601 return callback(null, t)
4145c1c6
C
602 },
603
604 databaseUtils.commitTransaction
55fa55a9 605
bf4ff8fe
C
606 ], function andFinally (err, t) {
607 if (err) {
608 logger.debug('Cannot update the video.', { error: err })
4145c1c6 609 return databaseUtils.rollbackTransaction(err, t, finalCallback)
bf4ff8fe
C
610 }
611
4145c1c6
C
612 logger.info('Abuse report for video %s created.', videoInstance.name)
613 return finalCallback(null)
55fa55a9 614 })
2df82d42 615}