aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers
diff options
context:
space:
mode:
authorChocobozzz <florian.bigard@gmail.com>2017-05-15 22:22:03 +0200
committerChocobozzz <florian.bigard@gmail.com>2017-05-20 09:57:40 +0200
commit65fcc3119c334b75dd13bcfdebf186afdc580a8f (patch)
tree4f2158c61a9b7c3f47cfa233d01413b946ee53c0 /server/helpers
parentd5f345ed4cfac4e1fa84dcb4fce1cda4d32f9c73 (diff)
downloadPeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.tar.gz
PeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.tar.zst
PeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.zip
First typescript iteration
Diffstat (limited to 'server/helpers')
-rw-r--r--server/helpers/custom-validators/index.js19
-rw-r--r--server/helpers/custom-validators/index.ts6
-rw-r--r--server/helpers/custom-validators/misc.ts (renamed from server/helpers/custom-validators/misc.js)12
-rw-r--r--server/helpers/custom-validators/pods.ts (renamed from server/helpers/custom-validators/pods.js)20
-rw-r--r--server/helpers/custom-validators/remote/index.js11
-rw-r--r--server/helpers/custom-validators/remote/index.ts1
-rw-r--r--server/helpers/custom-validators/remote/videos.js118
-rw-r--r--server/helpers/custom-validators/remote/videos.ts138
-rw-r--r--server/helpers/custom-validators/users.ts (renamed from server/helpers/custom-validators/users.js)28
-rw-r--r--server/helpers/custom-validators/videos.ts (renamed from server/helpers/custom-validators/videos.js)95
-rw-r--r--server/helpers/database-utils.ts (renamed from server/helpers/database-utils.js)25
-rw-r--r--server/helpers/index.ts6
-rw-r--r--server/helpers/logger.ts (renamed from server/helpers/logger.js)31
-rw-r--r--server/helpers/peertube-crypto.ts (renamed from server/helpers/peertube-crypto.js)67
-rw-r--r--server/helpers/requests.ts (renamed from server/helpers/requests.js)41
-rw-r--r--server/helpers/utils.ts (renamed from server/helpers/utils.js)26
16 files changed, 318 insertions, 326 deletions
diff --git a/server/helpers/custom-validators/index.js b/server/helpers/custom-validators/index.js
deleted file mode 100644
index 9383e0304..000000000
--- a/server/helpers/custom-validators/index.js
+++ /dev/null
@@ -1,19 +0,0 @@
1'use strict'
2
3const miscValidators = require('./misc')
4const podsValidators = require('./pods')
5const remoteValidators = require('./remote')
6const usersValidators = require('./users')
7const videosValidators = require('./videos')
8
9const validators = {
10 misc: miscValidators,
11 pods: podsValidators,
12 remote: remoteValidators,
13 users: usersValidators,
14 videos: videosValidators
15}
16
17// ---------------------------------------------------------------------------
18
19module.exports = validators
diff --git a/server/helpers/custom-validators/index.ts b/server/helpers/custom-validators/index.ts
new file mode 100644
index 000000000..1dcab624a
--- /dev/null
+++ b/server/helpers/custom-validators/index.ts
@@ -0,0 +1,6 @@
1export * from './remote'
2export * from './misc'
3export * from './pods'
4export * from './pods'
5export * from './users'
6export * from './videos'
diff --git a/server/helpers/custom-validators/misc.js b/server/helpers/custom-validators/misc.ts
index 052726241..83f50a7fe 100644
--- a/server/helpers/custom-validators/misc.js
+++ b/server/helpers/custom-validators/misc.ts
@@ -1,10 +1,3 @@
1'use strict'
2
3const miscValidators = {
4 exists,
5 isArray
6}
7
8function exists (value) { 1function exists (value) {
9 return value !== undefined && value !== null 2 return value !== undefined && value !== null
10} 3}
@@ -15,4 +8,7 @@ function isArray (value) {
15 8
16// --------------------------------------------------------------------------- 9// ---------------------------------------------------------------------------
17 10
18module.exports = miscValidators 11export {
12 exists,
13 isArray
14}
diff --git a/server/helpers/custom-validators/pods.js b/server/helpers/custom-validators/pods.ts
index 8bb3733ff..e4c827feb 100644
--- a/server/helpers/custom-validators/pods.js
+++ b/server/helpers/custom-validators/pods.ts
@@ -1,20 +1,15 @@
1'use strict' 1import expressValidator = require('express-validator')
2// TODO: use .validator when express-validator typing will have validator field
3const validator = expressValidator['validator']
2 4
3const validator = require('express-validator').validator 5import { isArray } from './misc'
4
5const miscValidators = require('./misc')
6
7const podsValidators = {
8 isEachUniqueHostValid,
9 isHostValid
10}
11 6
12function isHostValid (host) { 7function isHostValid (host) {
13 return validator.isURL(host) && host.split('://').length === 1 8 return validator.isURL(host) && host.split('://').length === 1
14} 9}
15 10
16function isEachUniqueHostValid (hosts) { 11function isEachUniqueHostValid (hosts) {
17 return miscValidators.isArray(hosts) && 12 return isArray(hosts) &&
18 hosts.length !== 0 && 13 hosts.length !== 0 &&
19 hosts.every(function (host) { 14 hosts.every(function (host) {
20 return isHostValid(host) && hosts.indexOf(host) === hosts.lastIndexOf(host) 15 return isHostValid(host) && hosts.indexOf(host) === hosts.lastIndexOf(host)
@@ -23,4 +18,7 @@ function isEachUniqueHostValid (hosts) {
23 18
24// --------------------------------------------------------------------------- 19// ---------------------------------------------------------------------------
25 20
26module.exports = podsValidators 21export {
22 isEachUniqueHostValid,
23 isHostValid
24}
diff --git a/server/helpers/custom-validators/remote/index.js b/server/helpers/custom-validators/remote/index.js
deleted file mode 100644
index 1939a95f4..000000000
--- a/server/helpers/custom-validators/remote/index.js
+++ /dev/null
@@ -1,11 +0,0 @@
1'use strict'
2
3const remoteVideosValidators = require('./videos')
4
5const validators = {
6 videos: remoteVideosValidators
7}
8
9// ---------------------------------------------------------------------------
10
11module.exports = validators
diff --git a/server/helpers/custom-validators/remote/index.ts b/server/helpers/custom-validators/remote/index.ts
new file mode 100644
index 000000000..d6f9a7e77
--- /dev/null
+++ b/server/helpers/custom-validators/remote/index.ts
@@ -0,0 +1 @@
export * from './videos';
diff --git a/server/helpers/custom-validators/remote/videos.js b/server/helpers/custom-validators/remote/videos.js
deleted file mode 100644
index 24715b4b3..000000000
--- a/server/helpers/custom-validators/remote/videos.js
+++ /dev/null
@@ -1,118 +0,0 @@
1'use strict'
2
3const has = require('lodash/has')
4const values = require('lodash/values')
5
6const constants = require('../../../initializers/constants')
7const videosValidators = require('../videos')
8const miscValidators = require('../misc')
9
10const ENDPOINT_ACTIONS = constants.REQUEST_ENDPOINT_ACTIONS[constants.REQUEST_ENDPOINTS.VIDEOS]
11
12const remoteVideosValidators = {
13 isEachRemoteRequestVideosValid,
14 isEachRemoteRequestVideosQaduValid,
15 isEachRemoteRequestVideosEventsValid
16}
17
18function isEachRemoteRequestVideosValid (requests) {
19 return miscValidators.isArray(requests) &&
20 requests.every(function (request) {
21 const video = request.data
22
23 if (!video) return false
24
25 return (
26 isRequestTypeAddValid(request.type) &&
27 isCommonVideoAttributesValid(video) &&
28 videosValidators.isVideoAuthorValid(video.author) &&
29 videosValidators.isVideoThumbnailDataValid(video.thumbnailData)
30 ) ||
31 (
32 isRequestTypeUpdateValid(request.type) &&
33 isCommonVideoAttributesValid(video)
34 ) ||
35 (
36 isRequestTypeRemoveValid(request.type) &&
37 videosValidators.isVideoRemoteIdValid(video.remoteId)
38 ) ||
39 (
40 isRequestTypeReportAbuseValid(request.type) &&
41 videosValidators.isVideoRemoteIdValid(request.data.videoRemoteId) &&
42 videosValidators.isVideoAbuseReasonValid(request.data.reportReason) &&
43 videosValidators.isVideoAbuseReporterUsernameValid(request.data.reporterUsername)
44 )
45 })
46}
47
48function isEachRemoteRequestVideosQaduValid (requests) {
49 return miscValidators.isArray(requests) &&
50 requests.every(function (request) {
51 const video = request.data
52
53 if (!video) return false
54
55 return (
56 videosValidators.isVideoRemoteIdValid(video.remoteId) &&
57 (has(video, 'views') === false || videosValidators.isVideoViewsValid) &&
58 (has(video, 'likes') === false || videosValidators.isVideoLikesValid) &&
59 (has(video, 'dislikes') === false || videosValidators.isVideoDislikesValid)
60 )
61 })
62}
63
64function isEachRemoteRequestVideosEventsValid (requests) {
65 return miscValidators.isArray(requests) &&
66 requests.every(function (request) {
67 const eventData = request.data
68
69 if (!eventData) return false
70
71 return (
72 videosValidators.isVideoRemoteIdValid(eventData.remoteId) &&
73 values(constants.REQUEST_VIDEO_EVENT_TYPES).indexOf(eventData.eventType) !== -1 &&
74 videosValidators.isVideoEventCountValid(eventData.count)
75 )
76 })
77}
78
79// ---------------------------------------------------------------------------
80
81module.exports = remoteVideosValidators
82
83// ---------------------------------------------------------------------------
84
85function isCommonVideoAttributesValid (video) {
86 return videosValidators.isVideoDateValid(video.createdAt) &&
87 videosValidators.isVideoDateValid(video.updatedAt) &&
88 videosValidators.isVideoCategoryValid(video.category) &&
89 videosValidators.isVideoLicenceValid(video.licence) &&
90 videosValidators.isVideoLanguageValid(video.language) &&
91 videosValidators.isVideoNSFWValid(video.nsfw) &&
92 videosValidators.isVideoDescriptionValid(video.description) &&
93 videosValidators.isVideoDurationValid(video.duration) &&
94 videosValidators.isVideoInfoHashValid(video.infoHash) &&
95 videosValidators.isVideoNameValid(video.name) &&
96 videosValidators.isVideoTagsValid(video.tags) &&
97 videosValidators.isVideoRemoteIdValid(video.remoteId) &&
98 videosValidators.isVideoExtnameValid(video.extname) &&
99 videosValidators.isVideoViewsValid(video.views) &&
100 videosValidators.isVideoLikesValid(video.likes) &&
101 videosValidators.isVideoDislikesValid(video.dislikes)
102}
103
104function isRequestTypeAddValid (value) {
105 return value === ENDPOINT_ACTIONS.ADD
106}
107
108function isRequestTypeUpdateValid (value) {
109 return value === ENDPOINT_ACTIONS.UPDATE
110}
111
112function isRequestTypeRemoveValid (value) {
113 return value === ENDPOINT_ACTIONS.REMOVE
114}
115
116function isRequestTypeReportAbuseValid (value) {
117 return value === ENDPOINT_ACTIONS.REPORT_ABUSE
118}
diff --git a/server/helpers/custom-validators/remote/videos.ts b/server/helpers/custom-validators/remote/videos.ts
new file mode 100644
index 000000000..4b904d011
--- /dev/null
+++ b/server/helpers/custom-validators/remote/videos.ts
@@ -0,0 +1,138 @@
1import { has, values } from 'lodash'
2
3import {
4 REQUEST_ENDPOINTS,
5 REQUEST_ENDPOINT_ACTIONS,
6 REQUEST_VIDEO_EVENT_TYPES
7} from '../../../initializers'
8import { isArray } from '../misc'
9import {
10 isVideoAuthorValid,
11 isVideoThumbnailDataValid,
12 isVideoRemoteIdValid,
13 isVideoAbuseReasonValid,
14 isVideoAbuseReporterUsernameValid,
15 isVideoViewsValid,
16 isVideoLikesValid,
17 isVideoDislikesValid,
18 isVideoEventCountValid,
19 isVideoDateValid,
20 isVideoCategoryValid,
21 isVideoLicenceValid,
22 isVideoLanguageValid,
23 isVideoNSFWValid,
24 isVideoDescriptionValid,
25 isVideoDurationValid,
26 isVideoInfoHashValid,
27 isVideoNameValid,
28 isVideoTagsValid,
29 isVideoExtnameValid
30} from '../videos'
31
32const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
33
34function isEachRemoteRequestVideosValid (requests) {
35 return isArray(requests) &&
36 requests.every(function (request) {
37 const video = request.data
38
39 if (!video) return false
40
41 return (
42 isRequestTypeAddValid(request.type) &&
43 isCommonVideoAttributesValid(video) &&
44 isVideoAuthorValid(video.author) &&
45 isVideoThumbnailDataValid(video.thumbnailData)
46 ) ||
47 (
48 isRequestTypeUpdateValid(request.type) &&
49 isCommonVideoAttributesValid(video)
50 ) ||
51 (
52 isRequestTypeRemoveValid(request.type) &&
53 isVideoRemoteIdValid(video.remoteId)
54 ) ||
55 (
56 isRequestTypeReportAbuseValid(request.type) &&
57 isVideoRemoteIdValid(request.data.videoRemoteId) &&
58 isVideoAbuseReasonValid(request.data.reportReason) &&
59 isVideoAbuseReporterUsernameValid(request.data.reporterUsername)
60 )
61 })
62}
63
64function isEachRemoteRequestVideosQaduValid (requests) {
65 return isArray(requests) &&
66 requests.every(function (request) {
67 const video = request.data
68
69 if (!video) return false
70
71 return (
72 isVideoRemoteIdValid(video.remoteId) &&
73 (has(video, 'views') === false || isVideoViewsValid) &&
74 (has(video, 'likes') === false || isVideoLikesValid) &&
75 (has(video, 'dislikes') === false || isVideoDislikesValid)
76 )
77 })
78}
79
80function isEachRemoteRequestVideosEventsValid (requests) {
81 return isArray(requests) &&
82 requests.every(function (request) {
83 const eventData = request.data
84
85 if (!eventData) return false
86
87 return (
88 isVideoRemoteIdValid(eventData.remoteId) &&
89 values(REQUEST_VIDEO_EVENT_TYPES).indexOf(eventData.eventType) !== -1 &&
90 isVideoEventCountValid(eventData.count)
91 )
92 })
93}
94
95// ---------------------------------------------------------------------------
96
97export {
98 isEachRemoteRequestVideosValid,
99 isEachRemoteRequestVideosQaduValid,
100 isEachRemoteRequestVideosEventsValid
101}
102
103// ---------------------------------------------------------------------------
104
105function isCommonVideoAttributesValid (video) {
106 return isVideoDateValid(video.createdAt) &&
107 isVideoDateValid(video.updatedAt) &&
108 isVideoCategoryValid(video.category) &&
109 isVideoLicenceValid(video.licence) &&
110 isVideoLanguageValid(video.language) &&
111 isVideoNSFWValid(video.nsfw) &&
112 isVideoDescriptionValid(video.description) &&
113 isVideoDurationValid(video.duration) &&
114 isVideoInfoHashValid(video.infoHash) &&
115 isVideoNameValid(video.name) &&
116 isVideoTagsValid(video.tags) &&
117 isVideoRemoteIdValid(video.remoteId) &&
118 isVideoExtnameValid(video.extname) &&
119 isVideoViewsValid(video.views) &&
120 isVideoLikesValid(video.likes) &&
121 isVideoDislikesValid(video.dislikes)
122}
123
124function isRequestTypeAddValid (value) {
125 return value === ENDPOINT_ACTIONS.ADD
126}
127
128function isRequestTypeUpdateValid (value) {
129 return value === ENDPOINT_ACTIONS.UPDATE
130}
131
132function isRequestTypeRemoveValid (value) {
133 return value === ENDPOINT_ACTIONS.REMOVE
134}
135
136function isRequestTypeReportAbuseValid (value) {
137 return value === ENDPOINT_ACTIONS.REPORT_ABUSE
138}
diff --git a/server/helpers/custom-validators/users.js b/server/helpers/custom-validators/users.ts
index 2fc026e98..8fd2dac4f 100644
--- a/server/helpers/custom-validators/users.js
+++ b/server/helpers/custom-validators/users.ts
@@ -1,24 +1,17 @@
1'use strict' 1import { values } from 'lodash'
2import expressValidator = require('express-validator')
3// TODO: use .validator when express-validator typing will have validator field
4const validator = expressValidator['validator']
2 5
3const validator = require('express-validator').validator 6import { CONSTRAINTS_FIELDS, USER_ROLES } from '../../initializers'
4const values = require('lodash/values') 7const USERS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.USERS
5
6const constants = require('../../initializers/constants')
7const USERS_CONSTRAINTS_FIELDS = constants.CONSTRAINTS_FIELDS.USERS
8
9const usersValidators = {
10 isUserPasswordValid,
11 isUserRoleValid,
12 isUserUsernameValid,
13 isUserDisplayNSFWValid
14}
15 8
16function isUserPasswordValid (value) { 9function isUserPasswordValid (value) {
17 return validator.isLength(value, USERS_CONSTRAINTS_FIELDS.PASSWORD) 10 return validator.isLength(value, USERS_CONSTRAINTS_FIELDS.PASSWORD)
18} 11}
19 12
20function isUserRoleValid (value) { 13function isUserRoleValid (value) {
21 return values(constants.USER_ROLES).indexOf(value) !== -1 14 return values(USER_ROLES).indexOf(value) !== -1
22} 15}
23 16
24function isUserUsernameValid (value) { 17function isUserUsernameValid (value) {
@@ -33,4 +26,9 @@ function isUserDisplayNSFWValid (value) {
33 26
34// --------------------------------------------------------------------------- 27// ---------------------------------------------------------------------------
35 28
36module.exports = usersValidators 29export {
30 isUserPasswordValid,
31 isUserRoleValid,
32 isUserUsernameValid,
33 isUserDisplayNSFWValid
34}
diff --git a/server/helpers/custom-validators/videos.js b/server/helpers/custom-validators/videos.ts
index 196731e04..2b2370be4 100644
--- a/server/helpers/custom-validators/videos.js
+++ b/server/helpers/custom-validators/videos.ts
@@ -1,43 +1,24 @@
1'use strict' 1import { values } from 'lodash'
2 2import expressValidator = require('express-validator')
3const validator = require('express-validator').validator 3// TODO: use .validator when express-validator typing will have validator field
4const values = require('lodash/values') 4const validator = expressValidator['validator']
5 5
6const constants = require('../../initializers/constants') 6import {
7const usersValidators = require('./users') 7 CONSTRAINTS_FIELDS,
8const miscValidators = require('./misc') 8 VIDEO_CATEGORIES,
9const VIDEOS_CONSTRAINTS_FIELDS = constants.CONSTRAINTS_FIELDS.VIDEOS 9 VIDEO_LICENCES,
10const VIDEO_ABUSES_CONSTRAINTS_FIELDS = constants.CONSTRAINTS_FIELDS.VIDEO_ABUSES 10 VIDEO_LANGUAGES,
11const VIDEO_EVENTS_CONSTRAINTS_FIELDS = constants.CONSTRAINTS_FIELDS.VIDEO_EVENTS 11 VIDEO_RATE_TYPES
12 12} from '../../initializers'
13const videosValidators = { 13import { isUserUsernameValid } from './users'
14 isVideoAuthorValid, 14import { isArray } from './misc'
15 isVideoDateValid, 15
16 isVideoCategoryValid, 16const VIDEOS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEOS
17 isVideoLicenceValid, 17const VIDEO_ABUSES_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_ABUSES
18 isVideoLanguageValid, 18const VIDEO_EVENTS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_EVENTS
19 isVideoNSFWValid,
20 isVideoDescriptionValid,
21 isVideoDurationValid,
22 isVideoInfoHashValid,
23 isVideoNameValid,
24 isVideoTagsValid,
25 isVideoThumbnailValid,
26 isVideoThumbnailDataValid,
27 isVideoExtnameValid,
28 isVideoRemoteIdValid,
29 isVideoAbuseReasonValid,
30 isVideoAbuseReporterUsernameValid,
31 isVideoFile,
32 isVideoViewsValid,
33 isVideoLikesValid,
34 isVideoRatingTypeValid,
35 isVideoDislikesValid,
36 isVideoEventCountValid
37}
38 19
39function isVideoAuthorValid (value) { 20function isVideoAuthorValid (value) {
40 return usersValidators.isUserUsernameValid(value) 21 return isUserUsernameValid(value)
41} 22}
42 23
43function isVideoDateValid (value) { 24function isVideoDateValid (value) {
@@ -45,15 +26,15 @@ function isVideoDateValid (value) {
45} 26}
46 27
47function isVideoCategoryValid (value) { 28function isVideoCategoryValid (value) {
48 return constants.VIDEO_CATEGORIES[value] !== undefined 29 return VIDEO_CATEGORIES[value] !== undefined
49} 30}
50 31
51function isVideoLicenceValid (value) { 32function isVideoLicenceValid (value) {
52 return constants.VIDEO_LICENCES[value] !== undefined 33 return VIDEO_LICENCES[value] !== undefined
53} 34}
54 35
55function isVideoLanguageValid (value) { 36function isVideoLanguageValid (value) {
56 return value === null || constants.VIDEO_LANGUAGES[value] !== undefined 37 return value === null || VIDEO_LANGUAGES[value] !== undefined
57} 38}
58 39
59function isVideoNSFWValid (value) { 40function isVideoNSFWValid (value) {
@@ -81,7 +62,7 @@ function isVideoNameValid (value) {
81} 62}
82 63
83function isVideoTagsValid (tags) { 64function isVideoTagsValid (tags) {
84 return miscValidators.isArray(tags) && 65 return isArray(tags) &&
85 validator.isInt(tags.length, VIDEOS_CONSTRAINTS_FIELDS.TAGS) && 66 validator.isInt(tags.length, VIDEOS_CONSTRAINTS_FIELDS.TAGS) &&
86 tags.every(function (tag) { 67 tags.every(function (tag) {
87 return validator.isLength(tag, VIDEOS_CONSTRAINTS_FIELDS.TAG) 68 return validator.isLength(tag, VIDEOS_CONSTRAINTS_FIELDS.TAG)
@@ -105,7 +86,7 @@ function isVideoAbuseReasonValid (value) {
105} 86}
106 87
107function isVideoAbuseReporterUsernameValid (value) { 88function isVideoAbuseReporterUsernameValid (value) {
108 return usersValidators.isUserUsernameValid(value) 89 return isUserUsernameValid(value)
109} 90}
110 91
111function isVideoViewsValid (value) { 92function isVideoViewsValid (value) {
@@ -125,7 +106,7 @@ function isVideoEventCountValid (value) {
125} 106}
126 107
127function isVideoRatingTypeValid (value) { 108function isVideoRatingTypeValid (value) {
128 return values(constants.VIDEO_RATE_TYPES).indexOf(value) !== -1 109 return values(VIDEO_RATE_TYPES).indexOf(value) !== -1
129} 110}
130 111
131function isVideoFile (value, files) { 112function isVideoFile (value, files) {
@@ -145,4 +126,28 @@ function isVideoFile (value, files) {
145 126
146// --------------------------------------------------------------------------- 127// ---------------------------------------------------------------------------
147 128
148module.exports = videosValidators 129export {
130 isVideoAuthorValid,
131 isVideoDateValid,
132 isVideoCategoryValid,
133 isVideoLicenceValid,
134 isVideoLanguageValid,
135 isVideoNSFWValid,
136 isVideoDescriptionValid,
137 isVideoDurationValid,
138 isVideoInfoHashValid,
139 isVideoNameValid,
140 isVideoTagsValid,
141 isVideoThumbnailValid,
142 isVideoThumbnailDataValid,
143 isVideoExtnameValid,
144 isVideoRemoteIdValid,
145 isVideoAbuseReasonValid,
146 isVideoAbuseReporterUsernameValid,
147 isVideoFile,
148 isVideoViewsValid,
149 isVideoLikesValid,
150 isVideoRatingTypeValid,
151 isVideoDislikesValid,
152 isVideoEventCountValid
153}
diff --git a/server/helpers/database-utils.js b/server/helpers/database-utils.ts
index c72d19429..b842ab9ec 100644
--- a/server/helpers/database-utils.js
+++ b/server/helpers/database-utils.ts
@@ -1,17 +1,8 @@
1'use strict' 1// TODO: import from ES6 when retry typing file will include errorFilter function
2 2import retry = require('async/retry')
3const retry = require('async/retry')
4 3
5const db = require('../initializers/database') 4const db = require('../initializers/database')
6const logger = require('./logger') 5import { logger } from './logger'
7
8const utils = {
9 commitTransaction,
10 retryTransactionWrapper,
11 rollbackTransaction,
12 startSerializableTransaction,
13 transactionRetryer
14}
15 6
16function commitTransaction (t, callback) { 7function commitTransaction (t, callback) {
17 return t.commit().asCallback(callback) 8 return t.commit().asCallback(callback)
@@ -33,7 +24,7 @@ function rollbackTransaction (err, t, callback) {
33function retryTransactionWrapper (functionToRetry, options, finalCallback) { 24function retryTransactionWrapper (functionToRetry, options, finalCallback) {
34 const args = options.arguments ? options.arguments : [] 25 const args = options.arguments ? options.arguments : []
35 26
36 utils.transactionRetryer( 27 transactionRetryer(
37 function (callback) { 28 function (callback) {
38 return functionToRetry.apply(this, args.concat([ callback ])) 29 return functionToRetry.apply(this, args.concat([ callback ]))
39 }, 30 },
@@ -69,4 +60,10 @@ function startSerializableTransaction (callback) {
69 60
70// --------------------------------------------------------------------------- 61// ---------------------------------------------------------------------------
71 62
72module.exports = utils 63export {
64 commitTransaction,
65 retryTransactionWrapper,
66 rollbackTransaction,
67 startSerializableTransaction,
68 transactionRetryer
69}
diff --git a/server/helpers/index.ts b/server/helpers/index.ts
new file mode 100644
index 000000000..e56bd21ad
--- /dev/null
+++ b/server/helpers/index.ts
@@ -0,0 +1,6 @@
1export * from './logger'
2export * from './custom-validators'
3export * from './database-utils'
4export * from './peertube-crypto'
5export * from './requests'
6export * from './utils'
diff --git a/server/helpers/logger.js b/server/helpers/logger.ts
index 281acedb8..3c35e41e0 100644
--- a/server/helpers/logger.js
+++ b/server/helpers/logger.ts
@@ -1,23 +1,21 @@
1// Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/ 1// Thanks http://tostring.it/2014/06/23/advanced-logging-with-nodejs/
2'use strict' 2import mkdirp = require('mkdirp')
3import path = require('path')
4import winston = require('winston')
3 5
4const mkdirp = require('mkdirp') 6// Do not use barrel (dependencies issues)
5const path = require('path') 7import { CONFIG } from '../initializers/constants'
6const winston = require('winston')
7winston.emitErrs = true
8 8
9const constants = require('../initializers/constants') 9const label = CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
10
11const label = constants.CONFIG.WEBSERVER.HOSTNAME + ':' + constants.CONFIG.WEBSERVER.PORT
12 10
13// Create the directory if it does not exist 11// Create the directory if it does not exist
14mkdirp.sync(constants.CONFIG.STORAGE.LOG_DIR) 12mkdirp.sync(CONFIG.STORAGE.LOG_DIR)
15 13
16const logger = new winston.Logger({ 14const logger = new winston.Logger({
17 transports: [ 15 transports: [
18 new winston.transports.File({ 16 new winston.transports.File({
19 level: 'debug', 17 level: 'debug',
20 filename: path.join(constants.CONFIG.STORAGE.LOG_DIR, 'all-logs.log'), 18 filename: path.join(CONFIG.STORAGE.LOG_DIR, 'all-logs.log'),
21 handleExceptions: true, 19 handleExceptions: true,
22 json: true, 20 json: true,
23 maxsize: 5242880, 21 maxsize: 5242880,
@@ -38,12 +36,13 @@ const logger = new winston.Logger({
38 exitOnError: true 36 exitOnError: true
39}) 37})
40 38
41logger.stream = { 39// TODO: useful?
42 write: function (message, encoding) { 40// logger.stream = {
43 logger.info(message) 41// write: function (message) {
44 } 42// logger.info(message)
45} 43// }
44// }
46 45
47// --------------------------------------------------------------------------- 46// ---------------------------------------------------------------------------
48 47
49module.exports = logger 48export { logger }
diff --git a/server/helpers/peertube-crypto.js b/server/helpers/peertube-crypto.ts
index 55ae6fab3..a4e9672e6 100644
--- a/server/helpers/peertube-crypto.js
+++ b/server/helpers/peertube-crypto.ts
@@ -1,26 +1,21 @@
1'use strict' 1import crypto = require('crypto')
2 2import bcrypt = require('bcrypt')
3const crypto = require('crypto') 3import fs = require('fs')
4const bcrypt = require('bcrypt') 4import openssl = require('openssl-wrapper')
5const fs = require('fs') 5import { join } from 'path'
6const openssl = require('openssl-wrapper') 6
7const pathUtils = require('path') 7import {
8 8 SIGNATURE_ALGORITHM,
9const constants = require('../initializers/constants') 9 SIGNATURE_ENCODING,
10const logger = require('./logger') 10 PRIVATE_CERT_NAME,
11 11 CONFIG,
12const peertubeCrypto = { 12 BCRYPT_SALT_SIZE,
13 checkSignature, 13 PUBLIC_CERT_NAME
14 comparePassword, 14} from '../initializers'
15 createCertsIfNotExist, 15import { logger } from './logger'
16 cryptPassword,
17 getMyPrivateCert,
18 getMyPublicCert,
19 sign
20}
21 16
22function checkSignature (publicKey, data, hexSignature) { 17function checkSignature (publicKey, data, hexSignature) {
23 const verify = crypto.createVerify(constants.SIGNATURE_ALGORITHM) 18 const verify = crypto.createVerify(SIGNATURE_ALGORITHM)
24 19
25 let dataString 20 let dataString
26 if (typeof data === 'string') { 21 if (typeof data === 'string') {
@@ -36,12 +31,12 @@ function checkSignature (publicKey, data, hexSignature) {
36 31
37 verify.update(dataString, 'utf8') 32 verify.update(dataString, 'utf8')
38 33
39 const isValid = verify.verify(publicKey, hexSignature, constants.SIGNATURE_ENCODING) 34 const isValid = verify.verify(publicKey, hexSignature, SIGNATURE_ENCODING)
40 return isValid 35 return isValid
41} 36}
42 37
43function sign (data) { 38function sign (data) {
44 const sign = crypto.createSign(constants.SIGNATURE_ALGORITHM) 39 const sign = crypto.createSign(SIGNATURE_ALGORITHM)
45 40
46 let dataString 41 let dataString
47 if (typeof data === 'string') { 42 if (typeof data === 'string') {
@@ -58,9 +53,9 @@ function sign (data) {
58 sign.update(dataString, 'utf8') 53 sign.update(dataString, 'utf8')
59 54
60 // TODO: make async 55 // TODO: make async
61 const certPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, constants.PRIVATE_CERT_NAME) 56 const certPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME)
62 const myKey = fs.readFileSync(certPath) 57 const myKey = fs.readFileSync(certPath)
63 const signature = sign.sign(myKey, constants.SIGNATURE_ENCODING) 58 const signature = sign.sign(myKey.toString(), SIGNATURE_ENCODING)
64 59
65 return signature 60 return signature
66} 61}
@@ -88,7 +83,7 @@ function createCertsIfNotExist (callback) {
88} 83}
89 84
90function cryptPassword (password, callback) { 85function cryptPassword (password, callback) {
91 bcrypt.genSalt(constants.BCRYPT_SALT_SIZE, function (err, salt) { 86 bcrypt.genSalt(BCRYPT_SALT_SIZE, function (err, salt) {
92 if (err) return callback(err) 87 if (err) return callback(err)
93 88
94 bcrypt.hash(password, salt, function (err, hash) { 89 bcrypt.hash(password, salt, function (err, hash) {
@@ -98,23 +93,31 @@ function cryptPassword (password, callback) {
98} 93}
99 94
100function getMyPrivateCert (callback) { 95function getMyPrivateCert (callback) {
101 const certPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, constants.PRIVATE_CERT_NAME) 96 const certPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME)
102 fs.readFile(certPath, 'utf8', callback) 97 fs.readFile(certPath, 'utf8', callback)
103} 98}
104 99
105function getMyPublicCert (callback) { 100function getMyPublicCert (callback) {
106 const certPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, constants.PUBLIC_CERT_NAME) 101 const certPath = join(CONFIG.STORAGE.CERT_DIR, PUBLIC_CERT_NAME)
107 fs.readFile(certPath, 'utf8', callback) 102 fs.readFile(certPath, 'utf8', callback)
108} 103}
109 104
110// --------------------------------------------------------------------------- 105// ---------------------------------------------------------------------------
111 106
112module.exports = peertubeCrypto 107export {
108 checkSignature,
109 comparePassword,
110 createCertsIfNotExist,
111 cryptPassword,
112 getMyPrivateCert,
113 getMyPublicCert,
114 sign
115}
113 116
114// --------------------------------------------------------------------------- 117// ---------------------------------------------------------------------------
115 118
116function certsExist (callback) { 119function certsExist (callback) {
117 const certPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, constants.PRIVATE_CERT_NAME) 120 const certPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME)
118 fs.access(certPath, function (err) { 121 fs.access(certPath, function (err) {
119 // If there is an error the certificates do not exist 122 // If there is an error the certificates do not exist
120 const exists = !err 123 const exists = !err
@@ -134,7 +137,7 @@ function createCerts (callback) {
134 137
135 logger.info('Generating a RSA key...') 138 logger.info('Generating a RSA key...')
136 139
137 const privateCertPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, constants.PRIVATE_CERT_NAME) 140 const privateCertPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME)
138 const genRsaOptions = { 141 const genRsaOptions = {
139 'out': privateCertPath, 142 'out': privateCertPath,
140 '2048': false 143 '2048': false
@@ -148,7 +151,7 @@ function createCerts (callback) {
148 logger.info('RSA key generated.') 151 logger.info('RSA key generated.')
149 logger.info('Managing public key...') 152 logger.info('Managing public key...')
150 153
151 const publicCertPath = pathUtils.join(constants.CONFIG.STORAGE.CERT_DIR, 'peertube.pub') 154 const publicCertPath = join(CONFIG.STORAGE.CERT_DIR, 'peertube.pub')
152 const rsaOptions = { 155 const rsaOptions = {
153 'in': privateCertPath, 156 'in': privateCertPath,
154 'pubout': true, 157 'pubout': true,
diff --git a/server/helpers/requests.js b/server/helpers/requests.ts
index efe056937..8ded52972 100644
--- a/server/helpers/requests.js
+++ b/server/helpers/requests.ts
@@ -1,21 +1,18 @@
1'use strict' 1import replay = require('request-replay')
2import request = require('request')
2 3
3const replay = require('request-replay') 4import {
4const request = require('request') 5 RETRY_REQUESTS,
5 6 REMOTE_SCHEME,
6const constants = require('../initializers/constants') 7 CONFIG
7const peertubeCrypto = require('./peertube-crypto') 8} from '../initializers'
8 9import { sign } from './peertube-crypto'
9const requests = {
10 makeRetryRequest,
11 makeSecureRequest
12}
13 10
14function makeRetryRequest (params, callback) { 11function makeRetryRequest (params, callback) {
15 replay( 12 replay(
16 request(params, callback), 13 request(params, callback),
17 { 14 {
18 retries: constants.RETRY_REQUESTS, 15 retries: RETRY_REQUESTS,
19 factor: 3, 16 factor: 3,
20 maxTimeout: Infinity, 17 maxTimeout: Infinity,
21 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ] 18 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
@@ -25,18 +22,17 @@ function makeRetryRequest (params, callback) {
25 22
26function makeSecureRequest (params, callback) { 23function makeSecureRequest (params, callback) {
27 const requestParams = { 24 const requestParams = {
28 url: constants.REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path 25 url: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path,
26 json: {}
29 } 27 }
30 28
31 if (params.method !== 'POST') { 29 if (params.method !== 'POST') {
32 return callback(new Error('Cannot make a secure request with a non POST method.')) 30 return callback(new Error('Cannot make a secure request with a non POST method.'))
33 } 31 }
34 32
35 requestParams.json = {}
36
37 // Add signature if it is specified in the params 33 // Add signature if it is specified in the params
38 if (params.sign === true) { 34 if (params.sign === true) {
39 const host = constants.CONFIG.WEBSERVER.HOST 35 const host = CONFIG.WEBSERVER.HOST
40 36
41 let dataToSign 37 let dataToSign
42 if (params.data) { 38 if (params.data) {
@@ -47,22 +43,23 @@ function makeSecureRequest (params, callback) {
47 dataToSign = host 43 dataToSign = host
48 } 44 }
49 45
50 requestParams.json.signature = { 46 requestParams.json['signature'] = {
51 host, // Which host we pretend to be 47 host, // Which host we pretend to be
52 signature: peertubeCrypto.sign(dataToSign) 48 signature: sign(dataToSign)
53 } 49 }
54 } 50 }
55 51
56 // If there are data informations 52 // If there are data informations
57 if (params.data) { 53 if (params.data) {
58 requestParams.json.data = params.data 54 requestParams.json['data'] = params.data
59 } 55 }
60 56
61 console.log(requestParams.json.data)
62
63 request.post(requestParams, callback) 57 request.post(requestParams, callback)
64} 58}
65 59
66// --------------------------------------------------------------------------- 60// ---------------------------------------------------------------------------
67 61
68module.exports = requests 62export {
63 makeRetryRequest,
64 makeSecureRequest
65}
diff --git a/server/helpers/utils.js b/server/helpers/utils.ts
index 6d40e8f3f..09c35a533 100644
--- a/server/helpers/utils.js
+++ b/server/helpers/utils.ts
@@ -1,24 +1,13 @@
1'use strict' 1import { pseudoRandomBytes } from 'crypto'
2 2
3const crypto = require('crypto') 3import { logger } from './logger'
4
5const logger = require('./logger')
6
7const utils = {
8 badRequest,
9 createEmptyCallback,
10 cleanForExit,
11 generateRandomString,
12 isTestInstance,
13 getFormatedObjects
14}
15 4
16function badRequest (req, res, next) { 5function badRequest (req, res, next) {
17 res.type('json').status(400).end() 6 res.type('json').status(400).end()
18} 7}
19 8
20function generateRandomString (size, callback) { 9function generateRandomString (size, callback) {
21 crypto.pseudoRandomBytes(size, function (err, raw) { 10 pseudoRandomBytes(size, function (err, raw) {
22 if (err) return callback(err) 11 if (err) return callback(err)
23 12
24 callback(null, raw.toString('hex')) 13 callback(null, raw.toString('hex'))
@@ -55,4 +44,11 @@ function getFormatedObjects (objects, objectsTotal) {
55 44
56// --------------------------------------------------------------------------- 45// ---------------------------------------------------------------------------
57 46
58module.exports = utils 47export {
48 badRequest,
49 createEmptyCallback,
50 cleanForExit,
51 generateRandomString,
52 isTestInstance,
53 getFormatedObjects
54}