From f253b1c1f19d9cb056ab95b2cb6208952e073894 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 21 Oct 2016 12:16:28 +0200 Subject: Server: remove v1 directory, we don't really need it --- server/controllers/api/clients.js | 41 +++++++ server/controllers/api/index.js | 35 ++++++ server/controllers/api/pods.js | 145 ++++++++++++++++++++++++ server/controllers/api/remote.js | 83 ++++++++++++++ server/controllers/api/requests.js | 38 +++++++ server/controllers/api/users.js | 170 ++++++++++++++++++++++++++++ server/controllers/api/v1/clients.js | 41 ------- server/controllers/api/v1/index.js | 35 ------ server/controllers/api/v1/pods.js | 145 ------------------------ server/controllers/api/v1/remote.js | 83 -------------- server/controllers/api/v1/requests.js | 38 ------- server/controllers/api/v1/users.js | 170 ---------------------------- server/controllers/api/v1/videos.js | 206 ---------------------------------- server/controllers/api/videos.js | 206 ++++++++++++++++++++++++++++++++++ server/controllers/index.js | 4 +- 15 files changed, 719 insertions(+), 721 deletions(-) create mode 100644 server/controllers/api/clients.js create mode 100644 server/controllers/api/index.js create mode 100644 server/controllers/api/pods.js create mode 100644 server/controllers/api/remote.js create mode 100644 server/controllers/api/requests.js create mode 100644 server/controllers/api/users.js delete mode 100644 server/controllers/api/v1/clients.js delete mode 100644 server/controllers/api/v1/index.js delete mode 100644 server/controllers/api/v1/pods.js delete mode 100644 server/controllers/api/v1/remote.js delete mode 100644 server/controllers/api/v1/requests.js delete mode 100644 server/controllers/api/v1/users.js delete mode 100644 server/controllers/api/v1/videos.js create mode 100644 server/controllers/api/videos.js diff --git a/server/controllers/api/clients.js b/server/controllers/api/clients.js new file mode 100644 index 000000000..ce1149227 --- /dev/null +++ b/server/controllers/api/clients.js @@ -0,0 +1,41 @@ +'use strict' + +const express = require('express') +const mongoose = require('mongoose') + +const constants = require('../../initializers/constants') + +const Client = mongoose.model('OAuthClient') + +const router = express.Router() + +router.get('/local', getLocalClient) + +// Get the client credentials for the PeerTube front end +function getLocalClient (req, res, next) { + const serverHost = constants.CONFIG.WEBSERVER.HOST + const serverPort = constants.CONFIG.WEBSERVER.PORT + let headerHostShouldBe = serverHost + if (serverPort !== 80 && serverPort !== 443) { + headerHostShouldBe += ':' + serverPort + } + + // Don't make this check if this is a test instance + if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) { + return res.type('json').status(403).end() + } + + Client.loadFirstClient(function (err, client) { + if (err) return next(err) + if (!client) return next(new Error('No client available.')) + + res.json({ + client_id: client._id, + client_secret: client.clientSecret + }) + }) +} + +// --------------------------------------------------------------------------- + +module.exports = router diff --git a/server/controllers/api/index.js b/server/controllers/api/index.js new file mode 100644 index 000000000..4cb65ed55 --- /dev/null +++ b/server/controllers/api/index.js @@ -0,0 +1,35 @@ +'use strict' + +const express = require('express') + +const router = express.Router() + +const clientsController = require('./clients') +const podsController = require('./pods') +const remoteController = require('./remote') +const requestsController = require('./requests') +const usersController = require('./users') +const videosController = require('./videos') + +router.use('/clients', clientsController) +router.use('/pods', podsController) +router.use('/remote', remoteController) +router.use('/requests', requestsController) +router.use('/users', usersController) +router.use('/videos', videosController) +router.use('/ping', pong) +router.use('/*', badRequest) + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function pong (req, res, next) { + return res.send('pong').status(200).end() +} + +function badRequest (req, res, next) { + res.type('json').status(400).end() +} diff --git a/server/controllers/api/pods.js b/server/controllers/api/pods.js new file mode 100644 index 000000000..853e0705b --- /dev/null +++ b/server/controllers/api/pods.js @@ -0,0 +1,145 @@ +'use strict' + +const express = require('express') +const mongoose = require('mongoose') +const waterfall = require('async/waterfall') + +const logger = require('../../helpers/logger') +const friends = require('../../lib/friends') +const middlewares = require('../../middlewares') +const admin = middlewares.admin +const oAuth = middlewares.oauth +const podsMiddleware = middlewares.pods +const checkSignature = middlewares.secure.checkSignature +const validators = middlewares.validators.pods +const signatureValidator = middlewares.validators.remote.signature + +const router = express.Router() +const Pod = mongoose.model('Pod') + +router.get('/', listPods) +router.post('/', + validators.podsAdd, + podsMiddleware.setBodyUrlPort, + addPods +) +router.post('/makefriends', + oAuth.authenticate, + admin.ensureIsAdmin, + validators.makeFriends, + podsMiddleware.setBodyUrlsPort, + makeFriends +) +router.get('/quitfriends', + oAuth.authenticate, + admin.ensureIsAdmin, + quitFriends +) +// Post because this is a secured request +router.post('/remove', + signatureValidator, + checkSignature, + removePods +) + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function addPods (req, res, next) { + const informations = req.body + + waterfall([ + function addPod (callback) { + const pod = new Pod(informations) + pod.save(function (err, podCreated) { + // Be sure about the number of parameters for the callback + return callback(err, podCreated) + }) + }, + + function sendMyVideos (podCreated, callback) { + friends.sendOwnedVideosToPod(podCreated._id) + + callback(null) + }, + + function fetchMyCertificate (callback) { + friends.getMyCertificate(function (err, cert) { + if (err) { + logger.error('Cannot read cert file.') + return callback(err) + } + + return callback(null, cert) + }) + } + ], function (err, cert) { + if (err) return next(err) + + return res.json({ cert: cert }) + }) +} + +function listPods (req, res, next) { + Pod.list(function (err, podsUrlList) { + if (err) return next(err) + + res.json(getFormatedPods(podsUrlList)) + }) +} + +function makeFriends (req, res, next) { + const urls = req.body.urls + + friends.makeFriends(urls, function (err) { + if (err) { + logger.error('Could not make friends.', { error: err }) + return + } + + logger.info('Made friends!') + }) + + res.type('json').status(204).end() +} + +function removePods (req, res, next) { + const url = req.body.signature.url + + waterfall([ + function loadPod (callback) { + Pod.loadByUrl(url, callback) + }, + + function removePod (pod, callback) { + pod.remove(callback) + } + ], function (err) { + if (err) return next(err) + + return res.type('json').status(204).end() + }) +} + +function quitFriends (req, res, next) { + friends.quitFriends(function (err) { + if (err) return next(err) + + res.type('json').status(204).end() + }) +} + +// --------------------------------------------------------------------------- + +function getFormatedPods (pods) { + const formatedPods = [] + + pods.forEach(function (pod) { + formatedPods.push(pod.toFormatedJSON()) + }) + + return formatedPods +} diff --git a/server/controllers/api/remote.js b/server/controllers/api/remote.js new file mode 100644 index 000000000..17b1d07c4 --- /dev/null +++ b/server/controllers/api/remote.js @@ -0,0 +1,83 @@ +'use strict' + +const each = require('async/each') +const eachSeries = require('async/eachSeries') +const express = require('express') +const mongoose = require('mongoose') + +const middlewares = require('../../middlewares') +const secureMiddleware = middlewares.secure +const validators = middlewares.validators.remote +const logger = require('../../helpers/logger') + +const router = express.Router() +const Video = mongoose.model('Video') + +router.post('/videos', + validators.signature, + validators.dataToDecrypt, + secureMiddleware.checkSignature, + secureMiddleware.decryptBody, + validators.remoteVideos, + remoteVideos +) + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function remoteVideos (req, res, next) { + const requests = req.body.data + const fromUrl = req.body.signature.url + + // We need to process in the same order to keep consistency + // TODO: optimization + eachSeries(requests, function (request, callbackEach) { + const videoData = request.data + + if (request.type === 'add') { + addRemoteVideo(videoData, callbackEach) + } else if (request.type === 'remove') { + removeRemoteVideo(videoData, fromUrl, callbackEach) + } else { + logger.error('Unkown remote request type %s.', request.type) + } + }, function (err) { + if (err) logger.error('Error managing remote videos.', { error: err }) + }) + + // We don't need to keep the other pod waiting + return res.type('json').status(204).end() +} + +function addRemoteVideo (videoToCreateData, callback) { + logger.debug('Adding remote video %s.', videoToCreateData.magnetUri) + + // Mongoose pre hook will automatically create the thumbnail on disk + videoToCreateData.thumbnail = videoToCreateData.thumbnailBase64 + + const video = new Video(videoToCreateData) + video.save(callback) +} + +function removeRemoteVideo (videoToRemoveData, fromUrl, callback) { + // We need the list because we have to remove some other stuffs (thumbnail etc) + Video.listByUrlAndMagnet(fromUrl, videoToRemoveData.magnetUri, function (err, videosList) { + if (err) { + logger.error('Cannot list videos from url and magnets.', { error: err }) + return callback(err) + } + + if (videosList.length === 0) { + logger.error('No remote video was found for this pod.', { magnetUri: videoToRemoveData.magnetUri, podUrl: fromUrl }) + } + + each(videosList, function (video, callbackEach) { + logger.debug('Removing remote video %s.', video.magnetUri) + + video.remove(callbackEach) + }, callback) + }) +} diff --git a/server/controllers/api/requests.js b/server/controllers/api/requests.js new file mode 100644 index 000000000..52aad6997 --- /dev/null +++ b/server/controllers/api/requests.js @@ -0,0 +1,38 @@ +'use strict' + +const express = require('express') +const mongoose = require('mongoose') + +const constants = require('../../initializers/constants') +const middlewares = require('../../middlewares') +const admin = middlewares.admin +const oAuth = middlewares.oauth + +const Request = mongoose.model('Request') + +const router = express.Router() + +router.get('/stats', + oAuth.authenticate, + admin.ensureIsAdmin, + getStatsRequests +) + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function getStatsRequests (req, res, next) { + Request.list(function (err, requests) { + if (err) return next(err) + + return res.json({ + requests: requests, + maxRequestsInParallel: constants.REQUESTS_IN_PARALLEL, + remainingMilliSeconds: Request.remainingMilliSeconds(), + milliSecondsInterval: constants.REQUESTS_INTERVAL + }) + }) +} diff --git a/server/controllers/api/users.js b/server/controllers/api/users.js new file mode 100644 index 000000000..b4d687312 --- /dev/null +++ b/server/controllers/api/users.js @@ -0,0 +1,170 @@ +'use strict' + +const each = require('async/each') +const express = require('express') +const mongoose = require('mongoose') +const waterfall = require('async/waterfall') + +const constants = require('../../initializers/constants') +const friends = require('../../lib/friends') +const logger = require('../../helpers/logger') +const middlewares = require('../../middlewares') +const admin = middlewares.admin +const oAuth = middlewares.oauth +const pagination = middlewares.pagination +const sort = middlewares.sort +const validatorsPagination = middlewares.validators.pagination +const validatorsSort = middlewares.validators.sort +const validatorsUsers = middlewares.validators.users + +const User = mongoose.model('User') +const Video = mongoose.model('Video') + +const router = express.Router() + +router.get('/me', oAuth.authenticate, getUserInformation) + +router.get('/', + validatorsPagination.pagination, + validatorsSort.usersSort, + sort.setUsersSort, + pagination.setPagination, + listUsers +) + +router.post('/', + oAuth.authenticate, + admin.ensureIsAdmin, + validatorsUsers.usersAdd, + createUser +) + +router.put('/:id', + oAuth.authenticate, + validatorsUsers.usersUpdate, + updateUser +) + +router.delete('/:id', + oAuth.authenticate, + admin.ensureIsAdmin, + validatorsUsers.usersRemove, + removeUser +) + +router.post('/token', oAuth.token, success) +// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function createUser (req, res, next) { + const user = new User({ + username: req.body.username, + password: req.body.password, + role: constants.USER_ROLES.USER + }) + + user.save(function (err, createdUser) { + if (err) return next(err) + + return res.type('json').status(204).end() + }) +} + +function getUserInformation (req, res, next) { + User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) { + if (err) return next(err) + + return res.json(user.toFormatedJSON()) + }) +} + +function listUsers (req, res, next) { + User.listForApi(req.query.start, req.query.count, req.query.sort, function (err, usersList, usersTotal) { + if (err) return next(err) + + res.json(getFormatedUsers(usersList, usersTotal)) + }) +} + +function removeUser (req, res, next) { + waterfall([ + function getUser (callback) { + User.loadById(req.params.id, callback) + }, + + function getVideos (user, callback) { + Video.listOwnedByAuthor(user.username, function (err, videos) { + return callback(err, user, videos) + }) + }, + + function removeVideosFromDB (user, videos, callback) { + each(videos, function (video, callbackEach) { + video.remove(callbackEach) + }, function (err) { + return callback(err, user, videos) + }) + }, + + function sendInformationToFriends (user, videos, callback) { + videos.forEach(function (video) { + const params = { + name: video.name, + magnetUri: video.magnetUri + } + + friends.removeVideoToFriends(params) + }) + + return callback(null, user) + }, + + function removeUserFromDB (user, callback) { + user.remove(callback) + } + ], function andFinally (err) { + if (err) { + logger.error('Errors when removed the user.', { error: err }) + return next(err) + } + + return res.sendStatus(204) + }) +} + +function updateUser (req, res, next) { + User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) { + if (err) return next(err) + + user.password = req.body.password + user.save(function (err) { + if (err) return next(err) + + return res.sendStatus(204) + }) + }) +} + +function success (req, res, next) { + res.end() +} + +// --------------------------------------------------------------------------- + +function getFormatedUsers (users, usersTotal) { + const formatedUsers = [] + + users.forEach(function (user) { + formatedUsers.push(user.toFormatedJSON()) + }) + + return { + total: usersTotal, + data: formatedUsers + } +} diff --git a/server/controllers/api/v1/clients.js b/server/controllers/api/v1/clients.js deleted file mode 100644 index 5b460db2e..000000000 --- a/server/controllers/api/v1/clients.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict' - -const express = require('express') -const mongoose = require('mongoose') - -const constants = require('../../../initializers/constants') - -const Client = mongoose.model('OAuthClient') - -const router = express.Router() - -router.get('/local', getLocalClient) - -// Get the client credentials for the PeerTube front end -function getLocalClient (req, res, next) { - const serverHost = constants.CONFIG.WEBSERVER.HOST - const serverPort = constants.CONFIG.WEBSERVER.PORT - let headerHostShouldBe = serverHost - if (serverPort !== 80 && serverPort !== 443) { - headerHostShouldBe += ':' + serverPort - } - - // Don't make this check if this is a test instance - if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) { - return res.type('json').status(403).end() - } - - Client.loadFirstClient(function (err, client) { - if (err) return next(err) - if (!client) return next(new Error('No client available.')) - - res.json({ - client_id: client._id, - client_secret: client.clientSecret - }) - }) -} - -// --------------------------------------------------------------------------- - -module.exports = router diff --git a/server/controllers/api/v1/index.js b/server/controllers/api/v1/index.js deleted file mode 100644 index 4cb65ed55..000000000 --- a/server/controllers/api/v1/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict' - -const express = require('express') - -const router = express.Router() - -const clientsController = require('./clients') -const podsController = require('./pods') -const remoteController = require('./remote') -const requestsController = require('./requests') -const usersController = require('./users') -const videosController = require('./videos') - -router.use('/clients', clientsController) -router.use('/pods', podsController) -router.use('/remote', remoteController) -router.use('/requests', requestsController) -router.use('/users', usersController) -router.use('/videos', videosController) -router.use('/ping', pong) -router.use('/*', badRequest) - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function pong (req, res, next) { - return res.send('pong').status(200).end() -} - -function badRequest (req, res, next) { - res.type('json').status(400).end() -} diff --git a/server/controllers/api/v1/pods.js b/server/controllers/api/v1/pods.js deleted file mode 100644 index 2f4621327..000000000 --- a/server/controllers/api/v1/pods.js +++ /dev/null @@ -1,145 +0,0 @@ -'use strict' - -const express = require('express') -const mongoose = require('mongoose') -const waterfall = require('async/waterfall') - -const logger = require('../../../helpers/logger') -const friends = require('../../../lib/friends') -const middlewares = require('../../../middlewares') -const admin = middlewares.admin -const oAuth = middlewares.oauth -const podsMiddleware = middlewares.pods -const checkSignature = middlewares.secure.checkSignature -const validators = middlewares.validators.pods -const signatureValidator = middlewares.validators.remote.signature - -const router = express.Router() -const Pod = mongoose.model('Pod') - -router.get('/', listPods) -router.post('/', - validators.podsAdd, - podsMiddleware.setBodyUrlPort, - addPods -) -router.post('/makefriends', - oAuth.authenticate, - admin.ensureIsAdmin, - validators.makeFriends, - podsMiddleware.setBodyUrlsPort, - makeFriends -) -router.get('/quitfriends', - oAuth.authenticate, - admin.ensureIsAdmin, - quitFriends -) -// Post because this is a secured request -router.post('/remove', - signatureValidator, - checkSignature, - removePods -) - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function addPods (req, res, next) { - const informations = req.body - - waterfall([ - function addPod (callback) { - const pod = new Pod(informations) - pod.save(function (err, podCreated) { - // Be sure about the number of parameters for the callback - return callback(err, podCreated) - }) - }, - - function sendMyVideos (podCreated, callback) { - friends.sendOwnedVideosToPod(podCreated._id) - - callback(null) - }, - - function fetchMyCertificate (callback) { - friends.getMyCertificate(function (err, cert) { - if (err) { - logger.error('Cannot read cert file.') - return callback(err) - } - - return callback(null, cert) - }) - } - ], function (err, cert) { - if (err) return next(err) - - return res.json({ cert: cert }) - }) -} - -function listPods (req, res, next) { - Pod.list(function (err, podsUrlList) { - if (err) return next(err) - - res.json(getFormatedPods(podsUrlList)) - }) -} - -function makeFriends (req, res, next) { - const urls = req.body.urls - - friends.makeFriends(urls, function (err) { - if (err) { - logger.error('Could not make friends.', { error: err }) - return - } - - logger.info('Made friends!') - }) - - res.type('json').status(204).end() -} - -function removePods (req, res, next) { - const url = req.body.signature.url - - waterfall([ - function loadPod (callback) { - Pod.loadByUrl(url, callback) - }, - - function removePod (pod, callback) { - pod.remove(callback) - } - ], function (err) { - if (err) return next(err) - - return res.type('json').status(204).end() - }) -} - -function quitFriends (req, res, next) { - friends.quitFriends(function (err) { - if (err) return next(err) - - res.type('json').status(204).end() - }) -} - -// --------------------------------------------------------------------------- - -function getFormatedPods (pods) { - const formatedPods = [] - - pods.forEach(function (pod) { - formatedPods.push(pod.toFormatedJSON()) - }) - - return formatedPods -} diff --git a/server/controllers/api/v1/remote.js b/server/controllers/api/v1/remote.js deleted file mode 100644 index a22c5d151..000000000 --- a/server/controllers/api/v1/remote.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict' - -const each = require('async/each') -const eachSeries = require('async/eachSeries') -const express = require('express') -const mongoose = require('mongoose') - -const middlewares = require('../../../middlewares') -const secureMiddleware = middlewares.secure -const validators = middlewares.validators.remote -const logger = require('../../../helpers/logger') - -const router = express.Router() -const Video = mongoose.model('Video') - -router.post('/videos', - validators.signature, - validators.dataToDecrypt, - secureMiddleware.checkSignature, - secureMiddleware.decryptBody, - validators.remoteVideos, - remoteVideos -) - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function remoteVideos (req, res, next) { - const requests = req.body.data - const fromUrl = req.body.signature.url - - // We need to process in the same order to keep consistency - // TODO: optimization - eachSeries(requests, function (request, callbackEach) { - const videoData = request.data - - if (request.type === 'add') { - addRemoteVideo(videoData, callbackEach) - } else if (request.type === 'remove') { - removeRemoteVideo(videoData, fromUrl, callbackEach) - } else { - logger.error('Unkown remote request type %s.', request.type) - } - }, function (err) { - if (err) logger.error('Error managing remote videos.', { error: err }) - }) - - // We don't need to keep the other pod waiting - return res.type('json').status(204).end() -} - -function addRemoteVideo (videoToCreateData, callback) { - logger.debug('Adding remote video %s.', videoToCreateData.magnetUri) - - // Mongoose pre hook will automatically create the thumbnail on disk - videoToCreateData.thumbnail = videoToCreateData.thumbnailBase64 - - const video = new Video(videoToCreateData) - video.save(callback) -} - -function removeRemoteVideo (videoToRemoveData, fromUrl, callback) { - // We need the list because we have to remove some other stuffs (thumbnail etc) - Video.listByUrlAndMagnet(fromUrl, videoToRemoveData.magnetUri, function (err, videosList) { - if (err) { - logger.error('Cannot list videos from url and magnets.', { error: err }) - return callback(err) - } - - if (videosList.length === 0) { - logger.error('No remote video was found for this pod.', { magnetUri: videoToRemoveData.magnetUri, podUrl: fromUrl }) - } - - each(videosList, function (video, callbackEach) { - logger.debug('Removing remote video %s.', video.magnetUri) - - video.remove(callbackEach) - }, callback) - }) -} diff --git a/server/controllers/api/v1/requests.js b/server/controllers/api/v1/requests.js deleted file mode 100644 index 97616424d..000000000 --- a/server/controllers/api/v1/requests.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict' - -const express = require('express') -const mongoose = require('mongoose') - -const constants = require('../../../initializers/constants') -const middlewares = require('../../../middlewares') -const admin = middlewares.admin -const oAuth = middlewares.oauth - -const Request = mongoose.model('Request') - -const router = express.Router() - -router.get('/stats', - oAuth.authenticate, - admin.ensureIsAdmin, - getStatsRequests -) - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function getStatsRequests (req, res, next) { - Request.list(function (err, requests) { - if (err) return next(err) - - return res.json({ - requests: requests, - maxRequestsInParallel: constants.REQUESTS_IN_PARALLEL, - remainingMilliSeconds: Request.remainingMilliSeconds(), - milliSecondsInterval: constants.REQUESTS_INTERVAL - }) - }) -} diff --git a/server/controllers/api/v1/users.js b/server/controllers/api/v1/users.js deleted file mode 100644 index 975e25e68..000000000 --- a/server/controllers/api/v1/users.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict' - -const each = require('async/each') -const express = require('express') -const mongoose = require('mongoose') -const waterfall = require('async/waterfall') - -const constants = require('../../../initializers/constants') -const friends = require('../../../lib/friends') -const logger = require('../../../helpers/logger') -const middlewares = require('../../../middlewares') -const admin = middlewares.admin -const oAuth = middlewares.oauth -const pagination = middlewares.pagination -const sort = middlewares.sort -const validatorsPagination = middlewares.validators.pagination -const validatorsSort = middlewares.validators.sort -const validatorsUsers = middlewares.validators.users - -const User = mongoose.model('User') -const Video = mongoose.model('Video') - -const router = express.Router() - -router.get('/me', oAuth.authenticate, getUserInformation) - -router.get('/', - validatorsPagination.pagination, - validatorsSort.usersSort, - sort.setUsersSort, - pagination.setPagination, - listUsers -) - -router.post('/', - oAuth.authenticate, - admin.ensureIsAdmin, - validatorsUsers.usersAdd, - createUser -) - -router.put('/:id', - oAuth.authenticate, - validatorsUsers.usersUpdate, - updateUser -) - -router.delete('/:id', - oAuth.authenticate, - admin.ensureIsAdmin, - validatorsUsers.usersRemove, - removeUser -) - -router.post('/token', oAuth.token, success) -// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function createUser (req, res, next) { - const user = new User({ - username: req.body.username, - password: req.body.password, - role: constants.USER_ROLES.USER - }) - - user.save(function (err, createdUser) { - if (err) return next(err) - - return res.type('json').status(204).end() - }) -} - -function getUserInformation (req, res, next) { - User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) { - if (err) return next(err) - - return res.json(user.toFormatedJSON()) - }) -} - -function listUsers (req, res, next) { - User.listForApi(req.query.start, req.query.count, req.query.sort, function (err, usersList, usersTotal) { - if (err) return next(err) - - res.json(getFormatedUsers(usersList, usersTotal)) - }) -} - -function removeUser (req, res, next) { - waterfall([ - function getUser (callback) { - User.loadById(req.params.id, callback) - }, - - function getVideos (user, callback) { - Video.listOwnedByAuthor(user.username, function (err, videos) { - return callback(err, user, videos) - }) - }, - - function removeVideosFromDB (user, videos, callback) { - each(videos, function (video, callbackEach) { - video.remove(callbackEach) - }, function (err) { - return callback(err, user, videos) - }) - }, - - function sendInformationToFriends (user, videos, callback) { - videos.forEach(function (video) { - const params = { - name: video.name, - magnetUri: video.magnetUri - } - - friends.removeVideoToFriends(params) - }) - - return callback(null, user) - }, - - function removeUserFromDB (user, callback) { - user.remove(callback) - } - ], function andFinally (err) { - if (err) { - logger.error('Errors when removed the user.', { error: err }) - return next(err) - } - - return res.sendStatus(204) - }) -} - -function updateUser (req, res, next) { - User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) { - if (err) return next(err) - - user.password = req.body.password - user.save(function (err) { - if (err) return next(err) - - return res.sendStatus(204) - }) - }) -} - -function success (req, res, next) { - res.end() -} - -// --------------------------------------------------------------------------- - -function getFormatedUsers (users, usersTotal) { - const formatedUsers = [] - - users.forEach(function (user) { - formatedUsers.push(user.toFormatedJSON()) - }) - - return { - total: usersTotal, - data: formatedUsers - } -} diff --git a/server/controllers/api/v1/videos.js b/server/controllers/api/v1/videos.js deleted file mode 100644 index ee47ce7ac..000000000 --- a/server/controllers/api/v1/videos.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict' - -const express = require('express') -const mongoose = require('mongoose') -const multer = require('multer') -const waterfall = require('async/waterfall') - -const constants = require('../../../initializers/constants') -const logger = require('../../../helpers/logger') -const friends = require('../../../lib/friends') -const middlewares = require('../../../middlewares') -const oAuth = middlewares.oauth -const pagination = middlewares.pagination -const validators = middlewares.validators -const validatorsPagination = validators.pagination -const validatorsSort = validators.sort -const validatorsVideos = validators.videos -const search = middlewares.search -const sort = middlewares.sort -const utils = require('../../../helpers/utils') - -const router = express.Router() -const Video = mongoose.model('Video') - -// multer configuration -const storage = multer.diskStorage({ - destination: function (req, file, cb) { - cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR) - }, - - filename: function (req, file, cb) { - 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 }]) - -router.get('/', - validatorsPagination.pagination, - validatorsSort.videosSort, - sort.setVideosSort, - pagination.setPagination, - listVideos -) -router.post('/', - oAuth.authenticate, - reqFiles, - validatorsVideos.videosAdd, - addVideo -) -router.get('/:id', - validatorsVideos.videosGet, - getVideo -) -router.delete('/:id', - oAuth.authenticate, - validatorsVideos.videosRemove, - removeVideo -) -router.get('/search/:value', - validatorsVideos.videosSearch, - validatorsPagination.pagination, - validatorsSort.videosSort, - sort.setVideosSort, - pagination.setPagination, - search.setVideosSearch, - searchVideos -) - -// --------------------------------------------------------------------------- - -module.exports = router - -// --------------------------------------------------------------------------- - -function addVideo (req, res, next) { - const videoFile = req.files.videofile[0] - const videoInfos = req.body - - waterfall([ - - function insertIntoDB (callback) { - const videoData = { - name: videoInfos.name, - filename: videoFile.filename, - description: videoInfos.description, - author: res.locals.oauth.token.user.username, - duration: videoFile.duration, - tags: videoInfos.tags - } - - const video = new Video(videoData) - video.save(function (err, video) { - // Assert there are only one argument sent to the next function (video) - return callback(err, video) - }) - }, - - function sendToFriends (video, callback) { - video.toRemoteJSON(function (err, remoteVideo) { - if (err) return callback(err) - - // Now we'll add the video's meta data to our friends - friends.addVideoToFriends(remoteVideo) - - return callback(null) - }) - } - - ], function andFinally (err) { - if (err) { - logger.error('Cannot insert the video.') - return next(err) - } - - // TODO : include Location of the new video -> 201 - return res.type('json').status(204).end() - }) -} - -function getVideo (req, res, next) { - Video.load(req.params.id, function (err, video) { - if (err) return next(err) - - if (!video) { - return res.type('json').status(204).end() - } - - res.json(video.toFormatedJSON()) - }) -} - -function listVideos (req, res, next) { - Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) { - if (err) return next(err) - - res.json(getFormatedVideos(videosList, videosTotal)) - }) -} - -function removeVideo (req, res, next) { - const videoId = req.params.id - - waterfall([ - function getVideo (callback) { - Video.load(videoId, callback) - }, - - function removeFromDB (video, callback) { - video.remove(function (err) { - if (err) return callback(err) - - return callback(null, video) - }) - }, - - function sendInformationToFriends (video, callback) { - const params = { - name: video.name, - magnetUri: video.magnetUri - } - - friends.removeVideoToFriends(params) - - return callback(null) - } - ], function andFinally (err) { - if (err) { - logger.error('Errors when removed the video.', { error: err }) - return next(err) - } - - return res.type('json').status(204).end() - }) -} - -function searchVideos (req, res, next) { - Video.search(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort, - function (err, videosList, videosTotal) { - if (err) return next(err) - - res.json(getFormatedVideos(videosList, videosTotal)) - }) -} - -// --------------------------------------------------------------------------- - -function getFormatedVideos (videos, videosTotal) { - const formatedVideos = [] - - videos.forEach(function (video) { - formatedVideos.push(video.toFormatedJSON()) - }) - - return { - total: videosTotal, - data: formatedVideos - } -} diff --git a/server/controllers/api/videos.js b/server/controllers/api/videos.js new file mode 100644 index 000000000..e2d393074 --- /dev/null +++ b/server/controllers/api/videos.js @@ -0,0 +1,206 @@ +'use strict' + +const express = require('express') +const mongoose = require('mongoose') +const multer = require('multer') +const waterfall = require('async/waterfall') + +const constants = require('../../initializers/constants') +const logger = require('../../helpers/logger') +const friends = require('../../lib/friends') +const middlewares = require('../../middlewares') +const oAuth = middlewares.oauth +const pagination = middlewares.pagination +const validators = middlewares.validators +const validatorsPagination = validators.pagination +const validatorsSort = validators.sort +const validatorsVideos = validators.videos +const search = middlewares.search +const sort = middlewares.sort +const utils = require('../../helpers/utils') + +const router = express.Router() +const Video = mongoose.model('Video') + +// multer configuration +const storage = multer.diskStorage({ + destination: function (req, file, cb) { + cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR) + }, + + filename: function (req, file, cb) { + 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 }]) + +router.get('/', + validatorsPagination.pagination, + validatorsSort.videosSort, + sort.setVideosSort, + pagination.setPagination, + listVideos +) +router.post('/', + oAuth.authenticate, + reqFiles, + validatorsVideos.videosAdd, + addVideo +) +router.get('/:id', + validatorsVideos.videosGet, + getVideo +) +router.delete('/:id', + oAuth.authenticate, + validatorsVideos.videosRemove, + removeVideo +) +router.get('/search/:value', + validatorsVideos.videosSearch, + validatorsPagination.pagination, + validatorsSort.videosSort, + sort.setVideosSort, + pagination.setPagination, + search.setVideosSearch, + searchVideos +) + +// --------------------------------------------------------------------------- + +module.exports = router + +// --------------------------------------------------------------------------- + +function addVideo (req, res, next) { + const videoFile = req.files.videofile[0] + const videoInfos = req.body + + waterfall([ + + function insertIntoDB (callback) { + const videoData = { + name: videoInfos.name, + filename: videoFile.filename, + description: videoInfos.description, + author: res.locals.oauth.token.user.username, + duration: videoFile.duration, + tags: videoInfos.tags + } + + const video = new Video(videoData) + video.save(function (err, video) { + // Assert there are only one argument sent to the next function (video) + return callback(err, video) + }) + }, + + function sendToFriends (video, callback) { + video.toRemoteJSON(function (err, remoteVideo) { + if (err) return callback(err) + + // Now we'll add the video's meta data to our friends + friends.addVideoToFriends(remoteVideo) + + return callback(null) + }) + } + + ], function andFinally (err) { + if (err) { + logger.error('Cannot insert the video.') + return next(err) + } + + // TODO : include Location of the new video -> 201 + return res.type('json').status(204).end() + }) +} + +function getVideo (req, res, next) { + Video.load(req.params.id, function (err, video) { + if (err) return next(err) + + if (!video) { + return res.type('json').status(204).end() + } + + res.json(video.toFormatedJSON()) + }) +} + +function listVideos (req, res, next) { + Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) { + if (err) return next(err) + + res.json(getFormatedVideos(videosList, videosTotal)) + }) +} + +function removeVideo (req, res, next) { + const videoId = req.params.id + + waterfall([ + function getVideo (callback) { + Video.load(videoId, callback) + }, + + function removeFromDB (video, callback) { + video.remove(function (err) { + if (err) return callback(err) + + return callback(null, video) + }) + }, + + function sendInformationToFriends (video, callback) { + const params = { + name: video.name, + magnetUri: video.magnetUri + } + + friends.removeVideoToFriends(params) + + return callback(null) + } + ], function andFinally (err) { + if (err) { + logger.error('Errors when removed the video.', { error: err }) + return next(err) + } + + return res.type('json').status(204).end() + }) +} + +function searchVideos (req, res, next) { + Video.search(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort, + function (err, videosList, videosTotal) { + if (err) return next(err) + + res.json(getFormatedVideos(videosList, videosTotal)) + }) +} + +// --------------------------------------------------------------------------- + +function getFormatedVideos (videos, videosTotal) { + const formatedVideos = [] + + videos.forEach(function (video) { + formatedVideos.push(video.toFormatedJSON()) + }) + + return { + total: videosTotal, + data: formatedVideos + } +} diff --git a/server/controllers/index.js b/server/controllers/index.js index 4c1d3dafe..6a3f3f98f 100644 --- a/server/controllers/index.js +++ b/server/controllers/index.js @@ -1,8 +1,6 @@ 'use strict' -const constants = require('../initializers/constants') - -const apiController = require('./api/' + constants.API_VERSION) +const apiController = require('./api/') module.exports = { api: apiController -- cgit v1.2.3