aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api
diff options
context:
space:
mode:
Diffstat (limited to 'server/controllers/api')
-rw-r--r--server/controllers/api/clients.ts (renamed from server/controllers/api/clients.js)20
-rw-r--r--server/controllers/api/config.js22
-rw-r--r--server/controllers/api/config.ts22
-rw-r--r--server/controllers/api/index.js35
-rw-r--r--server/controllers/api/index.ts33
-rw-r--r--server/controllers/api/pods.js109
-rw-r--r--server/controllers/api/pods.ts118
-rw-r--r--server/controllers/api/remote/index.js18
-rw-r--r--server/controllers/api/remote/index.ts18
-rw-r--r--server/controllers/api/remote/pods.ts (renamed from server/controllers/api/remote/pods.js)20
-rw-r--r--server/controllers/api/remote/videos.ts (renamed from server/controllers/api/remote/videos.js)122
-rw-r--r--server/controllers/api/requests.ts (renamed from server/controllers/api/requests.js)34
-rw-r--r--server/controllers/api/users.ts (renamed from server/controllers/api/users.js)96
-rw-r--r--server/controllers/api/videos/abuse.ts (renamed from server/controllers/api/videos/abuse.js)77
-rw-r--r--server/controllers/api/videos/blacklist.ts (renamed from server/controllers/api/videos/blacklist.js)34
-rw-r--r--server/controllers/api/videos/index.ts (renamed from server/controllers/api/videos/index.js)182
-rw-r--r--server/controllers/api/videos/rate.ts (renamed from server/controllers/api/videos/rate.js)78
17 files changed, 550 insertions, 488 deletions
diff --git a/server/controllers/api/clients.js b/server/controllers/api/clients.ts
index cf83cb835..902f62995 100644
--- a/server/controllers/api/clients.js
+++ b/server/controllers/api/clients.ts
@@ -1,19 +1,17 @@
1'use strict' 1import express = require('express')
2 2
3const express = require('express') 3import { CONFIG } from '../../initializers';
4 4import { logger } from '../../helpers'
5const constants = require('../../initializers/constants')
6const db = require('../../initializers/database') 5const db = require('../../initializers/database')
7const logger = require('../../helpers/logger')
8 6
9const router = express.Router() 7const clientsRouter = express.Router()
10 8
11router.get('/local', getLocalClient) 9clientsRouter.get('/local', getLocalClient)
12 10
13// Get the client credentials for the PeerTube front end 11// Get the client credentials for the PeerTube front end
14function getLocalClient (req, res, next) { 12function getLocalClient (req, res, next) {
15 const serverHostname = constants.CONFIG.WEBSERVER.HOSTNAME 13 const serverHostname = CONFIG.WEBSERVER.HOSTNAME
16 const serverPort = constants.CONFIG.WEBSERVER.PORT 14 const serverPort = CONFIG.WEBSERVER.PORT
17 let headerHostShouldBe = serverHostname 15 let headerHostShouldBe = serverHostname
18 if (serverPort !== 80 && serverPort !== 443) { 16 if (serverPort !== 80 && serverPort !== 443) {
19 headerHostShouldBe += ':' + serverPort 17 headerHostShouldBe += ':' + serverPort
@@ -38,4 +36,6 @@ function getLocalClient (req, res, next) {
38 36
39// --------------------------------------------------------------------------- 37// ---------------------------------------------------------------------------
40 38
41module.exports = router 39export {
40 clientsRouter
41}
diff --git a/server/controllers/api/config.js b/server/controllers/api/config.js
deleted file mode 100644
index 8154b6ad0..000000000
--- a/server/controllers/api/config.js
+++ /dev/null
@@ -1,22 +0,0 @@
1'use strict'
2
3const express = require('express')
4
5const constants = require('../../initializers/constants')
6
7const router = express.Router()
8
9router.get('/', getConfig)
10
11// Get the client credentials for the PeerTube front end
12function getConfig (req, res, next) {
13 res.json({
14 signup: {
15 enabled: constants.CONFIG.SIGNUP.ENABLED
16 }
17 })
18}
19
20// ---------------------------------------------------------------------------
21
22module.exports = router
diff --git a/server/controllers/api/config.ts b/server/controllers/api/config.ts
new file mode 100644
index 000000000..8f3fa2473
--- /dev/null
+++ b/server/controllers/api/config.ts
@@ -0,0 +1,22 @@
1import express = require('express')
2
3import { CONFIG } from '../../initializers';
4
5const configRouter = express.Router()
6
7configRouter.get('/', getConfig)
8
9// Get the client credentials for the PeerTube front end
10function getConfig (req, res, next) {
11 res.json({
12 signup: {
13 enabled: CONFIG.SIGNUP.ENABLED
14 }
15 })
16}
17
18// ---------------------------------------------------------------------------
19
20export {
21 configRouter
22}
diff --git a/server/controllers/api/index.js b/server/controllers/api/index.js
deleted file mode 100644
index 6edc089f4..000000000
--- a/server/controllers/api/index.js
+++ /dev/null
@@ -1,35 +0,0 @@
1'use strict'
2
3const express = require('express')
4
5const utils = require('../../helpers/utils')
6
7const router = express.Router()
8
9const clientsController = require('./clients')
10const configController = require('./config')
11const podsController = require('./pods')
12const remoteController = require('./remote')
13const requestsController = require('./requests')
14const usersController = require('./users')
15const videosController = require('./videos')
16
17router.use('/clients', clientsController)
18router.use('/config', configController)
19router.use('/pods', podsController)
20router.use('/remote', remoteController)
21router.use('/requests', requestsController)
22router.use('/users', usersController)
23router.use('/videos', videosController)
24router.use('/ping', pong)
25router.use('/*', utils.badRequest)
26
27// ---------------------------------------------------------------------------
28
29module.exports = router
30
31// ---------------------------------------------------------------------------
32
33function pong (req, res, next) {
34 return res.send('pong').status(200).end()
35}
diff --git a/server/controllers/api/index.ts b/server/controllers/api/index.ts
new file mode 100644
index 000000000..18bef2d3d
--- /dev/null
+++ b/server/controllers/api/index.ts
@@ -0,0 +1,33 @@
1import express = require('express')
2
3import { badRequest } from '../../helpers'
4
5import { clientsRouter } from './clients'
6import { configRouter } from './config'
7import { podsRouter } from './pods'
8import { remoteRouter } from './remote'
9import { requestsRouter } from './requests'
10import { usersRouter } from './users'
11import { videosRouter } from './videos'
12
13const apiRouter = express.Router()
14
15apiRouter.use('/clients', clientsRouter)
16apiRouter.use('/config', configRouter)
17apiRouter.use('/pods', podsRouter)
18apiRouter.use('/remote', remoteRouter)
19apiRouter.use('/requests', requestsRouter)
20apiRouter.use('/users', usersRouter)
21apiRouter.use('/videos', videosRouter)
22apiRouter.use('/ping', pong)
23apiRouter.use('/*', badRequest)
24
25// ---------------------------------------------------------------------------
26
27export { apiRouter }
28
29// ---------------------------------------------------------------------------
30
31function pong (req, res, next) {
32 return res.send('pong').status(200).end()
33}
diff --git a/server/controllers/api/pods.js b/server/controllers/api/pods.js
deleted file mode 100644
index ab5763cf6..000000000
--- a/server/controllers/api/pods.js
+++ /dev/null
@@ -1,109 +0,0 @@
1'use strict'
2
3const express = require('express')
4const waterfall = require('async/waterfall')
5
6const db = require('../../initializers/database')
7const constants = require('../../initializers/constants')
8const logger = require('../../helpers/logger')
9const peertubeCrypto = require('../../helpers/peertube-crypto')
10const utils = require('../../helpers/utils')
11const friends = require('../../lib/friends')
12const middlewares = require('../../middlewares')
13const admin = middlewares.admin
14const oAuth = middlewares.oauth
15const podsMiddleware = middlewares.pods
16const validators = middlewares.validators.pods
17
18const router = express.Router()
19
20router.get('/', listPods)
21router.post('/',
22 podsMiddleware.setBodyHostPort, // We need to modify the host before running the validator!
23 validators.podsAdd,
24 addPods
25)
26router.post('/makefriends',
27 oAuth.authenticate,
28 admin.ensureIsAdmin,
29 validators.makeFriends,
30 podsMiddleware.setBodyHostsPort,
31 makeFriends
32)
33router.get('/quitfriends',
34 oAuth.authenticate,
35 admin.ensureIsAdmin,
36 quitFriends
37)
38
39// ---------------------------------------------------------------------------
40
41module.exports = router
42
43// ---------------------------------------------------------------------------
44
45function addPods (req, res, next) {
46 const informations = req.body
47
48 waterfall([
49 function addPod (callback) {
50 const pod = db.Pod.build(informations)
51 pod.save().asCallback(function (err, podCreated) {
52 // Be sure about the number of parameters for the callback
53 return callback(err, podCreated)
54 })
55 },
56
57 function sendMyVideos (podCreated, callback) {
58 friends.sendOwnedVideosToPod(podCreated.id)
59
60 callback(null)
61 },
62
63 function fetchMyCertificate (callback) {
64 peertubeCrypto.getMyPublicCert(function (err, cert) {
65 if (err) {
66 logger.error('Cannot read cert file.')
67 return callback(err)
68 }
69
70 return callback(null, cert)
71 })
72 }
73 ], function (err, cert) {
74 if (err) return next(err)
75
76 return res.json({ cert: cert, email: constants.CONFIG.ADMIN.EMAIL })
77 })
78}
79
80function listPods (req, res, next) {
81 db.Pod.list(function (err, podsList) {
82 if (err) return next(err)
83
84 res.json(utils.getFormatedObjects(podsList, podsList.length))
85 })
86}
87
88function makeFriends (req, res, next) {
89 const hosts = req.body.hosts
90
91 friends.makeFriends(hosts, function (err) {
92 if (err) {
93 logger.error('Could not make friends.', { error: err })
94 return
95 }
96
97 logger.info('Made friends!')
98 })
99
100 res.type('json').status(204).end()
101}
102
103function quitFriends (req, res, next) {
104 friends.quitFriends(function (err) {
105 if (err) return next(err)
106
107 res.type('json').status(204).end()
108 })
109}
diff --git a/server/controllers/api/pods.ts b/server/controllers/api/pods.ts
new file mode 100644
index 000000000..06dfd8295
--- /dev/null
+++ b/server/controllers/api/pods.ts
@@ -0,0 +1,118 @@
1import express = require('express')
2import { waterfall } from 'async'
3
4const db = require('../../initializers/database')
5import { CONFIG } from '../../initializers'
6import {
7 logger,
8 getMyPublicCert,
9 getFormatedObjects
10} from '../../helpers'
11import {
12 sendOwnedVideosToPod,
13 makeFriends,
14 quitFriends
15} from '../../lib'
16import {
17 podsAddValidator,
18 authenticate,
19 ensureIsAdmin,
20 makeFriendsValidator,
21 setBodyHostPort,
22 setBodyHostsPort
23} from '../../middlewares'
24
25const podsRouter = express.Router()
26
27podsRouter.get('/', listPods)
28podsRouter.post('/',
29 setBodyHostPort, // We need to modify the host before running the validator!
30 podsAddValidator,
31 addPods
32)
33podsRouter.post('/makefriends',
34 authenticate,
35 ensureIsAdmin,
36 makeFriendsValidator,
37 setBodyHostsPort,
38 makeFriends
39)
40podsRouter.get('/quitfriends',
41 authenticate,
42 ensureIsAdmin,
43 quitFriends
44)
45
46// ---------------------------------------------------------------------------
47
48export {
49 podsRouter
50}
51
52// ---------------------------------------------------------------------------
53
54function addPods (req, res, next) {
55 const informations = req.body
56
57 waterfall([
58 function addPod (callback) {
59 const pod = db.Pod.build(informations)
60 pod.save().asCallback(function (err, podCreated) {
61 // Be sure about the number of parameters for the callback
62 return callback(err, podCreated)
63 })
64 },
65
66 function sendMyVideos (podCreated, callback) {
67 sendOwnedVideosToPod(podCreated.id)
68
69 callback(null)
70 },
71
72 function fetchMyCertificate (callback) {
73 getMyPublicCert(function (err, cert) {
74 if (err) {
75 logger.error('Cannot read cert file.')
76 return callback(err)
77 }
78
79 return callback(null, cert)
80 })
81 }
82 ], function (err, cert) {
83 if (err) return next(err)
84
85 return res.json({ cert: cert, email: CONFIG.ADMIN.EMAIL })
86 })
87}
88
89function listPods (req, res, next) {
90 db.Pod.list(function (err, podsList) {
91 if (err) return next(err)
92
93 res.json(getFormatedObjects(podsList, podsList.length))
94 })
95}
96
97function makeFriendsController (req, res, next) {
98 const hosts = req.body.hosts
99
100 makeFriends(hosts, function (err) {
101 if (err) {
102 logger.error('Could not make friends.', { error: err })
103 return
104 }
105
106 logger.info('Made friends!')
107 })
108
109 res.type('json').status(204).end()
110}
111
112function quitFriendsController (req, res, next) {
113 quitFriends(function (err) {
114 if (err) return next(err)
115
116 res.type('json').status(204).end()
117 })
118}
diff --git a/server/controllers/api/remote/index.js b/server/controllers/api/remote/index.js
deleted file mode 100644
index 6106850ab..000000000
--- a/server/controllers/api/remote/index.js
+++ /dev/null
@@ -1,18 +0,0 @@
1'use strict'
2
3const express = require('express')
4
5const utils = require('../../../helpers/utils')
6
7const router = express.Router()
8
9const podsRemoteController = require('./pods')
10const videosRemoteController = require('./videos')
11
12router.use('/pods', podsRemoteController)
13router.use('/videos', videosRemoteController)
14router.use('/*', utils.badRequest)
15
16// ---------------------------------------------------------------------------
17
18module.exports = router
diff --git a/server/controllers/api/remote/index.ts b/server/controllers/api/remote/index.ts
new file mode 100644
index 000000000..b11439204
--- /dev/null
+++ b/server/controllers/api/remote/index.ts
@@ -0,0 +1,18 @@
1import express = require('express')
2
3import { badRequest } from '../../../helpers'
4
5import { remotePodsRouter } from './pods'
6import { remoteVideosRouter } from './videos'
7
8const remoteRouter = express.Router()
9
10remoteRouter.use('/pods', remotePodsRouter)
11remoteRouter.use('/videos', remoteVideosRouter)
12remoteRouter.use('/*', badRequest)
13
14// ---------------------------------------------------------------------------
15
16export {
17 remoteRouter
18}
diff --git a/server/controllers/api/remote/pods.js b/server/controllers/api/remote/pods.ts
index 0343bc62e..85ef7bb42 100644
--- a/server/controllers/api/remote/pods.js
+++ b/server/controllers/api/remote/pods.ts
@@ -1,25 +1,23 @@
1'use strict' 1import express = require('express')
2 2import { waterfall } from 'async/waterfall'
3const express = require('express')
4const waterfall = require('async/waterfall')
5 3
6const db = require('../../../initializers/database') 4const db = require('../../../initializers/database')
7const middlewares = require('../../../middlewares') 5import { checkSignature, signatureValidator } from '../../../middlewares'
8const checkSignature = middlewares.secure.checkSignature
9const signatureValidator = middlewares.validators.remote.signature
10 6
11const router = express.Router() 7const remotePodsRouter = express.Router()
12 8
13// Post because this is a secured request 9// Post because this is a secured request
14router.post('/remove', 10remotePodsRouter.post('/remove',
15 signatureValidator.signature, 11 signatureValidator,
16 checkSignature, 12 checkSignature,
17 removePods 13 removePods
18) 14)
19 15
20// --------------------------------------------------------------------------- 16// ---------------------------------------------------------------------------
21 17
22module.exports = router 18export {
19 remotePodsRouter
20}
23 21
24// --------------------------------------------------------------------------- 22// ---------------------------------------------------------------------------
25 23
diff --git a/server/controllers/api/remote/videos.js b/server/controllers/api/remote/videos.ts
index e54793628..df4ba8309 100644
--- a/server/controllers/api/remote/videos.js
+++ b/server/controllers/api/remote/videos.ts
@@ -1,20 +1,30 @@
1'use strict' 1import express = require('express')
2 2import { eachSeries, waterfall } from 'async'
3const eachSeries = require('async/eachSeries')
4const express = require('express')
5const waterfall = require('async/waterfall')
6 3
7const db = require('../../../initializers/database') 4const db = require('../../../initializers/database')
8const constants = require('../../../initializers/constants') 5import {
9const middlewares = require('../../../middlewares') 6 REQUEST_ENDPOINT_ACTIONS,
10const secureMiddleware = middlewares.secure 7 REQUEST_ENDPOINTS,
11const videosValidators = middlewares.validators.remote.videos 8 REQUEST_VIDEO_EVENT_TYPES,
12const signatureValidators = middlewares.validators.remote.signature 9 REQUEST_VIDEO_QADU_TYPES
13const logger = require('../../../helpers/logger') 10} from '../../../initializers'
14const friends = require('../../../lib/friends') 11import {
15const databaseUtils = require('../../../helpers/database-utils') 12 checkSignature,
16 13 signatureValidator,
17const ENDPOINT_ACTIONS = constants.REQUEST_ENDPOINT_ACTIONS[constants.REQUEST_ENDPOINTS.VIDEOS] 14 remoteVideosValidator,
15 remoteQaduVideosValidator,
16 remoteEventsVideosValidator
17} from '../../../middlewares'
18import {
19 logger,
20 commitTransaction,
21 retryTransactionWrapper,
22 rollbackTransaction,
23 startSerializableTransaction
24} from '../../../helpers'
25import { quickAndDirtyUpdatesVideoToFriends } from '../../../lib'
26
27const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
18 28
19// Functions to call when processing a remote request 29// Functions to call when processing a remote request
20const functionsHash = {} 30const functionsHash = {}
@@ -23,32 +33,34 @@ functionsHash[ENDPOINT_ACTIONS.UPDATE] = updateRemoteVideoRetryWrapper
23functionsHash[ENDPOINT_ACTIONS.REMOVE] = removeRemoteVideo 33functionsHash[ENDPOINT_ACTIONS.REMOVE] = removeRemoteVideo
24functionsHash[ENDPOINT_ACTIONS.REPORT_ABUSE] = reportAbuseRemoteVideo 34functionsHash[ENDPOINT_ACTIONS.REPORT_ABUSE] = reportAbuseRemoteVideo
25 35
26const router = express.Router() 36const remoteVideosRouter = express.Router()
27 37
28router.post('/', 38remoteVideosRouter.post('/',
29 signatureValidators.signature, 39 signatureValidator,
30 secureMiddleware.checkSignature, 40 checkSignature,
31 videosValidators.remoteVideos, 41 remoteVideosValidator,
32 remoteVideos 42 remoteVideos
33) 43)
34 44
35router.post('/qadu', 45remoteVideosRouter.post('/qadu',
36 signatureValidators.signature, 46 signatureValidator,
37 secureMiddleware.checkSignature, 47 checkSignature,
38 videosValidators.remoteQaduVideos, 48 remoteQaduVideosValidator,
39 remoteVideosQadu 49 remoteVideosQadu
40) 50)
41 51
42router.post('/events', 52remoteVideosRouter.post('/events',
43 signatureValidators.signature, 53 signatureValidator,
44 secureMiddleware.checkSignature, 54 checkSignature,
45 videosValidators.remoteEventsVideos, 55 remoteEventsVideosValidator,
46 remoteVideosEvents 56 remoteVideosEvents
47) 57)
48 58
49// --------------------------------------------------------------------------- 59// ---------------------------------------------------------------------------
50 60
51module.exports = router 61export {
62 remoteVideosRouter
63}
52 64
53// --------------------------------------------------------------------------- 65// ---------------------------------------------------------------------------
54 66
@@ -58,7 +70,7 @@ function remoteVideos (req, res, next) {
58 70
59 // We need to process in the same order to keep consistency 71 // We need to process in the same order to keep consistency
60 // TODO: optimization 72 // TODO: optimization
61 eachSeries(requests, function (request, callbackEach) { 73 eachSeries(requests, function (request: any, callbackEach) {
62 const data = request.data 74 const data = request.data
63 75
64 // Get the function we need to call in order to process the request 76 // Get the function we need to call in order to process the request
@@ -81,7 +93,7 @@ function remoteVideosQadu (req, res, next) {
81 const requests = req.body.data 93 const requests = req.body.data
82 const fromPod = res.locals.secure.pod 94 const fromPod = res.locals.secure.pod
83 95
84 eachSeries(requests, function (request, callbackEach) { 96 eachSeries(requests, function (request: any, callbackEach) {
85 const videoData = request.data 97 const videoData = request.data
86 98
87 quickAndDirtyUpdateVideoRetryWrapper(videoData, fromPod, callbackEach) 99 quickAndDirtyUpdateVideoRetryWrapper(videoData, fromPod, callbackEach)
@@ -96,7 +108,7 @@ function remoteVideosEvents (req, res, next) {
96 const requests = req.body.data 108 const requests = req.body.data
97 const fromPod = res.locals.secure.pod 109 const fromPod = res.locals.secure.pod
98 110
99 eachSeries(requests, function (request, callbackEach) { 111 eachSeries(requests, function (request: any, callbackEach) {
100 const eventData = request.data 112 const eventData = request.data
101 113
102 processVideosEventsRetryWrapper(eventData, fromPod, callbackEach) 114 processVideosEventsRetryWrapper(eventData, fromPod, callbackEach)
@@ -113,12 +125,12 @@ function processVideosEventsRetryWrapper (eventData, fromPod, finalCallback) {
113 errorMessage: 'Cannot process videos events with many retries.' 125 errorMessage: 'Cannot process videos events with many retries.'
114 } 126 }
115 127
116 databaseUtils.retryTransactionWrapper(processVideosEvents, options, finalCallback) 128 retryTransactionWrapper(processVideosEvents, options, finalCallback)
117} 129}
118 130
119function processVideosEvents (eventData, fromPod, finalCallback) { 131function processVideosEvents (eventData, fromPod, finalCallback) {
120 waterfall([ 132 waterfall([
121 databaseUtils.startSerializableTransaction, 133 startSerializableTransaction,
122 134
123 function findVideo (t, callback) { 135 function findVideo (t, callback) {
124 fetchOwnedVideo(eventData.remoteId, function (err, videoInstance) { 136 fetchOwnedVideo(eventData.remoteId, function (err, videoInstance) {
@@ -133,19 +145,19 @@ function processVideosEvents (eventData, fromPod, finalCallback) {
133 let qaduType 145 let qaduType
134 146
135 switch (eventData.eventType) { 147 switch (eventData.eventType) {
136 case constants.REQUEST_VIDEO_EVENT_TYPES.VIEWS: 148 case REQUEST_VIDEO_EVENT_TYPES.VIEWS:
137 columnToUpdate = 'views' 149 columnToUpdate = 'views'
138 qaduType = constants.REQUEST_VIDEO_QADU_TYPES.VIEWS 150 qaduType = REQUEST_VIDEO_QADU_TYPES.VIEWS
139 break 151 break
140 152
141 case constants.REQUEST_VIDEO_EVENT_TYPES.LIKES: 153 case REQUEST_VIDEO_EVENT_TYPES.LIKES:
142 columnToUpdate = 'likes' 154 columnToUpdate = 'likes'
143 qaduType = constants.REQUEST_VIDEO_QADU_TYPES.LIKES 155 qaduType = REQUEST_VIDEO_QADU_TYPES.LIKES
144 break 156 break
145 157
146 case constants.REQUEST_VIDEO_EVENT_TYPES.DISLIKES: 158 case REQUEST_VIDEO_EVENT_TYPES.DISLIKES:
147 columnToUpdate = 'dislikes' 159 columnToUpdate = 'dislikes'
148 qaduType = constants.REQUEST_VIDEO_QADU_TYPES.DISLIKES 160 qaduType = REQUEST_VIDEO_QADU_TYPES.DISLIKES
149 break 161 break
150 162
151 default: 163 default:
@@ -168,17 +180,17 @@ function processVideosEvents (eventData, fromPod, finalCallback) {
168 } 180 }
169 ] 181 ]
170 182
171 friends.quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) { 183 quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) {
172 return callback(err, t) 184 return callback(err, t)
173 }) 185 })
174 }, 186 },
175 187
176 databaseUtils.commitTransaction 188 commitTransaction
177 189
178 ], function (err, t) { 190 ], function (err, t) {
179 if (err) { 191 if (err) {
180 logger.debug('Cannot process a video event.', { error: err }) 192 logger.debug('Cannot process a video event.', { error: err })
181 return databaseUtils.rollbackTransaction(err, t, finalCallback) 193 return rollbackTransaction(err, t, finalCallback)
182 } 194 }
183 195
184 logger.info('Remote video event processed for video %s.', eventData.remoteId) 196 logger.info('Remote video event processed for video %s.', eventData.remoteId)
@@ -192,14 +204,14 @@ function quickAndDirtyUpdateVideoRetryWrapper (videoData, fromPod, finalCallback
192 errorMessage: 'Cannot update quick and dirty the remote video with many retries.' 204 errorMessage: 'Cannot update quick and dirty the remote video with many retries.'
193 } 205 }
194 206
195 databaseUtils.retryTransactionWrapper(quickAndDirtyUpdateVideo, options, finalCallback) 207 retryTransactionWrapper(quickAndDirtyUpdateVideo, options, finalCallback)
196} 208}
197 209
198function quickAndDirtyUpdateVideo (videoData, fromPod, finalCallback) { 210function quickAndDirtyUpdateVideo (videoData, fromPod, finalCallback) {
199 let videoName 211 let videoName
200 212
201 waterfall([ 213 waterfall([
202 databaseUtils.startSerializableTransaction, 214 startSerializableTransaction,
203 215
204 function findVideo (t, callback) { 216 function findVideo (t, callback) {
205 fetchRemoteVideo(fromPod.host, videoData.remoteId, function (err, videoInstance) { 217 fetchRemoteVideo(fromPod.host, videoData.remoteId, function (err, videoInstance) {
@@ -229,12 +241,12 @@ function quickAndDirtyUpdateVideo (videoData, fromPod, finalCallback) {
229 }) 241 })
230 }, 242 },
231 243
232 databaseUtils.commitTransaction 244 commitTransaction
233 245
234 ], function (err, t) { 246 ], function (err, t) {
235 if (err) { 247 if (err) {
236 logger.debug('Cannot quick and dirty update the remote video.', { error: err }) 248 logger.debug('Cannot quick and dirty update the remote video.', { error: err })
237 return databaseUtils.rollbackTransaction(err, t, finalCallback) 249 return rollbackTransaction(err, t, finalCallback)
238 } 250 }
239 251
240 logger.info('Remote video %s quick and dirty updated', videoName) 252 logger.info('Remote video %s quick and dirty updated', videoName)
@@ -249,7 +261,7 @@ function addRemoteVideoRetryWrapper (videoToCreateData, fromPod, finalCallback)
249 errorMessage: 'Cannot insert the remote video with many retries.' 261 errorMessage: 'Cannot insert the remote video with many retries.'
250 } 262 }
251 263
252 databaseUtils.retryTransactionWrapper(addRemoteVideo, options, finalCallback) 264 retryTransactionWrapper(addRemoteVideo, options, finalCallback)
253} 265}
254 266
255function addRemoteVideo (videoToCreateData, fromPod, finalCallback) { 267function addRemoteVideo (videoToCreateData, fromPod, finalCallback) {
@@ -257,7 +269,7 @@ function addRemoteVideo (videoToCreateData, fromPod, finalCallback) {
257 269
258 waterfall([ 270 waterfall([
259 271
260 databaseUtils.startSerializableTransaction, 272 startSerializableTransaction,
261 273
262 function assertRemoteIdAndHostUnique (t, callback) { 274 function assertRemoteIdAndHostUnique (t, callback) {
263 db.Video.loadByHostAndRemoteId(fromPod.host, videoToCreateData.remoteId, function (err, video) { 275 db.Video.loadByHostAndRemoteId(fromPod.host, videoToCreateData.remoteId, function (err, video) {
@@ -345,13 +357,13 @@ function addRemoteVideo (videoToCreateData, fromPod, finalCallback) {
345 }) 357 })
346 }, 358 },
347 359
348 databaseUtils.commitTransaction 360 commitTransaction
349 361
350 ], function (err, t) { 362 ], function (err, t) {
351 if (err) { 363 if (err) {
352 // This is just a debug because we will retry the insert 364 // This is just a debug because we will retry the insert
353 logger.debug('Cannot insert the remote video.', { error: err }) 365 logger.debug('Cannot insert the remote video.', { error: err })
354 return databaseUtils.rollbackTransaction(err, t, finalCallback) 366 return rollbackTransaction(err, t, finalCallback)
355 } 367 }
356 368
357 logger.info('Remote video %s inserted.', videoToCreateData.name) 369 logger.info('Remote video %s inserted.', videoToCreateData.name)
@@ -366,7 +378,7 @@ function updateRemoteVideoRetryWrapper (videoAttributesToUpdate, fromPod, finalC
366 errorMessage: 'Cannot update the remote video with many retries' 378 errorMessage: 'Cannot update the remote video with many retries'
367 } 379 }
368 380
369 databaseUtils.retryTransactionWrapper(updateRemoteVideo, options, finalCallback) 381 retryTransactionWrapper(updateRemoteVideo, options, finalCallback)
370} 382}
371 383
372function updateRemoteVideo (videoAttributesToUpdate, fromPod, finalCallback) { 384function updateRemoteVideo (videoAttributesToUpdate, fromPod, finalCallback) {
@@ -374,7 +386,7 @@ function updateRemoteVideo (videoAttributesToUpdate, fromPod, finalCallback) {
374 386
375 waterfall([ 387 waterfall([
376 388
377 databaseUtils.startSerializableTransaction, 389 startSerializableTransaction,
378 390
379 function findVideo (t, callback) { 391 function findVideo (t, callback) {
380 fetchRemoteVideo(fromPod.host, videoAttributesToUpdate.remoteId, function (err, videoInstance) { 392 fetchRemoteVideo(fromPod.host, videoAttributesToUpdate.remoteId, function (err, videoInstance) {
@@ -421,13 +433,13 @@ function updateRemoteVideo (videoAttributesToUpdate, fromPod, finalCallback) {
421 }) 433 })
422 }, 434 },
423 435
424 databaseUtils.commitTransaction 436 commitTransaction
425 437
426 ], function (err, t) { 438 ], function (err, t) {
427 if (err) { 439 if (err) {
428 // This is just a debug because we will retry the insert 440 // This is just a debug because we will retry the insert
429 logger.debug('Cannot update the remote video.', { error: err }) 441 logger.debug('Cannot update the remote video.', { error: err })
430 return databaseUtils.rollbackTransaction(err, t, finalCallback) 442 return rollbackTransaction(err, t, finalCallback)
431 } 443 }
432 444
433 logger.info('Remote video %s updated', videoAttributesToUpdate.name) 445 logger.info('Remote video %s updated', videoAttributesToUpdate.name)
diff --git a/server/controllers/api/requests.js b/server/controllers/api/requests.ts
index 6fd5753ac..304499a4f 100644
--- a/server/controllers/api/requests.js
+++ b/server/controllers/api/requests.ts
@@ -1,32 +1,34 @@
1'use strict' 1import express = require('express')
2import { parallel } from 'async'
2 3
3const express = require('express') 4import {
4const parallel = require('async/parallel') 5 getRequestScheduler,
6 getRequestVideoQaduScheduler,
7 getRequestVideoEventScheduler
8} from '../../lib'
9import { authenticate, ensureIsAdmin } from '../../middlewares'
5 10
6const friends = require('../../lib/friends') 11const requestsRouter = express.Router()
7const middlewares = require('../../middlewares')
8const admin = middlewares.admin
9const oAuth = middlewares.oauth
10 12
11const router = express.Router() 13requestsRouter.get('/stats',
12 14 authenticate,
13router.get('/stats', 15 ensureIsAdmin,
14 oAuth.authenticate,
15 admin.ensureIsAdmin,
16 getStatsRequests 16 getStatsRequests
17) 17)
18 18
19// --------------------------------------------------------------------------- 19// ---------------------------------------------------------------------------
20 20
21module.exports = router 21export {
22 requestsRouter
23}
22 24
23// --------------------------------------------------------------------------- 25// ---------------------------------------------------------------------------
24 26
25function getStatsRequests (req, res, next) { 27function getStatsRequests (req, res, next) {
26 parallel({ 28 parallel({
27 requestScheduler: buildRequestSchedulerFunction(friends.getRequestScheduler()), 29 requestScheduler: buildRequestSchedulerFunction(getRequestScheduler()),
28 requestVideoQaduScheduler: buildRequestSchedulerFunction(friends.getRequestVideoQaduScheduler()), 30 requestVideoQaduScheduler: buildRequestSchedulerFunction(getRequestVideoQaduScheduler()),
29 requestVideoEventScheduler: buildRequestSchedulerFunction(friends.getRequestVideoEventScheduler()) 31 requestVideoEventScheduler: buildRequestSchedulerFunction(getRequestVideoEventScheduler())
30 }, function (err, result) { 32 }, function (err, result) {
31 if (err) return next(err) 33 if (err) return next(err)
32 34
diff --git a/server/controllers/api/users.js b/server/controllers/api/users.ts
index c7fe7bf85..981a4706a 100644
--- a/server/controllers/api/users.js
+++ b/server/controllers/api/users.ts
@@ -1,79 +1,83 @@
1'use strict' 1import express = require('express')
2import { waterfall } from 'async'
2 3
3const express = require('express')
4const waterfall = require('async/waterfall')
5
6const constants = require('../../initializers/constants')
7const db = require('../../initializers/database') 4const db = require('../../initializers/database')
8const logger = require('../../helpers/logger') 5import { CONFIG, USER_ROLES } from '../../initializers'
9const utils = require('../../helpers/utils') 6import { logger, getFormatedObjects } from '../../helpers'
10const middlewares = require('../../middlewares') 7import {
11const admin = middlewares.admin 8 authenticate,
12const oAuth = middlewares.oauth 9 ensureIsAdmin,
13const pagination = middlewares.pagination 10 usersAddValidator,
14const sort = middlewares.sort 11 usersUpdateValidator,
15const validatorsPagination = middlewares.validators.pagination 12 usersRemoveValidator,
16const validatorsSort = middlewares.validators.sort 13 usersVideoRatingValidator,
17const validatorsUsers = middlewares.validators.users 14 paginationValidator,
18 15 setPagination,
19const router = express.Router() 16 usersSortValidator,
20 17 setUsersSort,
21router.get('/me', 18 token
22 oAuth.authenticate, 19} from '../../middlewares'
20
21const usersRouter = express.Router()
22
23usersRouter.get('/me',
24 authenticate,
23 getUserInformation 25 getUserInformation
24) 26)
25 27
26router.get('/me/videos/:videoId/rating', 28usersRouter.get('/me/videos/:videoId/rating',
27 oAuth.authenticate, 29 authenticate,
28 validatorsUsers.usersVideoRating, 30 usersVideoRatingValidator,
29 getUserVideoRating 31 getUserVideoRating
30) 32)
31 33
32router.get('/', 34usersRouter.get('/',
33 validatorsPagination.pagination, 35 paginationValidator,
34 validatorsSort.usersSort, 36 usersSortValidator,
35 sort.setUsersSort, 37 setUsersSort,
36 pagination.setPagination, 38 setPagination,
37 listUsers 39 listUsers
38) 40)
39 41
40router.post('/', 42usersRouter.post('/',
41 oAuth.authenticate, 43 authenticate,
42 admin.ensureIsAdmin, 44 ensureIsAdmin,
43 validatorsUsers.usersAdd, 45 usersAddValidator,
44 createUser 46 createUser
45) 47)
46 48
47router.post('/register', 49usersRouter.post('/register',
48 ensureRegistrationEnabled, 50 ensureRegistrationEnabled,
49 validatorsUsers.usersAdd, 51 usersAddValidator,
50 createUser 52 createUser
51) 53)
52 54
53router.put('/:id', 55usersRouter.put('/:id',
54 oAuth.authenticate, 56 authenticate,
55 validatorsUsers.usersUpdate, 57 usersUpdateValidator,
56 updateUser 58 updateUser
57) 59)
58 60
59router.delete('/:id', 61usersRouter.delete('/:id',
60 oAuth.authenticate, 62 authenticate,
61 admin.ensureIsAdmin, 63 ensureIsAdmin,
62 validatorsUsers.usersRemove, 64 usersRemoveValidator,
63 removeUser 65 removeUser
64) 66)
65 67
66router.post('/token', oAuth.token, success) 68usersRouter.post('/token', token, success)
67// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route 69// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
68 70
69// --------------------------------------------------------------------------- 71// ---------------------------------------------------------------------------
70 72
71module.exports = router 73export {
74 usersRouter
75}
72 76
73// --------------------------------------------------------------------------- 77// ---------------------------------------------------------------------------
74 78
75function ensureRegistrationEnabled (req, res, next) { 79function ensureRegistrationEnabled (req, res, next) {
76 const registrationEnabled = constants.CONFIG.SIGNUP.ENABLED 80 const registrationEnabled = CONFIG.SIGNUP.ENABLED
77 81
78 if (registrationEnabled === true) { 82 if (registrationEnabled === true) {
79 return next() 83 return next()
@@ -88,7 +92,7 @@ function createUser (req, res, next) {
88 password: req.body.password, 92 password: req.body.password,
89 email: req.body.email, 93 email: req.body.email,
90 displayNSFW: false, 94 displayNSFW: false,
91 role: constants.USER_ROLES.USER 95 role: USER_ROLES.USER
92 }) 96 })
93 97
94 user.save().asCallback(function (err, createdUser) { 98 user.save().asCallback(function (err, createdUser) {
@@ -126,7 +130,7 @@ function listUsers (req, res, next) {
126 db.User.listForApi(req.query.start, req.query.count, req.query.sort, function (err, usersList, usersTotal) { 130 db.User.listForApi(req.query.start, req.query.count, req.query.sort, function (err, usersList, usersTotal) {
127 if (err) return next(err) 131 if (err) return next(err)
128 132
129 res.json(utils.getFormatedObjects(usersList, usersTotal)) 133 res.json(getFormatedObjects(usersList, usersTotal))
130 }) 134 })
131} 135}
132 136
diff --git a/server/controllers/api/videos/abuse.js b/server/controllers/api/videos/abuse.ts
index 0fb44bb14..88204120f 100644
--- a/server/controllers/api/videos/abuse.js
+++ b/server/controllers/api/videos/abuse.ts
@@ -1,43 +1,48 @@
1'use strict' 1import express = require('express')
2 2import { waterfall } from 'async'
3const express = require('express')
4const waterfall = require('async/waterfall')
5 3
6const db = require('../../../initializers/database') 4const db = require('../../../initializers/database')
7const logger = require('../../../helpers/logger') 5import friends = require('../../../lib/friends')
8const friends = require('../../../lib/friends') 6import {
9const middlewares = require('../../../middlewares') 7 logger,
10const admin = middlewares.admin 8 getFormatedObjects,
11const oAuth = middlewares.oauth 9 retryTransactionWrapper,
12const pagination = middlewares.pagination 10 startSerializableTransaction,
13const validators = middlewares.validators 11 commitTransaction,
14const validatorsPagination = validators.pagination 12 rollbackTransaction
15const validatorsSort = validators.sort 13} from '../../../helpers'
16const validatorsVideos = validators.videos 14import {
17const sort = middlewares.sort 15 authenticate,
18const databaseUtils = require('../../../helpers/database-utils') 16 ensureIsAdmin,
19const utils = require('../../../helpers/utils') 17 paginationValidator,
20 18 videoAbuseReportValidator,
21const router = express.Router() 19 videoAbusesSortValidator,
22 20 setVideoAbusesSort,
23router.get('/abuse', 21 setPagination
24 oAuth.authenticate, 22} from '../../../middlewares'
25 admin.ensureIsAdmin, 23
26 validatorsPagination.pagination, 24const abuseVideoRouter = express.Router()
27 validatorsSort.videoAbusesSort, 25
28 sort.setVideoAbusesSort, 26abuseVideoRouter.get('/abuse',
29 pagination.setPagination, 27 authenticate,
28 ensureIsAdmin,
29 paginationValidator,
30 videoAbusesSortValidator,
31 setVideoAbusesSort,
32 setPagination,
30 listVideoAbuses 33 listVideoAbuses
31) 34)
32router.post('/:id/abuse', 35abuseVideoRouter.post('/:id/abuse',
33 oAuth.authenticate, 36 authenticate,
34 validatorsVideos.videoAbuseReport, 37 videoAbuseReportValidator,
35 reportVideoAbuseRetryWrapper 38 reportVideoAbuseRetryWrapper
36) 39)
37 40
38// --------------------------------------------------------------------------- 41// ---------------------------------------------------------------------------
39 42
40module.exports = router 43export {
44 abuseVideoRouter
45}
41 46
42// --------------------------------------------------------------------------- 47// ---------------------------------------------------------------------------
43 48
@@ -45,7 +50,7 @@ function listVideoAbuses (req, res, next) {
45 db.VideoAbuse.listForApi(req.query.start, req.query.count, req.query.sort, function (err, abusesList, abusesTotal) { 50 db.VideoAbuse.listForApi(req.query.start, req.query.count, req.query.sort, function (err, abusesList, abusesTotal) {
46 if (err) return next(err) 51 if (err) return next(err)
47 52
48 res.json(utils.getFormatedObjects(abusesList, abusesTotal)) 53 res.json(getFormatedObjects(abusesList, abusesTotal))
49 }) 54 })
50} 55}
51 56
@@ -55,7 +60,7 @@ function reportVideoAbuseRetryWrapper (req, res, next) {
55 errorMessage: 'Cannot report abuse to the video with many retries.' 60 errorMessage: 'Cannot report abuse to the video with many retries.'
56 } 61 }
57 62
58 databaseUtils.retryTransactionWrapper(reportVideoAbuse, options, function (err) { 63 retryTransactionWrapper(reportVideoAbuse, options, function (err) {
59 if (err) return next(err) 64 if (err) return next(err)
60 65
61 return res.type('json').status(204).end() 66 return res.type('json').status(204).end()
@@ -75,7 +80,7 @@ function reportVideoAbuse (req, res, finalCallback) {
75 80
76 waterfall([ 81 waterfall([
77 82
78 databaseUtils.startSerializableTransaction, 83 startSerializableTransaction,
79 84
80 function createAbuse (t, callback) { 85 function createAbuse (t, callback) {
81 db.VideoAbuse.create(abuse).asCallback(function (err, abuse) { 86 db.VideoAbuse.create(abuse).asCallback(function (err, abuse) {
@@ -98,12 +103,12 @@ function reportVideoAbuse (req, res, finalCallback) {
98 return callback(null, t) 103 return callback(null, t)
99 }, 104 },
100 105
101 databaseUtils.commitTransaction 106 commitTransaction
102 107
103 ], function andFinally (err, t) { 108 ], function andFinally (err, t) {
104 if (err) { 109 if (err) {
105 logger.debug('Cannot update the video.', { error: err }) 110 logger.debug('Cannot update the video.', { error: err })
106 return databaseUtils.rollbackTransaction(err, t, finalCallback) 111 return rollbackTransaction(err, t, finalCallback)
107 } 112 }
108 113
109 logger.info('Abuse report for video %s created.', videoInstance.name) 114 logger.info('Abuse report for video %s created.', videoInstance.name)
diff --git a/server/controllers/api/videos/blacklist.js b/server/controllers/api/videos/blacklist.ts
index 8c3e2a69d..db6d95e73 100644
--- a/server/controllers/api/videos/blacklist.js
+++ b/server/controllers/api/videos/blacklist.ts
@@ -1,27 +1,27 @@
1'use strict' 1import express = require('express')
2
3const express = require('express')
4 2
5const db = require('../../../initializers/database') 3const db = require('../../../initializers/database')
6const logger = require('../../../helpers/logger') 4import { logger } from '../../../helpers'
7const middlewares = require('../../../middlewares') 5import {
8const admin = middlewares.admin 6 authenticate,
9const oAuth = middlewares.oauth 7 ensureIsAdmin,
10const validators = middlewares.validators 8 videosBlacklistValidator
11const validatorsVideos = validators.videos 9} from '../../../middlewares'
12 10
13const router = express.Router() 11const blacklistRouter = express.Router()
14 12
15router.post('/:id/blacklist', 13blacklistRouter.post('/:id/blacklist',
16 oAuth.authenticate, 14 authenticate,
17 admin.ensureIsAdmin, 15 ensureIsAdmin,
18 validatorsVideos.videosBlacklist, 16 videosBlacklistValidator,
19 addVideoToBlacklist 17 addVideoToBlacklist
20) 18)
21 19
22// --------------------------------------------------------------------------- 20// ---------------------------------------------------------------------------
23 21
24module.exports = router 22export {
23 blacklistRouter
24}
25 25
26// --------------------------------------------------------------------------- 26// ---------------------------------------------------------------------------
27 27
diff --git a/server/controllers/api/videos/index.js b/server/controllers/api/videos/index.ts
index 8de44d5ac..5fbf03676 100644
--- a/server/controllers/api/videos/index.js
+++ b/server/controllers/api/videos/index.ts
@@ -1,37 +1,57 @@
1'use strict' 1import express = require('express')
2import fs = require('fs')
3import multer = require('multer')
4import path = require('path')
5import { waterfall } from 'async'
2 6
3const express = require('express')
4const fs = require('fs')
5const multer = require('multer')
6const path = require('path')
7const waterfall = require('async/waterfall')
8
9const constants = require('../../../initializers/constants')
10const db = require('../../../initializers/database') 7const db = require('../../../initializers/database')
11const logger = require('../../../helpers/logger') 8import {
12const friends = require('../../../lib/friends') 9 CONFIG,
13const middlewares = require('../../../middlewares') 10 REQUEST_VIDEO_QADU_TYPES,
14const oAuth = middlewares.oauth 11 REQUEST_VIDEO_EVENT_TYPES,
15const pagination = middlewares.pagination 12 VIDEO_CATEGORIES,
16const validators = middlewares.validators 13 VIDEO_LICENCES,
17const validatorsPagination = validators.pagination 14 VIDEO_LANGUAGES
18const validatorsSort = validators.sort 15} from '../../../initializers'
19const validatorsVideos = validators.videos 16import {
20const search = middlewares.search 17 addEventToRemoteVideo,
21const sort = middlewares.sort 18 quickAndDirtyUpdateVideoToFriends,
22const databaseUtils = require('../../../helpers/database-utils') 19 addVideoToFriends,
23const utils = require('../../../helpers/utils') 20 updateVideoToFriends
24 21} from '../../../lib'
25const abuseController = require('./abuse') 22import {
26const blacklistController = require('./blacklist') 23 authenticate,
27const rateController = require('./rate') 24 paginationValidator,
28 25 videosSortValidator,
29const router = express.Router() 26 setVideosSort,
27 setPagination,
28 setVideosSearch,
29 videosUpdateValidator,
30 videosSearchValidator,
31 videosAddValidator,
32 videosGetValidator,
33 videosRemoveValidator
34} from '../../../middlewares'
35import {
36 logger,
37 commitTransaction,
38 retryTransactionWrapper,
39 rollbackTransaction,
40 startSerializableTransaction,
41 generateRandomString,
42 getFormatedObjects
43} from '../../../helpers'
44
45import { abuseVideoRouter } from './abuse'
46import { blacklistRouter } from './blacklist'
47import { rateVideoRouter } from './rate'
48
49const videosRouter = express.Router()
30 50
31// multer configuration 51// multer configuration
32const storage = multer.diskStorage({ 52const storage = multer.diskStorage({
33 destination: function (req, file, cb) { 53 destination: function (req, file, cb) {
34 cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR) 54 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
35 }, 55 },
36 56
37 filename: function (req, file, cb) { 57 filename: function (req, file, cb) {
@@ -39,7 +59,7 @@ const storage = multer.diskStorage({
39 if (file.mimetype === 'video/webm') extension = 'webm' 59 if (file.mimetype === 'video/webm') extension = 'webm'
40 else if (file.mimetype === 'video/mp4') extension = 'mp4' 60 else if (file.mimetype === 'video/mp4') extension = 'mp4'
41 else if (file.mimetype === 'video/ogg') extension = 'ogv' 61 else if (file.mimetype === 'video/ogg') extension = 'ogv'
42 utils.generateRandomString(16, function (err, randomString) { 62 generateRandomString(16, function (err, randomString) {
43 const fieldname = err ? undefined : randomString 63 const fieldname = err ? undefined : randomString
44 cb(null, fieldname + '.' + extension) 64 cb(null, fieldname + '.' + extension)
45 }) 65 })
@@ -48,70 +68,72 @@ const storage = multer.diskStorage({
48 68
49const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }]) 69const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
50 70
51router.use('/', abuseController) 71videosRouter.use('/', abuseVideoRouter)
52router.use('/', blacklistController) 72videosRouter.use('/', blacklistRouter)
53router.use('/', rateController) 73videosRouter.use('/', rateVideoRouter)
54 74
55router.get('/categories', listVideoCategories) 75videosRouter.get('/categories', listVideoCategories)
56router.get('/licences', listVideoLicences) 76videosRouter.get('/licences', listVideoLicences)
57router.get('/languages', listVideoLanguages) 77videosRouter.get('/languages', listVideoLanguages)
58 78
59router.get('/', 79videosRouter.get('/',
60 validatorsPagination.pagination, 80 paginationValidator,
61 validatorsSort.videosSort, 81 videosSortValidator,
62 sort.setVideosSort, 82 setVideosSort,
63 pagination.setPagination, 83 setPagination,
64 listVideos 84 listVideos
65) 85)
66router.put('/:id', 86videosRouter.put('/:id',
67 oAuth.authenticate, 87 authenticate,
68 reqFiles, 88 reqFiles,
69 validatorsVideos.videosUpdate, 89 videosUpdateValidator,
70 updateVideoRetryWrapper 90 updateVideoRetryWrapper
71) 91)
72router.post('/', 92videosRouter.post('/',
73 oAuth.authenticate, 93 authenticate,
74 reqFiles, 94 reqFiles,
75 validatorsVideos.videosAdd, 95 videosAddValidator,
76 addVideoRetryWrapper 96 addVideoRetryWrapper
77) 97)
78router.get('/:id', 98videosRouter.get('/:id',
79 validatorsVideos.videosGet, 99 videosGetValidator,
80 getVideo 100 getVideo
81) 101)
82 102
83router.delete('/:id', 103videosRouter.delete('/:id',
84 oAuth.authenticate, 104 authenticate,
85 validatorsVideos.videosRemove, 105 videosRemoveValidator,
86 removeVideo 106 removeVideo
87) 107)
88 108
89router.get('/search/:value', 109videosRouter.get('/search/:value',
90 validatorsVideos.videosSearch, 110 videosSearchValidator,
91 validatorsPagination.pagination, 111 paginationValidator,
92 validatorsSort.videosSort, 112 videosSortValidator,
93 sort.setVideosSort, 113 setVideosSort,
94 pagination.setPagination, 114 setPagination,
95 search.setVideosSearch, 115 setVideosSearch,
96 searchVideos 116 searchVideos
97) 117)
98 118
99// --------------------------------------------------------------------------- 119// ---------------------------------------------------------------------------
100 120
101module.exports = router 121export {
122 videosRouter
123}
102 124
103// --------------------------------------------------------------------------- 125// ---------------------------------------------------------------------------
104 126
105function listVideoCategories (req, res, next) { 127function listVideoCategories (req, res, next) {
106 res.json(constants.VIDEO_CATEGORIES) 128 res.json(VIDEO_CATEGORIES)
107} 129}
108 130
109function listVideoLicences (req, res, next) { 131function listVideoLicences (req, res, next) {
110 res.json(constants.VIDEO_LICENCES) 132 res.json(VIDEO_LICENCES)
111} 133}
112 134
113function listVideoLanguages (req, res, next) { 135function listVideoLanguages (req, res, next) {
114 res.json(constants.VIDEO_LANGUAGES) 136 res.json(VIDEO_LANGUAGES)
115} 137}
116 138
117// Wrapper to video add that retry the function if there is a database error 139// Wrapper to video add that retry the function if there is a database error
@@ -122,7 +144,7 @@ function addVideoRetryWrapper (req, res, next) {
122 errorMessage: 'Cannot insert the video with many retries.' 144 errorMessage: 'Cannot insert the video with many retries.'
123 } 145 }
124 146
125 databaseUtils.retryTransactionWrapper(addVideo, options, function (err) { 147 retryTransactionWrapper(addVideo, options, function (err) {
126 if (err) return next(err) 148 if (err) return next(err)
127 149
128 // TODO : include Location of the new video -> 201 150 // TODO : include Location of the new video -> 201
@@ -135,7 +157,7 @@ function addVideo (req, res, videoFile, finalCallback) {
135 157
136 waterfall([ 158 waterfall([
137 159
138 databaseUtils.startSerializableTransaction, 160 startSerializableTransaction,
139 161
140 function findOrCreateAuthor (t, callback) { 162 function findOrCreateAuthor (t, callback) {
141 const user = res.locals.oauth.token.User 163 const user = res.locals.oauth.token.User
@@ -179,7 +201,7 @@ function addVideo (req, res, videoFile, finalCallback) {
179 201
180 // Set the videoname the same as the id 202 // Set the videoname the same as the id
181 function renameVideoFile (t, author, tagInstances, video, callback) { 203 function renameVideoFile (t, author, tagInstances, video, callback) {
182 const videoDir = constants.CONFIG.STORAGE.VIDEOS_DIR 204 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
183 const source = path.join(videoDir, videoFile.filename) 205 const source = path.join(videoDir, videoFile.filename)
184 const destination = path.join(videoDir, video.getVideoFilename()) 206 const destination = path.join(videoDir, video.getVideoFilename())
185 207
@@ -218,25 +240,25 @@ function addVideo (req, res, videoFile, finalCallback) {
218 240
219 function sendToFriends (t, video, callback) { 241 function sendToFriends (t, video, callback) {
220 // Let transcoding job send the video to friends because the videofile extension might change 242 // Let transcoding job send the video to friends because the videofile extension might change
221 if (constants.CONFIG.TRANSCODING.ENABLED === true) return callback(null, t) 243 if (CONFIG.TRANSCODING.ENABLED === true) return callback(null, t)
222 244
223 video.toAddRemoteJSON(function (err, remoteVideo) { 245 video.toAddRemoteJSON(function (err, remoteVideo) {
224 if (err) return callback(err) 246 if (err) return callback(err)
225 247
226 // Now we'll add the video's meta data to our friends 248 // Now we'll add the video's meta data to our friends
227 friends.addVideoToFriends(remoteVideo, t, function (err) { 249 addVideoToFriends(remoteVideo, t, function (err) {
228 return callback(err, t) 250 return callback(err, t)
229 }) 251 })
230 }) 252 })
231 }, 253 },
232 254
233 databaseUtils.commitTransaction 255 commitTransaction
234 256
235 ], function andFinally (err, t) { 257 ], function andFinally (err, t) {
236 if (err) { 258 if (err) {
237 // This is just a debug because we will retry the insert 259 // This is just a debug because we will retry the insert
238 logger.debug('Cannot insert the video.', { error: err }) 260 logger.debug('Cannot insert the video.', { error: err })
239 return databaseUtils.rollbackTransaction(err, t, finalCallback) 261 return rollbackTransaction(err, t, finalCallback)
240 } 262 }
241 263
242 logger.info('Video with name %s created.', videoInfos.name) 264 logger.info('Video with name %s created.', videoInfos.name)
@@ -250,7 +272,7 @@ function updateVideoRetryWrapper (req, res, next) {
250 errorMessage: 'Cannot update the video with many retries.' 272 errorMessage: 'Cannot update the video with many retries.'
251 } 273 }
252 274
253 databaseUtils.retryTransactionWrapper(updateVideo, options, function (err) { 275 retryTransactionWrapper(updateVideo, options, function (err) {
254 if (err) return next(err) 276 if (err) return next(err)
255 277
256 // TODO : include Location of the new video -> 201 278 // TODO : include Location of the new video -> 201
@@ -265,7 +287,7 @@ function updateVideo (req, res, finalCallback) {
265 287
266 waterfall([ 288 waterfall([
267 289
268 databaseUtils.startSerializableTransaction, 290 startSerializableTransaction,
269 291
270 function findOrCreateTags (t, callback) { 292 function findOrCreateTags (t, callback) {
271 if (videoInfosToUpdate.tags) { 293 if (videoInfosToUpdate.tags) {
@@ -312,12 +334,12 @@ function updateVideo (req, res, finalCallback) {
312 const json = videoInstance.toUpdateRemoteJSON() 334 const json = videoInstance.toUpdateRemoteJSON()
313 335
314 // Now we'll update the video's meta data to our friends 336 // Now we'll update the video's meta data to our friends
315 friends.updateVideoToFriends(json, t, function (err) { 337 updateVideoToFriends(json, t, function (err) {
316 return callback(err, t) 338 return callback(err, t)
317 }) 339 })
318 }, 340 },
319 341
320 databaseUtils.commitTransaction 342 commitTransaction
321 343
322 ], function andFinally (err, t) { 344 ], function andFinally (err, t) {
323 if (err) { 345 if (err) {
@@ -331,7 +353,7 @@ function updateVideo (req, res, finalCallback) {
331 videoInstance.set(key, value) 353 videoInstance.set(key, value)
332 }) 354 })
333 355
334 return databaseUtils.rollbackTransaction(err, t, finalCallback) 356 return rollbackTransaction(err, t, finalCallback)
335 } 357 }
336 358
337 logger.info('Video with name %s updated.', videoInfosToUpdate.name) 359 logger.info('Video with name %s updated.', videoInfosToUpdate.name)
@@ -354,17 +376,17 @@ function getVideo (req, res, next) {
354 // For example, only add a view when a user watch a video during 30s etc 376 // For example, only add a view when a user watch a video during 30s etc
355 const qaduParams = { 377 const qaduParams = {
356 videoId: videoInstance.id, 378 videoId: videoInstance.id,
357 type: constants.REQUEST_VIDEO_QADU_TYPES.VIEWS 379 type: REQUEST_VIDEO_QADU_TYPES.VIEWS
358 } 380 }
359 friends.quickAndDirtyUpdateVideoToFriends(qaduParams) 381 quickAndDirtyUpdateVideoToFriends(qaduParams)
360 }) 382 })
361 } else { 383 } else {
362 // Just send the event to our friends 384 // Just send the event to our friends
363 const eventParams = { 385 const eventParams = {
364 videoId: videoInstance.id, 386 videoId: videoInstance.id,
365 type: constants.REQUEST_VIDEO_EVENT_TYPES.VIEWS 387 type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
366 } 388 }
367 friends.addEventToRemoteVideo(eventParams) 389 addEventToRemoteVideo(eventParams)
368 } 390 }
369 391
370 // Do not wait the view system 392 // Do not wait the view system
@@ -375,7 +397,7 @@ function listVideos (req, res, next) {
375 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) { 397 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
376 if (err) return next(err) 398 if (err) return next(err)
377 399
378 res.json(utils.getFormatedObjects(videosList, videosTotal)) 400 res.json(getFormatedObjects(videosList, videosTotal))
379 }) 401 })
380} 402}
381 403
@@ -398,7 +420,7 @@ function searchVideos (req, res, next) {
398 function (err, videosList, videosTotal) { 420 function (err, videosList, videosTotal) {
399 if (err) return next(err) 421 if (err) return next(err)
400 422
401 res.json(utils.getFormatedObjects(videosList, videosTotal)) 423 res.json(getFormatedObjects(videosList, videosTotal))
402 } 424 }
403 ) 425 )
404} 426}
diff --git a/server/controllers/api/videos/rate.js b/server/controllers/api/videos/rate.ts
index df8a69a1d..21053792a 100644
--- a/server/controllers/api/videos/rate.js
+++ b/server/controllers/api/videos/rate.ts
@@ -1,29 +1,41 @@
1'use strict' 1import express = require('express')
2import { waterfall } from 'async'
2 3
3const express = require('express')
4const waterfall = require('async/waterfall')
5
6const constants = require('../../../initializers/constants')
7const db = require('../../../initializers/database') 4const db = require('../../../initializers/database')
8const logger = require('../../../helpers/logger') 5import {
9const friends = require('../../../lib/friends') 6 logger,
10const middlewares = require('../../../middlewares') 7 retryTransactionWrapper,
11const oAuth = middlewares.oauth 8 startSerializableTransaction,
12const validators = middlewares.validators 9 commitTransaction,
13const validatorsVideos = validators.videos 10 rollbackTransaction
14const databaseUtils = require('../../../helpers/database-utils') 11} from '../../../helpers'
15 12import {
16const router = express.Router() 13 VIDEO_RATE_TYPES,
17 14 REQUEST_VIDEO_EVENT_TYPES,
18router.put('/:id/rate', 15 REQUEST_VIDEO_QADU_TYPES
19 oAuth.authenticate, 16} from '../../../initializers'
20 validatorsVideos.videoRate, 17import {
18 addEventsToRemoteVideo,
19 quickAndDirtyUpdatesVideoToFriends
20} from '../../../lib'
21import {
22 authenticate,
23 videoRateValidator
24} from '../../../middlewares'
25
26const rateVideoRouter = express.Router()
27
28rateVideoRouter.put('/:id/rate',
29 authenticate,
30 videoRateValidator,
21 rateVideoRetryWrapper 31 rateVideoRetryWrapper
22) 32)
23 33
24// --------------------------------------------------------------------------- 34// ---------------------------------------------------------------------------
25 35
26module.exports = router 36export {
37 rateVideoRouter
38}
27 39
28// --------------------------------------------------------------------------- 40// ---------------------------------------------------------------------------
29 41
@@ -33,7 +45,7 @@ function rateVideoRetryWrapper (req, res, next) {
33 errorMessage: 'Cannot update the user video rate.' 45 errorMessage: 'Cannot update the user video rate.'
34 } 46 }
35 47
36 databaseUtils.retryTransactionWrapper(rateVideo, options, function (err) { 48 retryTransactionWrapper(rateVideo, options, function (err) {
37 if (err) return next(err) 49 if (err) return next(err)
38 50
39 return res.type('json').status(204).end() 51 return res.type('json').status(204).end()
@@ -46,7 +58,7 @@ function rateVideo (req, res, finalCallback) {
46 const userInstance = res.locals.oauth.token.User 58 const userInstance = res.locals.oauth.token.User
47 59
48 waterfall([ 60 waterfall([
49 databaseUtils.startSerializableTransaction, 61 startSerializableTransaction,
50 62
51 function findPreviousRate (t, callback) { 63 function findPreviousRate (t, callback) {
52 db.UserVideoRate.load(userInstance.id, videoInstance.id, t, function (err, previousRate) { 64 db.UserVideoRate.load(userInstance.id, videoInstance.id, t, function (err, previousRate) {
@@ -60,14 +72,14 @@ function rateVideo (req, res, finalCallback) {
60 let likesToIncrement = 0 72 let likesToIncrement = 0
61 let dislikesToIncrement = 0 73 let dislikesToIncrement = 0
62 74
63 if (rateType === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement++ 75 if (rateType === VIDEO_RATE_TYPES.LIKE) likesToIncrement++
64 else if (rateType === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement++ 76 else if (rateType === VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement++
65 77
66 // There was a previous rate, update it 78 // There was a previous rate, update it
67 if (previousRate) { 79 if (previousRate) {
68 // We will remove the previous rate, so we will need to remove it from the video attribute 80 // We will remove the previous rate, so we will need to remove it from the video attribute
69 if (previousRate.type === constants.VIDEO_RATE_TYPES.LIKE) likesToIncrement-- 81 if (previousRate.type === VIDEO_RATE_TYPES.LIKE) likesToIncrement--
70 else if (previousRate.type === constants.VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement-- 82 else if (previousRate.type === VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement--
71 83
72 previousRate.type = rateType 84 previousRate.type = rateType
73 85
@@ -110,7 +122,7 @@ function rateVideo (req, res, finalCallback) {
110 if (likesToIncrement !== 0) { 122 if (likesToIncrement !== 0) {
111 eventsParams.push({ 123 eventsParams.push({
112 videoId: videoInstance.id, 124 videoId: videoInstance.id,
113 type: constants.REQUEST_VIDEO_EVENT_TYPES.LIKES, 125 type: REQUEST_VIDEO_EVENT_TYPES.LIKES,
114 count: likesToIncrement 126 count: likesToIncrement
115 }) 127 })
116 } 128 }
@@ -118,12 +130,12 @@ function rateVideo (req, res, finalCallback) {
118 if (dislikesToIncrement !== 0) { 130 if (dislikesToIncrement !== 0) {
119 eventsParams.push({ 131 eventsParams.push({
120 videoId: videoInstance.id, 132 videoId: videoInstance.id,
121 type: constants.REQUEST_VIDEO_EVENT_TYPES.DISLIKES, 133 type: REQUEST_VIDEO_EVENT_TYPES.DISLIKES,
122 count: dislikesToIncrement 134 count: dislikesToIncrement
123 }) 135 })
124 } 136 }
125 137
126 friends.addEventsToRemoteVideo(eventsParams, t, function (err) { 138 addEventsToRemoteVideo(eventsParams, t, function (err) {
127 return callback(err, t, likesToIncrement, dislikesToIncrement) 139 return callback(err, t, likesToIncrement, dislikesToIncrement)
128 }) 140 })
129 }, 141 },
@@ -138,29 +150,29 @@ function rateVideo (req, res, finalCallback) {
138 if (likesToIncrement !== 0) { 150 if (likesToIncrement !== 0) {
139 qadusParams.push({ 151 qadusParams.push({
140 videoId: videoInstance.id, 152 videoId: videoInstance.id,
141 type: constants.REQUEST_VIDEO_QADU_TYPES.LIKES 153 type: REQUEST_VIDEO_QADU_TYPES.LIKES
142 }) 154 })
143 } 155 }
144 156
145 if (dislikesToIncrement !== 0) { 157 if (dislikesToIncrement !== 0) {
146 qadusParams.push({ 158 qadusParams.push({
147 videoId: videoInstance.id, 159 videoId: videoInstance.id,
148 type: constants.REQUEST_VIDEO_QADU_TYPES.DISLIKES 160 type: REQUEST_VIDEO_QADU_TYPES.DISLIKES
149 }) 161 })
150 } 162 }
151 163
152 friends.quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) { 164 quickAndDirtyUpdatesVideoToFriends(qadusParams, t, function (err) {
153 return callback(err, t) 165 return callback(err, t)
154 }) 166 })
155 }, 167 },
156 168
157 databaseUtils.commitTransaction 169 commitTransaction
158 170
159 ], function (err, t) { 171 ], function (err, t) {
160 if (err) { 172 if (err) {
161 // This is just a debug because we will retry the insert 173 // This is just a debug because we will retry the insert
162 logger.debug('Cannot add the user video rate.', { error: err }) 174 logger.debug('Cannot add the user video rate.', { error: err })
163 return databaseUtils.rollbackTransaction(err, t, finalCallback) 175 return rollbackTransaction(err, t, finalCallback)
164 } 176 }
165 177
166 logger.info('User video rate for video %s of user %s updated.', videoInstance.name, userInstance.username) 178 logger.info('User video rate for video %s of user %s updated.', videoInstance.name, userInstance.username)