]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/core-utils.ts
Refactor video creation
[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
a1587156 8import { createHash, HexBase64Latin1Encoding, randomBytes } from 'crypto'
9b474844 9import { basename, isAbsolute, join, resolve } from 'path'
e4f97bab 10import * as pem from 'pem'
225a89c2 11import { URL } from 'url'
c73e83da 12import { truncate } from 'lodash'
f023a19c 13import { exec, ExecOptions } 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)
a1587156 27 newObject[newKey] = objectConverter(oldObject[oldKey], keyConverter, valueConverter)
a4101923
C
28 })
29
30 return newObject
31}
225a89c2 32
06215f15 33const timeTable = {
a1587156
C
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
06215f15 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') {
a1587156 47 const split = duration.match(/^([\d.,]+)\s?(\w+)$/)
06215f15
C
48
49 if (split.length === 3) {
50 const len = parseFloat(split[1])
a1587156 51 let unit = split[2].replace(/s$/i, '').toLowerCase()
06215f15
C
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)
a1587156
C
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
0e5ff97f
BY
81 } else if (value.match(tg)) {
82 match = value.match(tg)
a1587156
C
83 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
84 parseInt(match[2], 10) * 1024 * 1024 * 1024
0e5ff97f
BY
85 } else if (value.match(tm)) {
86 match = value.match(tm)
a1587156
C
87 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
88 parseInt(match[2], 10) * 1024 * 1024
0e5ff97f
BY
89 } else if (value.match(gm)) {
90 match = value.match(gm)
a1587156
C
91 return parseInt(match[1], 10) * 1024 * 1024 * 1024 +
92 parseInt(match[2], 10) * 1024 * 1024
0e5ff97f
BY
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
9b474844 141let rootPath: string
a1587156 142
1840c2f7 143function root () {
9b474844
C
144 if (rootPath) return rootPath
145
fdbda9e3 146 // We are in /helpers/utils.js
9b474844 147 rootPath = join(__dirname, '..', '..')
fdbda9e3 148
9b474844 149 if (basename(rootPath) === 'dist') rootPath = resolve(rootPath, '..')
fdbda9e3 150
9b474844 151 return rootPath
1840c2f7
C
152}
153
49347a0a
C
154// Thanks: https://stackoverflow.com/a/12034334
155function escapeHTML (stringParam) {
23e27dd5
C
156 if (!stringParam) return ''
157
49347a0a
C
158 const entityMap = {
159 '&': '&',
160 '<': '&lt;',
161 '>': '&gt;',
162 '"': '&quot;',
cf7a61b5 163 '\'': '&#39;',
49347a0a
C
164 '/': '&#x2F;',
165 '`': '&#x60;',
166 '=': '&#x3D;'
167 }
168
a1587156 169 return String(stringParam).replace(/[&<>"'`=/]/g, s => entityMap[s])
49347a0a
C
170}
171
e4f97bab
C
172function pageToStartAndCount (page: number, itemsPerPage: number) {
173 const start = (page - 1) * itemsPerPage
174
175 return { start, count: itemsPerPage }
176}
177
c6c0fa6c
C
178function mapToJSON (map: Map<any, any>) {
179 const obj: any = {}
180
181 for (const [ k, v ] of map) {
182 obj[k] = v
183 }
184
185 return obj
186}
187
0b4204f9
C
188function buildPath (path: string) {
189 if (isAbsolute(path)) return path
190
191 return join(root(), path)
192}
193
c73e83da 194// Consistent with .length, lodash truncate function is not
687c6180 195function peertubeTruncate (str: string, options: { length: number, separator?: RegExp, omission?: string }) {
c73e83da
C
196 const truncatedStr = truncate(str, options)
197
198 // The truncated string is okay, we can return it
687c6180 199 if (truncatedStr.length <= options.length) return truncatedStr
c73e83da
C
200
201 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
202 // We always use the .length so we need to truncate more if needed
687c6180 203 options.length -= truncatedStr.length - options.length
c73e83da
C
204 return truncate(str, options)
205}
206
09209296 207function sha256 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
729bb184 208 return createHash('sha256').update(str).digest(encoding)
990b6a0b
C
209}
210
09209296
C
211function sha1 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
212 return createHash('sha1').update(str).digest(encoding)
213}
214
f023a19c
C
215function execShell (command: string, options?: ExecOptions) {
216 return new Promise<{ err?: Error, stdout: string, stderr: string }>((res, rej) => {
217 exec(command, options, (err, stdout, stderr) => {
a1587156 218 // eslint-disable-next-line prefer-promise-reject-errors
f023a19c
C
219 if (err) return rej({ err, stdout, stderr })
220
221 return res({ stdout, stderr })
222 })
223 })
224}
225
6fcd19ba
C
226function promisify0<A> (func: (cb: (err: any, result: A) => void) => void): () => Promise<A> {
227 return function promisified (): Promise<A> {
228 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
229 func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ])
230 })
231 }
232}
233
234// Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2
235function promisify1<T, A> (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise<A> {
236 return function promisified (arg: T): Promise<A> {
237 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
238 func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ])
239 })
240 }
241}
242
6fcd19ba
C
243function promisify2<T, U, A> (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise<A> {
244 return function promisified (arg1: T, arg2: U): Promise<A> {
245 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
246 func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ])
247 })
248 }
249}
250
a1587156 251const randomBytesPromise = promisify1<number, Buffer>(randomBytes)
e4f97bab
C
252const createPrivateKey = promisify1<number, { key: string }>(pem.createPrivateKey)
253const getPublicKey = promisify1<string, { publicKey: string }>(pem.getPublicKey)
499d9015
C
254const execPromise2 = promisify2<string, any, string>(exec)
255const execPromise = promisify1<string, string>(exec)
6fcd19ba 256
1840c2f7
C
257// ---------------------------------------------------------------------------
258
259export {
260 isTestInstance,
00f9e41e 261 isProdInstance,
1a12f66d 262 getAppNumber,
00f9e41e 263
a4101923 264 objectConverter,
6fcd19ba 265 root,
49347a0a 266 escapeHTML,
e4f97bab 267 pageToStartAndCount,
225a89c2
C
268 sanitizeUrl,
269 sanitizeHost,
0b4204f9 270 buildPath,
f023a19c 271 execShell,
c73e83da 272 peertubeTruncate,
09209296 273
990b6a0b 274 sha256,
09209296 275 sha1,
c6c0fa6c 276 mapToJSON,
6fcd19ba
C
277
278 promisify0,
279 promisify1,
8d2be0ed 280 promisify2,
e4f97bab 281
a1587156 282 randomBytesPromise,
e4f97bab
C
283 createPrivateKey,
284 getPublicKey,
499d9015
C
285 execPromise2,
286 execPromise
1840c2f7 287}