aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/v1
diff options
context:
space:
mode:
Diffstat (limited to 'server/controllers/api/v1')
-rw-r--r--server/controllers/api/v1/clients.js41
-rw-r--r--server/controllers/api/v1/index.js35
-rw-r--r--server/controllers/api/v1/pods.js145
-rw-r--r--server/controllers/api/v1/remote.js83
-rw-r--r--server/controllers/api/v1/requests.js38
-rw-r--r--server/controllers/api/v1/users.js170
-rw-r--r--server/controllers/api/v1/videos.js206
7 files changed, 0 insertions, 718 deletions
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 @@
1'use strict'
2
3const express = require('express')
4const mongoose = require('mongoose')
5
6const constants = require('../../../initializers/constants')
7
8const Client = mongoose.model('OAuthClient')
9
10const router = express.Router()
11
12router.get('/local', getLocalClient)
13
14// Get the client credentials for the PeerTube front end
15function getLocalClient (req, res, next) {
16 const serverHost = constants.CONFIG.WEBSERVER.HOST
17 const serverPort = constants.CONFIG.WEBSERVER.PORT
18 let headerHostShouldBe = serverHost
19 if (serverPort !== 80 && serverPort !== 443) {
20 headerHostShouldBe += ':' + serverPort
21 }
22
23 // Don't make this check if this is a test instance
24 if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) {
25 return res.type('json').status(403).end()
26 }
27
28 Client.loadFirstClient(function (err, client) {
29 if (err) return next(err)
30 if (!client) return next(new Error('No client available.'))
31
32 res.json({
33 client_id: client._id,
34 client_secret: client.clientSecret
35 })
36 })
37}
38
39// ---------------------------------------------------------------------------
40
41module.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 @@
1'use strict'
2
3const express = require('express')
4
5const router = express.Router()
6
7const clientsController = require('./clients')
8const podsController = require('./pods')
9const remoteController = require('./remote')
10const requestsController = require('./requests')
11const usersController = require('./users')
12const videosController = require('./videos')
13
14router.use('/clients', clientsController)
15router.use('/pods', podsController)
16router.use('/remote', remoteController)
17router.use('/requests', requestsController)
18router.use('/users', usersController)
19router.use('/videos', videosController)
20router.use('/ping', pong)
21router.use('/*', badRequest)
22
23// ---------------------------------------------------------------------------
24
25module.exports = router
26
27// ---------------------------------------------------------------------------
28
29function pong (req, res, next) {
30 return res.send('pong').status(200).end()
31}
32
33function badRequest (req, res, next) {
34 res.type('json').status(400).end()
35}
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 @@
1'use strict'
2
3const express = require('express')
4const mongoose = require('mongoose')
5const waterfall = require('async/waterfall')
6
7const logger = require('../../../helpers/logger')
8const friends = require('../../../lib/friends')
9const middlewares = require('../../../middlewares')
10const admin = middlewares.admin
11const oAuth = middlewares.oauth
12const podsMiddleware = middlewares.pods
13const checkSignature = middlewares.secure.checkSignature
14const validators = middlewares.validators.pods
15const signatureValidator = middlewares.validators.remote.signature
16
17const router = express.Router()
18const Pod = mongoose.model('Pod')
19
20router.get('/', listPods)
21router.post('/',
22 validators.podsAdd,
23 podsMiddleware.setBodyUrlPort,
24 addPods
25)
26router.post('/makefriends',
27 oAuth.authenticate,
28 admin.ensureIsAdmin,
29 validators.makeFriends,
30 podsMiddleware.setBodyUrlsPort,
31 makeFriends
32)
33router.get('/quitfriends',
34 oAuth.authenticate,
35 admin.ensureIsAdmin,
36 quitFriends
37)
38// Post because this is a secured request
39router.post('/remove',
40 signatureValidator,
41 checkSignature,
42 removePods
43)
44
45// ---------------------------------------------------------------------------
46
47module.exports = router
48
49// ---------------------------------------------------------------------------
50
51function addPods (req, res, next) {
52 const informations = req.body
53
54 waterfall([
55 function addPod (callback) {
56 const pod = new Pod(informations)
57 pod.save(function (err, podCreated) {
58 // Be sure about the number of parameters for the callback
59 return callback(err, podCreated)
60 })
61 },
62
63 function sendMyVideos (podCreated, callback) {
64 friends.sendOwnedVideosToPod(podCreated._id)
65
66 callback(null)
67 },
68
69 function fetchMyCertificate (callback) {
70 friends.getMyCertificate(function (err, cert) {
71 if (err) {
72 logger.error('Cannot read cert file.')
73 return callback(err)
74 }
75
76 return callback(null, cert)
77 })
78 }
79 ], function (err, cert) {
80 if (err) return next(err)
81
82 return res.json({ cert: cert })
83 })
84}
85
86function listPods (req, res, next) {
87 Pod.list(function (err, podsUrlList) {
88 if (err) return next(err)
89
90 res.json(getFormatedPods(podsUrlList))
91 })
92}
93
94function makeFriends (req, res, next) {
95 const urls = req.body.urls
96
97 friends.makeFriends(urls, function (err) {
98 if (err) {
99 logger.error('Could not make friends.', { error: err })
100 return
101 }
102
103 logger.info('Made friends!')
104 })
105
106 res.type('json').status(204).end()
107}
108
109function removePods (req, res, next) {
110 const url = req.body.signature.url
111
112 waterfall([
113 function loadPod (callback) {
114 Pod.loadByUrl(url, callback)
115 },
116
117 function removePod (pod, callback) {
118 pod.remove(callback)
119 }
120 ], function (err) {
121 if (err) return next(err)
122
123 return res.type('json').status(204).end()
124 })
125}
126
127function quitFriends (req, res, next) {
128 friends.quitFriends(function (err) {
129 if (err) return next(err)
130
131 res.type('json').status(204).end()
132 })
133}
134
135// ---------------------------------------------------------------------------
136
137function getFormatedPods (pods) {
138 const formatedPods = []
139
140 pods.forEach(function (pod) {
141 formatedPods.push(pod.toFormatedJSON())
142 })
143
144 return formatedPods
145}
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 @@
1'use strict'
2
3const each = require('async/each')
4const eachSeries = require('async/eachSeries')
5const express = require('express')
6const mongoose = require('mongoose')
7
8const middlewares = require('../../../middlewares')
9const secureMiddleware = middlewares.secure
10const validators = middlewares.validators.remote
11const logger = require('../../../helpers/logger')
12
13const router = express.Router()
14const Video = mongoose.model('Video')
15
16router.post('/videos',
17 validators.signature,
18 validators.dataToDecrypt,
19 secureMiddleware.checkSignature,
20 secureMiddleware.decryptBody,
21 validators.remoteVideos,
22 remoteVideos
23)
24
25// ---------------------------------------------------------------------------
26
27module.exports = router
28
29// ---------------------------------------------------------------------------
30
31function remoteVideos (req, res, next) {
32 const requests = req.body.data
33 const fromUrl = req.body.signature.url
34
35 // We need to process in the same order to keep consistency
36 // TODO: optimization
37 eachSeries(requests, function (request, callbackEach) {
38 const videoData = request.data
39
40 if (request.type === 'add') {
41 addRemoteVideo(videoData, callbackEach)
42 } else if (request.type === 'remove') {
43 removeRemoteVideo(videoData, fromUrl, callbackEach)
44 } else {
45 logger.error('Unkown remote request type %s.', request.type)
46 }
47 }, function (err) {
48 if (err) logger.error('Error managing remote videos.', { error: err })
49 })
50
51 // We don't need to keep the other pod waiting
52 return res.type('json').status(204).end()
53}
54
55function addRemoteVideo (videoToCreateData, callback) {
56 logger.debug('Adding remote video %s.', videoToCreateData.magnetUri)
57
58 // Mongoose pre hook will automatically create the thumbnail on disk
59 videoToCreateData.thumbnail = videoToCreateData.thumbnailBase64
60
61 const video = new Video(videoToCreateData)
62 video.save(callback)
63}
64
65function removeRemoteVideo (videoToRemoveData, fromUrl, callback) {
66 // We need the list because we have to remove some other stuffs (thumbnail etc)
67 Video.listByUrlAndMagnet(fromUrl, videoToRemoveData.magnetUri, function (err, videosList) {
68 if (err) {
69 logger.error('Cannot list videos from url and magnets.', { error: err })
70 return callback(err)
71 }
72
73 if (videosList.length === 0) {
74 logger.error('No remote video was found for this pod.', { magnetUri: videoToRemoveData.magnetUri, podUrl: fromUrl })
75 }
76
77 each(videosList, function (video, callbackEach) {
78 logger.debug('Removing remote video %s.', video.magnetUri)
79
80 video.remove(callbackEach)
81 }, callback)
82 })
83}
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 @@
1'use strict'
2
3const express = require('express')
4const mongoose = require('mongoose')
5
6const constants = require('../../../initializers/constants')
7const middlewares = require('../../../middlewares')
8const admin = middlewares.admin
9const oAuth = middlewares.oauth
10
11const Request = mongoose.model('Request')
12
13const router = express.Router()
14
15router.get('/stats',
16 oAuth.authenticate,
17 admin.ensureIsAdmin,
18 getStatsRequests
19)
20
21// ---------------------------------------------------------------------------
22
23module.exports = router
24
25// ---------------------------------------------------------------------------
26
27function getStatsRequests (req, res, next) {
28 Request.list(function (err, requests) {
29 if (err) return next(err)
30
31 return res.json({
32 requests: requests,
33 maxRequestsInParallel: constants.REQUESTS_IN_PARALLEL,
34 remainingMilliSeconds: Request.remainingMilliSeconds(),
35 milliSecondsInterval: constants.REQUESTS_INTERVAL
36 })
37 })
38}
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 @@
1'use strict'
2
3const each = require('async/each')
4const express = require('express')
5const mongoose = require('mongoose')
6const waterfall = require('async/waterfall')
7
8const constants = require('../../../initializers/constants')
9const friends = require('../../../lib/friends')
10const logger = require('../../../helpers/logger')
11const middlewares = require('../../../middlewares')
12const admin = middlewares.admin
13const oAuth = middlewares.oauth
14const pagination = middlewares.pagination
15const sort = middlewares.sort
16const validatorsPagination = middlewares.validators.pagination
17const validatorsSort = middlewares.validators.sort
18const validatorsUsers = middlewares.validators.users
19
20const User = mongoose.model('User')
21const Video = mongoose.model('Video')
22
23const router = express.Router()
24
25router.get('/me', oAuth.authenticate, getUserInformation)
26
27router.get('/',
28 validatorsPagination.pagination,
29 validatorsSort.usersSort,
30 sort.setUsersSort,
31 pagination.setPagination,
32 listUsers
33)
34
35router.post('/',
36 oAuth.authenticate,
37 admin.ensureIsAdmin,
38 validatorsUsers.usersAdd,
39 createUser
40)
41
42router.put('/:id',
43 oAuth.authenticate,
44 validatorsUsers.usersUpdate,
45 updateUser
46)
47
48router.delete('/:id',
49 oAuth.authenticate,
50 admin.ensureIsAdmin,
51 validatorsUsers.usersRemove,
52 removeUser
53)
54
55router.post('/token', oAuth.token, success)
56// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
57
58// ---------------------------------------------------------------------------
59
60module.exports = router
61
62// ---------------------------------------------------------------------------
63
64function createUser (req, res, next) {
65 const user = new User({
66 username: req.body.username,
67 password: req.body.password,
68 role: constants.USER_ROLES.USER
69 })
70
71 user.save(function (err, createdUser) {
72 if (err) return next(err)
73
74 return res.type('json').status(204).end()
75 })
76}
77
78function getUserInformation (req, res, next) {
79 User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) {
80 if (err) return next(err)
81
82 return res.json(user.toFormatedJSON())
83 })
84}
85
86function listUsers (req, res, next) {
87 User.listForApi(req.query.start, req.query.count, req.query.sort, function (err, usersList, usersTotal) {
88 if (err) return next(err)
89
90 res.json(getFormatedUsers(usersList, usersTotal))
91 })
92}
93
94function removeUser (req, res, next) {
95 waterfall([
96 function getUser (callback) {
97 User.loadById(req.params.id, callback)
98 },
99
100 function getVideos (user, callback) {
101 Video.listOwnedByAuthor(user.username, function (err, videos) {
102 return callback(err, user, videos)
103 })
104 },
105
106 function removeVideosFromDB (user, videos, callback) {
107 each(videos, function (video, callbackEach) {
108 video.remove(callbackEach)
109 }, function (err) {
110 return callback(err, user, videos)
111 })
112 },
113
114 function sendInformationToFriends (user, videos, callback) {
115 videos.forEach(function (video) {
116 const params = {
117 name: video.name,
118 magnetUri: video.magnetUri
119 }
120
121 friends.removeVideoToFriends(params)
122 })
123
124 return callback(null, user)
125 },
126
127 function removeUserFromDB (user, callback) {
128 user.remove(callback)
129 }
130 ], function andFinally (err) {
131 if (err) {
132 logger.error('Errors when removed the user.', { error: err })
133 return next(err)
134 }
135
136 return res.sendStatus(204)
137 })
138}
139
140function updateUser (req, res, next) {
141 User.loadByUsername(res.locals.oauth.token.user.username, function (err, user) {
142 if (err) return next(err)
143
144 user.password = req.body.password
145 user.save(function (err) {
146 if (err) return next(err)
147
148 return res.sendStatus(204)
149 })
150 })
151}
152
153function success (req, res, next) {
154 res.end()
155}
156
157// ---------------------------------------------------------------------------
158
159function getFormatedUsers (users, usersTotal) {
160 const formatedUsers = []
161
162 users.forEach(function (user) {
163 formatedUsers.push(user.toFormatedJSON())
164 })
165
166 return {
167 total: usersTotal,
168 data: formatedUsers
169 }
170}
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 @@
1'use strict'
2
3const express = require('express')
4const mongoose = require('mongoose')
5const multer = require('multer')
6const waterfall = require('async/waterfall')
7
8const constants = require('../../../initializers/constants')
9const logger = require('../../../helpers/logger')
10const friends = require('../../../lib/friends')
11const middlewares = require('../../../middlewares')
12const oAuth = middlewares.oauth
13const pagination = middlewares.pagination
14const validators = middlewares.validators
15const validatorsPagination = validators.pagination
16const validatorsSort = validators.sort
17const validatorsVideos = validators.videos
18const search = middlewares.search
19const sort = middlewares.sort
20const utils = require('../../../helpers/utils')
21
22const router = express.Router()
23const Video = mongoose.model('Video')
24
25// multer configuration
26const storage = multer.diskStorage({
27 destination: function (req, file, cb) {
28 cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR)
29 },
30
31 filename: function (req, file, cb) {
32 let extension = ''
33 if (file.mimetype === 'video/webm') extension = 'webm'
34 else if (file.mimetype === 'video/mp4') extension = 'mp4'
35 else if (file.mimetype === 'video/ogg') extension = 'ogv'
36 utils.generateRandomString(16, function (err, randomString) {
37 const fieldname = err ? undefined : randomString
38 cb(null, fieldname + '.' + extension)
39 })
40 }
41})
42
43const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
44
45router.get('/',
46 validatorsPagination.pagination,
47 validatorsSort.videosSort,
48 sort.setVideosSort,
49 pagination.setPagination,
50 listVideos
51)
52router.post('/',
53 oAuth.authenticate,
54 reqFiles,
55 validatorsVideos.videosAdd,
56 addVideo
57)
58router.get('/:id',
59 validatorsVideos.videosGet,
60 getVideo
61)
62router.delete('/:id',
63 oAuth.authenticate,
64 validatorsVideos.videosRemove,
65 removeVideo
66)
67router.get('/search/:value',
68 validatorsVideos.videosSearch,
69 validatorsPagination.pagination,
70 validatorsSort.videosSort,
71 sort.setVideosSort,
72 pagination.setPagination,
73 search.setVideosSearch,
74 searchVideos
75)
76
77// ---------------------------------------------------------------------------
78
79module.exports = router
80
81// ---------------------------------------------------------------------------
82
83function addVideo (req, res, next) {
84 const videoFile = req.files.videofile[0]
85 const videoInfos = req.body
86
87 waterfall([
88
89 function insertIntoDB (callback) {
90 const videoData = {
91 name: videoInfos.name,
92 filename: videoFile.filename,
93 description: videoInfos.description,
94 author: res.locals.oauth.token.user.username,
95 duration: videoFile.duration,
96 tags: videoInfos.tags
97 }
98
99 const video = new Video(videoData)
100 video.save(function (err, video) {
101 // Assert there are only one argument sent to the next function (video)
102 return callback(err, video)
103 })
104 },
105
106 function sendToFriends (video, callback) {
107 video.toRemoteJSON(function (err, remoteVideo) {
108 if (err) return callback(err)
109
110 // Now we'll add the video's meta data to our friends
111 friends.addVideoToFriends(remoteVideo)
112
113 return callback(null)
114 })
115 }
116
117 ], function andFinally (err) {
118 if (err) {
119 logger.error('Cannot insert the video.')
120 return next(err)
121 }
122
123 // TODO : include Location of the new video -> 201
124 return res.type('json').status(204).end()
125 })
126}
127
128function getVideo (req, res, next) {
129 Video.load(req.params.id, function (err, video) {
130 if (err) return next(err)
131
132 if (!video) {
133 return res.type('json').status(204).end()
134 }
135
136 res.json(video.toFormatedJSON())
137 })
138}
139
140function listVideos (req, res, next) {
141 Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
142 if (err) return next(err)
143
144 res.json(getFormatedVideos(videosList, videosTotal))
145 })
146}
147
148function removeVideo (req, res, next) {
149 const videoId = req.params.id
150
151 waterfall([
152 function getVideo (callback) {
153 Video.load(videoId, callback)
154 },
155
156 function removeFromDB (video, callback) {
157 video.remove(function (err) {
158 if (err) return callback(err)
159
160 return callback(null, video)
161 })
162 },
163
164 function sendInformationToFriends (video, callback) {
165 const params = {
166 name: video.name,
167 magnetUri: video.magnetUri
168 }
169
170 friends.removeVideoToFriends(params)
171
172 return callback(null)
173 }
174 ], function andFinally (err) {
175 if (err) {
176 logger.error('Errors when removed the video.', { error: err })
177 return next(err)
178 }
179
180 return res.type('json').status(204).end()
181 })
182}
183
184function searchVideos (req, res, next) {
185 Video.search(req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
186 function (err, videosList, videosTotal) {
187 if (err) return next(err)
188
189 res.json(getFormatedVideos(videosList, videosTotal))
190 })
191}
192
193// ---------------------------------------------------------------------------
194
195function getFormatedVideos (videos, videosTotal) {
196 const formatedVideos = []
197
198 videos.forEach(function (video) {
199 formatedVideos.push(video.toFormatedJSON())
200 })
201
202 return {
203 total: videosTotal,
204 data: formatedVideos
205 }
206}