]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/core-utils.ts
WIP plugins: add ability to register plugins
[github/Chocobozzz/PeerTube.git] / server / helpers / core-utils.ts
CommitLineData
1840c2f7
C
1/*
2 Different from 'utils' because we don't not import other PeerTube modules.
3 Useful to avoid circular dependencies.
4*/
5
6fcd19ba
C
6import * as bcrypt from 'bcrypt'
7import * as createTorrent from 'create-torrent'
729bb184 8import { createHash, HexBase64Latin1Encoding, pseudoRandomBytes } from 'crypto'
0b4204f9 9import { isAbsolute, join } from 'path'
e4f97bab 10import * as pem from 'pem'
225a89c2 11import { URL } from 'url'
c73e83da 12import { truncate } from 'lodash'
499d9015 13import { exec } from 'child_process'
a4101923
C
14
15const objectConverter = (oldObject: any, keyConverter: (e: string) => string, valueConverter: (e: any) => any) => {
16 if (!oldObject || typeof oldObject !== 'object') {
17 return valueConverter(oldObject)
18 }
19
74dc3bca 20 if (Array.isArray(oldObject)) {
a4101923
C
21 return oldObject.map(e => objectConverter(e, keyConverter, valueConverter))
22 }
23
24 const newObject = {}
25 Object.keys(oldObject).forEach(oldKey => {
26 const newKey = keyConverter(oldKey)
27 newObject[ newKey ] = objectConverter(oldObject[ oldKey ], keyConverter, valueConverter)
28 })
29
30 return newObject
31}
225a89c2 32
06215f15
C
33const timeTable = {
34 ms: 1,
35 second: 1000,
36 minute: 60000,
37 hour: 3600000,
38 day: 3600000 * 24,
39 week: 3600000 * 24 * 7,
40 month: 3600000 * 24 * 30
41}
0e5ff97f 42
8f0bc73d 43export function parseDurationToMs (duration: number | string): number {
06215f15
C
44 if (typeof duration === 'number') return duration
45
46 if (typeof duration === 'string') {
47 const split = duration.match(/^([\d\.,]+)\s?(\w+)$/)
48
49 if (split.length === 3) {
50 const len = parseFloat(split[1])
51 let unit = split[2].replace(/s$/i,'').toLowerCase()
52 if (unit === 'm') {
53 unit = 'ms'
54 }
55
56 return (len || 1) * (timeTable[unit] || 0)
57 }
58 }
59
ae9bbed4 60 throw new Error(`Duration ${duration} could not be properly parsed`)
06215f15
C
61}
62
0e5ff97f
BY
63export function parseBytes (value: string | number): number {
64 if (typeof value === 'number') return value
65
66 const tgm = /^(\d+)\s*TB\s*(\d+)\s*GB\s*(\d+)\s*MB$/
67 const tg = /^(\d+)\s*TB\s*(\d+)\s*GB$/
68 const tm = /^(\d+)\s*TB\s*(\d+)\s*MB$/
69 const gm = /^(\d+)\s*GB\s*(\d+)\s*MB$/
70 const t = /^(\d+)\s*TB$/
71 const g = /^(\d+)\s*GB$/
72 const m = /^(\d+)\s*MB$/
73 const b = /^(\d+)\s*B$/
74 let match
75
76 if (value.match(tgm)) {
77 match = value.match(tgm)
78 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
79 + parseInt(match[2], 10) * 1024 * 1024 * 1024
80 + parseInt(match[3], 10) * 1024 * 1024
81 } else if (value.match(tg)) {
82 match = value.match(tg)
83 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
84 + parseInt(match[2], 10) * 1024 * 1024 * 1024
85 } else if (value.match(tm)) {
86 match = value.match(tm)
87 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
88 + parseInt(match[2], 10) * 1024 * 1024
89 } else if (value.match(gm)) {
90 match = value.match(gm)
91 return parseInt(match[1], 10) * 1024 * 1024 * 1024
92 + parseInt(match[2], 10) * 1024 * 1024
93 } else if (value.match(t)) {
94 match = value.match(t)
95 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
96 } else if (value.match(g)) {
97 match = value.match(g)
98 return parseInt(match[1], 10) * 1024 * 1024 * 1024
99 } else if (value.match(m)) {
100 match = value.match(m)
101 return parseInt(match[1], 10) * 1024 * 1024
102 } else if (value.match(b)) {
103 match = value.match(b)
104 return parseInt(match[1], 10) * 1024
105 } else {
106 return parseInt(value, 10)
107 }
108}
109
225a89c2
C
110function sanitizeUrl (url: string) {
111 const urlObject = new URL(url)
112
113 if (urlObject.protocol === 'https:' && urlObject.port === '443') {
114 urlObject.port = ''
115 } else if (urlObject.protocol === 'http:' && urlObject.port === '80') {
116 urlObject.port = ''
117 }
118
119 return urlObject.href.replace(/\/$/, '')
120}
121
122// Don't import remote scheme from constants because we are in core utils
123function sanitizeHost (host: string, remoteScheme: string) {
604abfbe 124 const toRemove = remoteScheme === 'https' ? 443 : 80
225a89c2
C
125
126 return host.replace(new RegExp(`:${toRemove}$`), '')
127}
1840c2f7
C
128
129function isTestInstance () {
130 return process.env.NODE_ENV === 'test'
131}
132
00f9e41e
C
133function isProdInstance () {
134 return process.env.NODE_ENV === 'production'
135}
136
1a12f66d
C
137function getAppNumber () {
138 return process.env.NODE_APP_INSTANCE
139}
140
1840c2f7 141function root () {
fdbda9e3
C
142 // We are in /helpers/utils.js
143 const paths = [ __dirname, '..', '..' ]
144
145 // We are under /dist directory
c1e791ba 146 if (process.mainModule && process.mainModule.filename.endsWith('.ts') === false) {
fdbda9e3
C
147 paths.push('..')
148 }
149
150 return join.apply(null, paths)
1840c2f7
C
151}
152
49347a0a
C
153// Thanks: https://stackoverflow.com/a/12034334
154function escapeHTML (stringParam) {
23e27dd5
C
155 if (!stringParam) return ''
156
49347a0a
C
157 const entityMap = {
158 '&': '&',
159 '<': '&lt;',
160 '>': '&gt;',
161 '"': '&quot;',
cf7a61b5 162 '\'': '&#39;',
49347a0a
C
163 '/': '&#x2F;',
164 '`': '&#x60;',
165 '=': '&#x3D;'
166 }
167
168 return String(stringParam).replace(/[&<>"'`=\/]/g, s => entityMap[s])
169}
170
e4f97bab
C
171function pageToStartAndCount (page: number, itemsPerPage: number) {
172 const start = (page - 1) * itemsPerPage
173
174 return { start, count: itemsPerPage }
175}
176
0b4204f9
C
177function buildPath (path: string) {
178 if (isAbsolute(path)) return path
179
180 return join(root(), path)
181}
182
c73e83da
C
183// Consistent with .length, lodash truncate function is not
184function peertubeTruncate (str: string, maxLength: number) {
185 const options = {
186 length: maxLength
187 }
188 const truncatedStr = truncate(str, options)
189
190 // The truncated string is okay, we can return it
191 if (truncatedStr.length <= maxLength) return truncatedStr
192
193 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
194 // We always use the .length so we need to truncate more if needed
195 options.length -= truncatedStr.length - maxLength
196 return truncate(str, options)
197}
198
09209296 199function sha256 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
729bb184 200 return createHash('sha256').update(str).digest(encoding)
990b6a0b
C
201}
202
09209296
C
203function sha1 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
204 return createHash('sha1').update(str).digest(encoding)
205}
206
6fcd19ba
C
207function promisify0<A> (func: (cb: (err: any, result: A) => void) => void): () => Promise<A> {
208 return function promisified (): Promise<A> {
209 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
210 func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ])
211 })
212 }
213}
214
215// Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2
216function promisify1<T, A> (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise<A> {
217 return function promisified (arg: T): Promise<A> {
218 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
219 func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ])
220 })
221 }
222}
223
224function promisify1WithVoid<T> (func: (arg: T, cb: (err: any) => void) => void): (arg: T) => Promise<void> {
225 return function promisified (arg: T): Promise<void> {
226 return new Promise<void>((resolve: () => void, reject: (err: any) => void) => {
227 func.apply(null, [ arg, (err: any) => err ? reject(err) : resolve() ])
228 })
229 }
230}
231
232function promisify2<T, U, A> (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise<A> {
233 return function promisified (arg1: T, arg2: U): Promise<A> {
234 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
235 func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ])
236 })
237 }
238}
239
240function promisify2WithVoid<T, U> (func: (arg1: T, arg2: U, cb: (err: any) => void) => void): (arg1: T, arg2: U) => Promise<void> {
241 return function promisified (arg1: T, arg2: U): Promise<void> {
242 return new Promise<void>((resolve: () => void, reject: (err: any) => void) => {
243 func.apply(null, [ arg1, arg2, (err: any) => err ? reject(err) : resolve() ])
244 })
245 }
246}
247
6fcd19ba 248const pseudoRandomBytesPromise = promisify1<number, Buffer>(pseudoRandomBytes)
e4f97bab
C
249const createPrivateKey = promisify1<number, { key: string }>(pem.createPrivateKey)
250const getPublicKey = promisify1<string, { publicKey: string }>(pem.getPublicKey)
6fcd19ba
C
251const bcryptComparePromise = promisify2<any, string, boolean>(bcrypt.compare)
252const bcryptGenSaltPromise = promisify1<number, string>(bcrypt.genSalt)
53abc4c2 253const bcryptHashPromise = promisify2<any, string | number, string>(bcrypt.hash)
6fcd19ba 254const createTorrentPromise = promisify2<string, any, any>(createTorrent)
499d9015
C
255const execPromise2 = promisify2<string, any, string>(exec)
256const execPromise = promisify1<string, string>(exec)
6fcd19ba 257
1840c2f7
C
258// ---------------------------------------------------------------------------
259
260export {
261 isTestInstance,
00f9e41e 262 isProdInstance,
1a12f66d 263 getAppNumber,
00f9e41e 264
a4101923 265 objectConverter,
6fcd19ba 266 root,
49347a0a 267 escapeHTML,
e4f97bab 268 pageToStartAndCount,
225a89c2
C
269 sanitizeUrl,
270 sanitizeHost,
0b4204f9 271 buildPath,
c73e83da 272 peertubeTruncate,
09209296 273
990b6a0b 274 sha256,
09209296 275 sha1,
6fcd19ba
C
276
277 promisify0,
278 promisify1,
e4f97bab 279
6fcd19ba 280 pseudoRandomBytesPromise,
e4f97bab
C
281 createPrivateKey,
282 getPublicKey,
6fcd19ba
C
283 bcryptComparePromise,
284 bcryptGenSaltPromise,
285 bcryptHashPromise,
499d9015
C
286 createTorrentPromise,
287 execPromise2,
288 execPromise
1840c2f7 289}