]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/core-utils.ts
Correctly close RTMPS server too
[github/Chocobozzz/PeerTube.git] / server / helpers / core-utils.ts
CommitLineData
a1587156
C
1/* eslint-disable no-useless-call */
2
1840c2f7 3/*
272abc0b 4 Different from 'utils' because we don't import other PeerTube modules.
1840c2f7
C
5 Useful to avoid circular dependencies.
6*/
7
ba5a8d89
C
8import { exec, ExecOptions } from 'child_process'
9import { BinaryToTextEncoding, createHash, randomBytes } from 'crypto'
10import { truncate } from 'lodash'
ea54cd04 11import { basename, extname, isAbsolute, join, resolve } from 'path'
41fb13c3 12import { createPrivateKey as createPrivateKey_1, getPublicKey as getPublicKey_1 } from 'pem'
db4b15f2 13import { pipeline } from 'stream'
225a89c2 14import { URL } from 'url'
db4b15f2 15import { promisify } from 'util'
a4101923
C
16
17const objectConverter = (oldObject: any, keyConverter: (e: string) => string, valueConverter: (e: any) => any) => {
18 if (!oldObject || typeof oldObject !== 'object') {
19 return valueConverter(oldObject)
20 }
21
74dc3bca 22 if (Array.isArray(oldObject)) {
a4101923
C
23 return oldObject.map(e => objectConverter(e, keyConverter, valueConverter))
24 }
25
26 const newObject = {}
27 Object.keys(oldObject).forEach(oldKey => {
28 const newKey = keyConverter(oldKey)
a1587156 29 newObject[newKey] = objectConverter(oldObject[oldKey], keyConverter, valueConverter)
a4101923
C
30 })
31
32 return newObject
33}
225a89c2 34
ea54cd04
C
35function mapToJSON (map: Map<any, any>) {
36 const obj: any = {}
37
38 for (const [ k, v ] of map) {
39 obj[k] = v
40 }
41
42 return obj
43}
44
45// ---------------------------------------------------------------------------
46
06215f15 47const timeTable = {
a1587156
C
48 ms: 1,
49 second: 1000,
50 minute: 60000,
51 hour: 3600000,
52 day: 3600000 * 24,
53 week: 3600000 * 24 * 7,
54 month: 3600000 * 24 * 30
06215f15 55}
0e5ff97f 56
8f0bc73d 57export function parseDurationToMs (duration: number | string): number {
fb719404 58 if (duration === null) return null
06215f15
C
59 if (typeof duration === 'number') return duration
60
61 if (typeof duration === 'string') {
a1587156 62 const split = duration.match(/^([\d.,]+)\s?(\w+)$/)
06215f15
C
63
64 if (split.length === 3) {
65 const len = parseFloat(split[1])
a1587156 66 let unit = split[2].replace(/s$/i, '').toLowerCase()
06215f15
C
67 if (unit === 'm') {
68 unit = 'ms'
69 }
70
71 return (len || 1) * (timeTable[unit] || 0)
72 }
73 }
74
ae9bbed4 75 throw new Error(`Duration ${duration} could not be properly parsed`)
06215f15
C
76}
77
0e5ff97f
BY
78export function parseBytes (value: string | number): number {
79 if (typeof value === 'number') return value
80
81 const tgm = /^(\d+)\s*TB\s*(\d+)\s*GB\s*(\d+)\s*MB$/
82 const tg = /^(\d+)\s*TB\s*(\d+)\s*GB$/
83 const tm = /^(\d+)\s*TB\s*(\d+)\s*MB$/
84 const gm = /^(\d+)\s*GB\s*(\d+)\s*MB$/
85 const t = /^(\d+)\s*TB$/
86 const g = /^(\d+)\s*GB$/
87 const m = /^(\d+)\s*MB$/
88 const b = /^(\d+)\s*B$/
89 let match
90
91 if (value.match(tgm)) {
92 match = value.match(tgm)
a1587156
C
93 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
94 parseInt(match[2], 10) * 1024 * 1024 * 1024 +
95 parseInt(match[3], 10) * 1024 * 1024
0e5ff97f
BY
96 } else if (value.match(tg)) {
97 match = value.match(tg)
a1587156
C
98 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
99 parseInt(match[2], 10) * 1024 * 1024 * 1024
0e5ff97f
BY
100 } else if (value.match(tm)) {
101 match = value.match(tm)
a1587156
C
102 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
103 parseInt(match[2], 10) * 1024 * 1024
0e5ff97f
BY
104 } else if (value.match(gm)) {
105 match = value.match(gm)
a1587156
C
106 return parseInt(match[1], 10) * 1024 * 1024 * 1024 +
107 parseInt(match[2], 10) * 1024 * 1024
0e5ff97f
BY
108 } else if (value.match(t)) {
109 match = value.match(t)
110 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
111 } else if (value.match(g)) {
112 match = value.match(g)
113 return parseInt(match[1], 10) * 1024 * 1024 * 1024
114 } else if (value.match(m)) {
115 match = value.match(m)
116 return parseInt(match[1], 10) * 1024 * 1024
117 } else if (value.match(b)) {
118 match = value.match(b)
119 return parseInt(match[1], 10) * 1024
120 } else {
121 return parseInt(value, 10)
122 }
123}
124
ea54cd04
C
125// ---------------------------------------------------------------------------
126
225a89c2
C
127function sanitizeUrl (url: string) {
128 const urlObject = new URL(url)
129
130 if (urlObject.protocol === 'https:' && urlObject.port === '443') {
131 urlObject.port = ''
132 } else if (urlObject.protocol === 'http:' && urlObject.port === '80') {
133 urlObject.port = ''
134 }
135
136 return urlObject.href.replace(/\/$/, '')
137}
138
139// Don't import remote scheme from constants because we are in core utils
140function sanitizeHost (host: string, remoteScheme: string) {
604abfbe 141 const toRemove = remoteScheme === 'https' ? 443 : 80
225a89c2
C
142
143 return host.replace(new RegExp(`:${toRemove}$`), '')
144}
1840c2f7 145
ea54cd04
C
146// ---------------------------------------------------------------------------
147
1840c2f7
C
148function isTestInstance () {
149 return process.env.NODE_ENV === 'test'
150}
151
00f9e41e
C
152function isProdInstance () {
153 return process.env.NODE_ENV === 'production'
154}
155
1a12f66d
C
156function getAppNumber () {
157 return process.env.NODE_APP_INSTANCE
158}
159
ea54cd04
C
160// ---------------------------------------------------------------------------
161
9b474844 162let rootPath: string
a1587156 163
1840c2f7 164function root () {
9b474844
C
165 if (rootPath) return rootPath
166
e874edd9 167 rootPath = __dirname
fdbda9e3 168
e874edd9
C
169 if (basename(rootPath) === 'helpers') rootPath = resolve(rootPath, '..')
170 if (basename(rootPath) === 'server') rootPath = resolve(rootPath, '..')
9b474844 171 if (basename(rootPath) === 'dist') rootPath = resolve(rootPath, '..')
fdbda9e3 172
9b474844 173 return rootPath
1840c2f7
C
174}
175
ea54cd04
C
176function buildPath (path: string) {
177 if (isAbsolute(path)) return path
e4f97bab 178
ea54cd04 179 return join(root(), path)
e4f97bab
C
180}
181
ea54cd04
C
182function getLowercaseExtension (filename: string) {
183 const ext = extname(filename) || ''
c6c0fa6c 184
ea54cd04 185 return ext.toLowerCase()
c6c0fa6c
C
186}
187
ea54cd04 188// ---------------------------------------------------------------------------
0b4204f9 189
c73e83da 190// Consistent with .length, lodash truncate function is not
687c6180 191function peertubeTruncate (str: string, options: { length: number, separator?: RegExp, omission?: string }) {
c73e83da
C
192 const truncatedStr = truncate(str, options)
193
194 // The truncated string is okay, we can return it
687c6180 195 if (truncatedStr.length <= options.length) return truncatedStr
c73e83da
C
196
197 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
198 // We always use the .length so we need to truncate more if needed
687c6180 199 options.length -= truncatedStr.length - options.length
c73e83da
C
200 return truncate(str, options)
201}
202
ea54cd04
C
203function pageToStartAndCount (page: number, itemsPerPage: number) {
204 const start = (page - 1) * itemsPerPage
205
206 return { start, count: itemsPerPage }
207}
208
209// ---------------------------------------------------------------------------
210
211type SemVersion = { major: number, minor: number, patch: number }
212function parseSemVersion (s: string) {
213 const parsed = s.match(/^v?(\d+)\.(\d+)\.(\d+)$/i)
214
215 return {
216 major: parseInt(parsed[1]),
217 minor: parseInt(parsed[2]),
218 patch: parseInt(parsed[3])
219 } as SemVersion
220}
221
222// ---------------------------------------------------------------------------
223
ba5a8d89 224function sha256 (str: string | Buffer, encoding: BinaryToTextEncoding = 'hex') {
729bb184 225 return createHash('sha256').update(str).digest(encoding)
990b6a0b
C
226}
227
ba5a8d89 228function sha1 (str: string | Buffer, encoding: BinaryToTextEncoding = 'hex') {
09209296
C
229 return createHash('sha1').update(str).digest(encoding)
230}
231
ea54cd04
C
232// ---------------------------------------------------------------------------
233
f023a19c
C
234function execShell (command: string, options?: ExecOptions) {
235 return new Promise<{ err?: Error, stdout: string, stderr: string }>((res, rej) => {
236 exec(command, options, (err, stdout, stderr) => {
a1587156 237 // eslint-disable-next-line prefer-promise-reject-errors
f023a19c
C
238 if (err) return rej({ err, stdout, stderr })
239
240 return res({ stdout, stderr })
241 })
242 })
243}
244
ea54cd04
C
245// ---------------------------------------------------------------------------
246
318b0bd0
C
247function isOdd (num: number) {
248 return (num % 2) !== 0
249}
250
251function toEven (num: number) {
b7c8304c 252 if (isOdd(num)) return num + 1
318b0bd0
C
253
254 return num
255}
256
257// ---------------------------------------------------------------------------
258
6fcd19ba
C
259function promisify0<A> (func: (cb: (err: any, result: A) => void) => void): () => Promise<A> {
260 return function promisified (): Promise<A> {
261 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
262 func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ])
263 })
264 }
265}
266
267// Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2
268function promisify1<T, A> (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise<A> {
269 return function promisified (arg: T): Promise<A> {
270 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
271 func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ])
272 })
273 }
274}
275
6fcd19ba
C
276function promisify2<T, U, A> (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise<A> {
277 return function promisified (arg1: T, arg2: U): Promise<A> {
278 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
279 func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ])
280 })
281 }
282}
283
a1587156 284const randomBytesPromise = promisify1<number, Buffer>(randomBytes)
41fb13c3
C
285const createPrivateKey = promisify1<number, { key: string }>(createPrivateKey_1)
286const getPublicKey = promisify1<string, { publicKey: string }>(getPublicKey_1)
499d9015
C
287const execPromise2 = promisify2<string, any, string>(exec)
288const execPromise = promisify1<string, string>(exec)
db4b15f2 289const pipelinePromise = promisify(pipeline)
6fcd19ba 290
1840c2f7
C
291// ---------------------------------------------------------------------------
292
293export {
294 isTestInstance,
00f9e41e 295 isProdInstance,
1a12f66d 296 getAppNumber,
00f9e41e 297
a4101923 298 objectConverter,
ea54cd04
C
299 mapToJSON,
300
6fcd19ba 301 root,
ea54cd04
C
302 buildPath,
303 getLowercaseExtension,
225a89c2
C
304 sanitizeUrl,
305 sanitizeHost,
ea54cd04 306
f023a19c 307 execShell,
ea54cd04
C
308
309 pageToStartAndCount,
c73e83da 310 peertubeTruncate,
09209296 311
990b6a0b 312 sha256,
09209296 313 sha1,
6fcd19ba
C
314
315 promisify0,
316 promisify1,
8d2be0ed 317 promisify2,
e4f97bab 318
a1587156 319 randomBytesPromise,
e4f97bab
C
320 createPrivateKey,
321 getPublicKey,
499d9015 322 execPromise2,
db4b15f2 323 execPromise,
ae71acca
C
324 pipelinePromise,
325
318b0bd0
C
326 parseSemVersion,
327
328 isOdd,
329 toEven
1840c2f7 330}