1
0
Fork 0
peertube/server/controllers/api/videos.js

618 lines
18 KiB
JavaScript
Raw Normal View History

'use strict'
2016-03-16 21:29:27 +00:00
const express = require('express')
const fs = require('fs')
2016-03-16 21:29:27 +00:00
const multer = require('multer')
const path = require('path')
2016-07-18 15:17:52 +00:00
const waterfall = require('async/waterfall')
2016-03-16 21:29:27 +00:00
const constants = require('../../initializers/constants')
2016-12-11 20:50:51 +00:00
const db = require('../../initializers/database')
const logger = require('../../helpers/logger')
const friends = require('../../lib/friends')
const middlewares = require('../../middlewares')
2017-01-04 19:59:23 +00:00
const admin = middlewares.admin
const oAuth = middlewares.oauth
const pagination = middlewares.pagination
2016-07-01 14:16:40 +00:00
const validators = middlewares.validators
const validatorsPagination = validators.pagination
const validatorsSort = validators.sort
const validatorsVideos = validators.videos
const search = middlewares.search
2016-05-17 19:03:00 +00:00
const sort = middlewares.sort
const databaseUtils = require('../../helpers/database-utils')
const utils = require('../../helpers/utils')
2016-03-16 21:29:27 +00:00
const router = express.Router()
// multer configuration
2016-03-16 21:29:27 +00:00
const storage = multer.diskStorage({
destination: function (req, file, cb) {
2016-10-21 09:33:31 +00:00
cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR)
},
filename: function (req, file, cb) {
2016-03-16 21:29:27 +00:00
let extension = ''
if (file.mimetype === 'video/webm') extension = 'webm'
else if (file.mimetype === 'video/mp4') extension = 'mp4'
else if (file.mimetype === 'video/ogg') extension = 'ogv'
utils.generateRandomString(16, function (err, randomString) {
const fieldname = err ? undefined : randomString
cb(null, fieldname + '.' + extension)
})
}
})
const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
2015-06-09 15:41:40 +00:00
2017-03-22 20:15:55 +00:00
router.get('/categories', listVideoCategories)
2017-03-27 18:53:11 +00:00
router.get('/licences', listVideoLicences)
2017-03-22 20:15:55 +00:00
2017-01-04 19:59:23 +00:00
router.get('/abuse',
oAuth.authenticate,
admin.ensureIsAdmin,
validatorsPagination.pagination,
validatorsSort.videoAbusesSort,
sort.setVideoAbusesSort,
pagination.setPagination,
listVideoAbuses
)
router.post('/:id/abuse',
oAuth.authenticate,
validatorsVideos.videoAbuseReport,
2017-01-10 21:33:00 +00:00
reportVideoAbuseRetryWrapper
2017-01-04 19:59:23 +00:00
)
2017-03-08 20:35:43 +00:00
router.put('/:id/rate',
oAuth.authenticate,
validatorsVideos.videoRate,
rateVideoRetryWrapper
)
router.get('/',
2016-07-01 14:16:40 +00:00
validatorsPagination.pagination,
validatorsSort.videosSort,
2016-05-17 19:03:00 +00:00
sort.setVideosSort,
pagination.setPagination,
listVideos
)
2016-12-29 18:07:05 +00:00
router.put('/:id',
oAuth.authenticate,
reqFiles,
validatorsVideos.videosUpdate,
updateVideoRetryWrapper
2016-12-29 18:07:05 +00:00
)
router.post('/',
oAuth.authenticate,
reqFiles,
2016-07-01 14:16:40 +00:00
validatorsVideos.videosAdd,
addVideoRetryWrapper
)
router.get('/:id',
2016-07-01 14:16:40 +00:00
validatorsVideos.videosGet,
getVideo
)
router.delete('/:id',
oAuth.authenticate,
2016-07-01 14:16:40 +00:00
validatorsVideos.videosRemove,
removeVideo
)
router.get('/search/:value',
2016-07-01 14:16:40 +00:00
validatorsVideos.videosSearch,
validatorsPagination.pagination,
validatorsSort.videosSort,
2016-05-17 19:03:00 +00:00
sort.setVideosSort,
pagination.setPagination,
search.setVideosSearch,
searchVideos
)
2015-06-09 15:41:40 +00:00
// ---------------------------------------------------------------------------
2016-01-31 10:23:52 +00:00
module.exports = router
2016-01-31 10:23:52 +00:00
// ---------------------------------------------------------------------------
2016-01-31 10:23:52 +00:00
2017-03-22 20:15:55 +00:00
function listVideoCategories (req, res, next) {
res.json(constants.VIDEO_CATEGORIES)
}
2017-03-27 18:53:11 +00:00
function listVideoLicences (req, res, next) {
res.json(constants.VIDEO_LICENCES)
}
2017-03-08 20:35:43 +00:00
function rateVideoRetryWrapper (req, res, next) {
const options = {
arguments: [ req, res ],
errorMessage: 'Cannot update the user video rate.'
}
databaseUtils.retryTransactionWrapper(rateVideo, options, function (err) {
if (err) return next(err)
return res.type('json').status(204).end()
})
}
function rateVideo (req, res, finalCallback) {
const rateType = req.body.rating
const videoInstance = res.locals.video
const userInstance = res.locals.oauth.token.User
waterfall([
databaseUtils.startSerializableTransaction,
function findPreviousRate (t, callback) {
db.UserVideoRate.load(userInstance.id, videoInstance.id, t, function (err, previousRate) {
return callback(err, t, previousRate)
})
},
function insertUserRateIntoDB (t, previousRate, callback) {
const options = { transaction: t }
let likesToIncrement = 0
let dislikesToIncrement = 0
if (rateType === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement++
else if (rateType === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement++
// There was a previous rate, update it
if (previousRate) {
// We will remove the previous rate, so we will need to remove it from the video attribute
if (previousRate.type === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement--
else if (previousRate.type === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement--
previousRate.type = rateType
previousRate.save(options).asCallback(function (err) {
return callback(err, t, likesToIncrement, dislikesToIncrement)
})
} else { // There was not a previous rate, insert a new one
const query = {
userId: userInstance.id,
videoId: videoInstance.id,
type: rateType
}
db.UserVideoRate.create(query, options).asCallback(function (err) {
return callback(err, t, likesToIncrement, dislikesToIncrement)
})
}
},
function updateVideoAttributeDB (t, likesToIncrement, dislikesToIncrement, callback) {
const options = { transaction: t }
const incrementQuery = {
likes: likesToIncrement,
dislikes: dislikesToIncrement
}
// Even if we do not own the video we increment the attributes
// It is usefull for the user to have a feedback
videoInstance.increment(incrementQuery, options).asCallback(function (err) {
return callback(err, t, likesToIncrement, dislikesToIncrement)
})
},
function sendEventsToFriendsIfNeeded (t, likesToIncrement, dislikesToIncrement, callback) {
// No need for an event type, we own the video
if (videoInstance.isOwned()) return callback(null, t, likesToIncrement, dislikesToIncrement)
const eventsParams = []
if (likesToIncrement !== 0) {
eventsParams.push({
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_EVENT_TYPES.LIKES,
count: likesToIncrement
})
}
if (dislikesToIncrement !== 0) {
eventsParams.push({
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_EVENT_TYPES.DISLIKES,
count: dislikesToIncrement
})
}
friends.addEventsToRemoteVideo(eventsParams, t, function (err) {
return callback(err, t, likesToIncrement, dislikesToIncrement)
})
},
function sendQaduToFriendsIfNeeded (t, likesToIncrement, dislikesToIncrement, callback) {
// We do not own the video, there is no need to send a quick and dirty update to friends
// Our rate was already sent by the addEvent function
if (videoInstance.isOwned() === false) return callback(null, t)
const qadusParams = []
if (likesToIncrement !== 0) {
qadusParams.push({
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_QADU_TYPES.LIKES
})
}
if (dislikesToIncrement !== 0) {
qadusParams.push({
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_QADU_TYPES.DISLIKES
})
}
friends.quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) {
return callback(err, t)
})
},
databaseUtils.commitTransaction
], function (err, t) {
if (err) {
// This is just a debug because we will retry the insert
logger.debug('Cannot add the user video rate.', { error: err })
return databaseUtils.rollbackTransaction(err, t, finalCallback)
}
logger.info('User video rate for video %s of user %s updated.', videoInstance.name, userInstance.username)
return finalCallback(null)
})
}
// Wrapper to video add that retry the function if there is a database error
// We need this because we run the transaction in SERIALIZABLE isolation that can fail
function addVideoRetryWrapper (req, res, next) {
const options = {
arguments: [ req, res, req.files.videofile[0] ],
errorMessage: 'Cannot insert the video with many retries.'
}
databaseUtils.retryTransactionWrapper(addVideo, options, function (err) {
if (err) return next(err)
// TODO : include Location of the new video -> 201
return res.type('json').status(204).end()
})
}
2017-01-17 19:38:45 +00:00
function addVideo (req, res, videoFile, finalCallback) {
const videoInfos = req.body
2016-07-18 15:17:52 +00:00
waterfall([
databaseUtils.startSerializableTransaction,
2016-12-24 15:59:17 +00:00
2017-01-17 19:38:45 +00:00
function findOrCreateAuthor (t, callback) {
const user = res.locals.oauth.token.User
2016-12-11 20:50:51 +00:00
2016-12-29 17:02:03 +00:00
const name = user.username
// null because it is OUR pod
const podId = null
const userId = user.id
2016-12-29 17:02:03 +00:00
db.Author.findOrCreateAuthor(name, podId, userId, t, function (err, authorInstance) {
2017-01-17 19:38:45 +00:00
return callback(err, t, authorInstance)
2016-12-24 15:59:17 +00:00
})
},
2017-01-17 19:38:45 +00:00
function findOrCreateTags (t, author, callback) {
2016-12-24 15:59:17 +00:00
const tags = videoInfos.tags
2016-12-29 17:02:03 +00:00
db.Tag.findOrCreateTags(tags, t, function (err, tagInstances) {
2017-01-17 19:38:45 +00:00
return callback(err, t, author, tagInstances)
2016-12-11 20:50:51 +00:00
})
},
2017-01-17 19:38:45 +00:00
function createVideoObject (t, author, tagInstances, callback) {
const videoData = {
name: videoInfos.name,
remoteId: null,
extname: path.extname(videoFile.filename),
2017-03-22 20:15:55 +00:00
category: videoInfos.category,
2017-03-27 18:53:11 +00:00
licence: videoInfos.licence,
2017-03-28 19:19:46 +00:00
nsfw: videoInfos.nsfw,
description: videoInfos.description,
2016-05-16 17:49:10 +00:00
duration: videoFile.duration,
2017-03-08 20:35:43 +00:00
authorId: author.id
}
2016-12-11 20:50:51 +00:00
const video = db.Video.build(videoData)
2017-01-17 19:38:45 +00:00
return callback(null, t, author, tagInstances, video)
},
2016-12-11 20:50:51 +00:00
// Set the videoname the same as the id
2017-01-17 19:38:45 +00:00
function renameVideoFile (t, author, tagInstances, video, callback) {
const videoDir = constants.CONFIG.STORAGE.VIDEOS_DIR
const source = path.join(videoDir, videoFile.filename)
2016-11-11 14:20:03 +00:00
const destination = path.join(videoDir, video.getVideoFilename())
fs.rename(source, destination, function (err) {
2017-01-17 19:38:45 +00:00
if (err) return callback(err)
// This is important in case if there is another attempt
videoFile.filename = video.getVideoFilename()
2017-01-17 19:38:45 +00:00
return callback(null, t, author, tagInstances, video)
})
},
2017-01-17 19:38:45 +00:00
function insertVideoIntoDB (t, author, tagInstances, video, callback) {
2016-12-24 15:59:17 +00:00
const options = { transaction: t }
// Add tags association
video.save(options).asCallback(function (err, videoCreated) {
2017-01-17 19:38:45 +00:00
if (err) return callback(err)
2016-12-24 15:59:17 +00:00
2016-12-11 20:50:51 +00:00
// Do not forget to add Author informations to the created video
videoCreated.Author = author
2017-01-17 19:38:45 +00:00
return callback(err, t, tagInstances, videoCreated)
2016-05-03 20:41:46 +00:00
})
},
2017-01-17 19:38:45 +00:00
function associateTagsToVideo (t, tagInstances, video, callback) {
2016-12-24 15:59:17 +00:00
const options = { transaction: t }
video.setTags(tagInstances, options).asCallback(function (err) {
video.Tags = tagInstances
2017-01-17 19:38:45 +00:00
return callback(err, t, video)
2016-12-24 15:59:17 +00:00
})
},
2017-01-17 19:38:45 +00:00
function sendToFriends (t, video, callback) {
2016-12-29 18:07:05 +00:00
video.toAddRemoteJSON(function (err, remoteVideo) {
2017-01-17 19:38:45 +00:00
if (err) return callback(err)
// Now we'll add the video's meta data to our friends
friends.addVideoToFriends(remoteVideo, t, function (err) {
2017-01-17 19:38:45 +00:00
return callback(err, t)
})
})
2017-01-17 19:38:45 +00:00
},
databaseUtils.commitTransaction
2016-12-29 18:07:05 +00:00
], function andFinally (err, t) {
if (err) {
// This is just a debug because we will retry the insert
logger.debug('Cannot insert the video.', { error: err })
2017-01-17 19:38:45 +00:00
return databaseUtils.rollbackTransaction(err, t, finalCallback)
2016-12-29 18:07:05 +00:00
}
2017-01-17 19:38:45 +00:00
logger.info('Video with name %s created.', videoInfos.name)
return finalCallback(null)
2016-12-29 18:07:05 +00:00
})
}
function updateVideoRetryWrapper (req, res, next) {
const options = {
arguments: [ req, res ],
errorMessage: 'Cannot update the video with many retries.'
}
databaseUtils.retryTransactionWrapper(updateVideo, options, function (err) {
if (err) return next(err)
// TODO : include Location of the new video -> 201
return res.type('json').status(204).end()
})
}
function updateVideo (req, res, finalCallback) {
const videoInstance = res.locals.video
const videoFieldsSave = videoInstance.toJSON()
2016-12-29 18:07:05 +00:00
const videoInfosToUpdate = req.body
waterfall([
databaseUtils.startSerializableTransaction,
2016-12-29 18:07:05 +00:00
function findOrCreateTags (t, callback) {
if (videoInfosToUpdate.tags) {
db.Tag.findOrCreateTags(videoInfosToUpdate.tags, t, function (err, tagInstances) {
return callback(err, t, tagInstances)
})
} else {
return callback(null, t, null)
}
},
function updateVideoIntoDB (t, tagInstances, callback) {
const options = {
transaction: t
}
2016-12-29 18:07:05 +00:00
if (videoInfosToUpdate.name) videoInstance.set('name', videoInfosToUpdate.name)
2017-03-22 20:15:55 +00:00
if (videoInfosToUpdate.category) videoInstance.set('category', videoInfosToUpdate.category)
2017-03-27 18:53:11 +00:00
if (videoInfosToUpdate.licence) videoInstance.set('licence', videoInfosToUpdate.licence)
2017-03-28 19:19:46 +00:00
if (videoInfosToUpdate.nsfw) videoInstance.set('nsfw', videoInfosToUpdate.nsfw)
2016-12-29 18:07:05 +00:00
if (videoInfosToUpdate.description) videoInstance.set('description', videoInfosToUpdate.description)
videoInstance.save(options).asCallback(function (err) {
return callback(err, t, tagInstances)
})
},
function associateTagsToVideo (t, tagInstances, callback) {
if (tagInstances) {
const options = { transaction: t }
videoInstance.setTags(tagInstances, options).asCallback(function (err) {
videoInstance.Tags = tagInstances
return callback(err, t)
})
} else {
return callback(null, t)
}
},
function sendToFriends (t, callback) {
const json = videoInstance.toUpdateRemoteJSON()
// Now we'll update the video's meta data to our friends
friends.updateVideoToFriends(json, t, function (err) {
return callback(err, t)
})
2017-01-17 19:38:45 +00:00
},
databaseUtils.commitTransaction
2016-12-29 18:07:05 +00:00
2016-12-24 15:59:17 +00:00
], function andFinally (err, t) {
if (err) {
logger.debug('Cannot update the video.', { error: err })
2016-12-24 15:59:17 +00:00
// Force fields we want to update
// If the transaction is retried, sequelize will think the object has not changed
// So it will skip the SQL request, even if the last one was ROLLBACKed!
Object.keys(videoFieldsSave).forEach(function (key) {
const value = videoFieldsSave[key]
videoInstance.set(key, value)
})
2017-01-17 19:38:45 +00:00
return databaseUtils.rollbackTransaction(err, t, finalCallback)
}
2017-01-17 19:38:45 +00:00
logger.info('Video with name %s updated.', videoInfosToUpdate.name)
return finalCallback(null)
})
}
2015-06-09 15:41:40 +00:00
function getVideo (req, res, next) {
const videoInstance = res.locals.video
if (videoInstance.isOwned()) {
// The increment is done directly in the database, not using the instance value
videoInstance.increment('views').asCallback(function (err) {
if (err) {
logger.error('Cannot add view to video %d.', videoInstance.id)
return
}
// FIXME: make a real view system
// For example, only add a view when a user watch a video during 30s etc
2017-03-08 20:35:43 +00:00
const qaduParams = {
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_QADU_TYPES.VIEWS
}
friends.quickAndDirtyUpdateVideoToFriends(qaduParams)
})
2017-02-26 17:57:33 +00:00
} else {
// Just send the event to our friends
2017-03-08 20:35:43 +00:00
const eventParams = {
videoId: videoInstance.id,
type: constants.REQUEST_VIDEO_EVENT_TYPES.VIEWS
}
friends.addEventToRemoteVideo(eventParams)
}
// Do not wait the view system
res.json(videoInstance.toFormatedJSON())
}
2015-06-09 15:41:40 +00:00
function listVideos (req, res, next) {
2016-12-11 20:50:51 +00:00
db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
if (err) return next(err)
2016-01-31 10:23:52 +00:00
2017-01-04 19:59:23 +00:00
res.json(utils.getFormatedObjects(videosList, videosTotal))
})
}
2016-01-31 10:23:52 +00:00
function removeVideo (req, res, next) {
const videoInstance = res.locals.video
2015-06-09 15:41:40 +00:00
videoInstance.destroy().asCallback(function (err) {
if (err) {
logger.error('Errors when removed the video.', { error: err })
return next(err)
}
return res.type('json').status(204).end()
})
}
2015-06-09 15:41:40 +00:00
function searchVideos (req, res, next) {
2016-12-24 15:59:17 +00:00
db.Video.searchAndPopulateAuthorAndPodAndTags(
req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
function (err, videosList, videosTotal) {
if (err) return next(err)
2015-06-09 15:41:40 +00:00
2017-01-04 19:59:23 +00:00
res.json(utils.getFormatedObjects(videosList, videosTotal))
2016-12-24 15:59:17 +00:00
}
)
}
2016-02-04 20:10:33 +00:00
2017-01-04 19:59:23 +00:00
function listVideoAbuses (req, res, next) {
db.VideoAbuse.listForApi(req.query.start, req.query.count, req.query.sort, function (err, abusesList, abusesTotal) {
if (err) return next(err)
2016-03-18 15:28:09 +00:00
2017-01-04 19:59:23 +00:00
res.json(utils.getFormatedObjects(abusesList, abusesTotal))
2016-03-18 15:28:09 +00:00
})
2017-01-04 19:59:23 +00:00
}
2016-03-18 15:28:09 +00:00
2017-01-10 21:33:00 +00:00
function reportVideoAbuseRetryWrapper (req, res, next) {
const options = {
arguments: [ req, res ],
errorMessage: 'Cannot report abuse to the video with many retries.'
}
2017-01-10 21:33:00 +00:00
databaseUtils.retryTransactionWrapper(reportVideoAbuse, options, function (err) {
if (err) return next(err)
return res.type('json').status(204).end()
})
2017-01-10 21:33:00 +00:00
}
function reportVideoAbuse (req, res, finalCallback) {
2017-01-04 19:59:23 +00:00
const videoInstance = res.locals.video
const reporterUsername = res.locals.oauth.token.User.username
const abuse = {
reporterUsername,
reason: req.body.reason,
videoId: videoInstance.id,
reporterPodId: null // This is our pod that reported this abuse
}
2017-01-04 19:59:23 +00:00
2017-01-10 21:33:00 +00:00
waterfall([
databaseUtils.startSerializableTransaction,
2017-01-10 21:33:00 +00:00
function createAbuse (t, callback) {
db.VideoAbuse.create(abuse).asCallback(function (err, abuse) {
return callback(err, t, abuse)
})
},
function sendToFriendsIfNeeded (t, abuse, callback) {
// We send the information to the destination pod
if (videoInstance.isOwned() === false) {
const reportData = {
reporterUsername,
reportReason: abuse.reason,
videoRemoteId: videoInstance.remoteId
}
2017-01-04 19:59:23 +00:00
2017-01-10 21:33:00 +00:00
friends.reportAbuseVideoToFriend(reportData, videoInstance)
2017-01-04 19:59:23 +00:00
}
2017-01-10 21:33:00 +00:00
return callback(null, t)
2017-01-17 19:38:45 +00:00
},
databaseUtils.commitTransaction
2017-01-04 19:59:23 +00:00
2017-01-10 21:33:00 +00:00
], function andFinally (err, t) {
if (err) {
logger.debug('Cannot update the video.', { error: err })
2017-01-17 19:38:45 +00:00
return databaseUtils.rollbackTransaction(err, t, finalCallback)
2017-01-10 21:33:00 +00:00
}
2017-01-17 19:38:45 +00:00
logger.info('Abuse report for video %s created.', videoInstance.name)
return finalCallback(null)
2017-01-04 19:59:23 +00:00
})
2016-03-18 15:28:09 +00:00
}