--- /dev/null
+'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
--- /dev/null
+'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()
+}
--- /dev/null
+'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
+}
--- /dev/null
+'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)
+ })
+}
--- /dev/null
+'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
+ })
+ })
+}
--- /dev/null
+'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
+ }
+}
+++ /dev/null
-'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
+++ /dev/null
-'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()
-}
+++ /dev/null
-'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
-}
+++ /dev/null
-'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)
- })
-}
+++ /dev/null
-'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
- })
- })
-}
+++ /dev/null
-'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
- }
-}
+++ /dev/null
-'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
- }
-}
--- /dev/null
+'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
+ }
+}
'use strict'
-const constants = require('../initializers/constants')
-
-const apiController = require('./api/' + constants.API_VERSION)
+const apiController = require('./api/')
module.exports = {
api: apiController