1 /* eslint-disable no-useless-call */
4 Different from 'utils' because we don't import other PeerTube modules.
5 Useful to avoid circular dependencies.
8 import { createHash, HexBase64Latin1Encoding, randomBytes } from 'crypto'
9 import { basename, isAbsolute, join, resolve } from 'path'
10 import * as pem from 'pem'
11 import { URL } from 'url'
12 import { truncate } from 'lodash'
13 import { exec, ExecOptions } from 'child_process'
15 const objectConverter = (oldObject: any, keyConverter: (e: string) => string, valueConverter: (e: any) => any) => {
16 if (!oldObject || typeof oldObject !== 'object') {
17 return valueConverter(oldObject)
20 if (Array.isArray(oldObject)) {
21 return oldObject.map(e => objectConverter(e, keyConverter, valueConverter))
25 Object.keys(oldObject).forEach(oldKey => {
26 const newKey = keyConverter(oldKey)
27 newObject[newKey] = objectConverter(oldObject[oldKey], keyConverter, valueConverter)
39 week: 3600000 * 24 * 7,
40 month: 3600000 * 24 * 30
43 export function parseDurationToMs (duration: number | string): number {
44 if (duration === null) return null
45 if (typeof duration === 'number') return duration
47 if (typeof duration === 'string') {
48 const split = duration.match(/^([\d.,]+)\s?(\w+)$/)
50 if (split.length === 3) {
51 const len = parseFloat(split[1])
52 let unit = split[2].replace(/s$/i, '').toLowerCase()
57 return (len || 1) * (timeTable[unit] || 0)
61 throw new Error(`Duration ${duration} could not be properly parsed`)
64 export function parseBytes (value: string | number): number {
65 if (typeof value === 'number') return value
67 const tgm = /^(\d+)\s*TB\s*(\d+)\s*GB\s*(\d+)\s*MB$/
68 const tg = /^(\d+)\s*TB\s*(\d+)\s*GB$/
69 const tm = /^(\d+)\s*TB\s*(\d+)\s*MB$/
70 const gm = /^(\d+)\s*GB\s*(\d+)\s*MB$/
71 const t = /^(\d+)\s*TB$/
72 const g = /^(\d+)\s*GB$/
73 const m = /^(\d+)\s*MB$/
74 const b = /^(\d+)\s*B$/
77 if (value.match(tgm)) {
78 match = value.match(tgm)
79 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
80 parseInt(match[2], 10) * 1024 * 1024 * 1024 +
81 parseInt(match[3], 10) * 1024 * 1024
82 } else if (value.match(tg)) {
83 match = value.match(tg)
84 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
85 parseInt(match[2], 10) * 1024 * 1024 * 1024
86 } else if (value.match(tm)) {
87 match = value.match(tm)
88 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
89 parseInt(match[2], 10) * 1024 * 1024
90 } else if (value.match(gm)) {
91 match = value.match(gm)
92 return parseInt(match[1], 10) * 1024 * 1024 * 1024 +
93 parseInt(match[2], 10) * 1024 * 1024
94 } else if (value.match(t)) {
95 match = value.match(t)
96 return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
97 } else if (value.match(g)) {
98 match = value.match(g)
99 return parseInt(match[1], 10) * 1024 * 1024 * 1024
100 } else if (value.match(m)) {
101 match = value.match(m)
102 return parseInt(match[1], 10) * 1024 * 1024
103 } else if (value.match(b)) {
104 match = value.match(b)
105 return parseInt(match[1], 10) * 1024
107 return parseInt(value, 10)
111 function sanitizeUrl (url: string) {
112 const urlObject = new URL(url)
114 if (urlObject.protocol === 'https:' && urlObject.port === '443') {
116 } else if (urlObject.protocol === 'http:' && urlObject.port === '80') {
120 return urlObject.href.replace(/\/$/, '')
123 // Don't import remote scheme from constants because we are in core utils
124 function sanitizeHost (host: string, remoteScheme: string) {
125 const toRemove = remoteScheme === 'https' ? 443 : 80
127 return host.replace(new RegExp(`:${toRemove}$`), '')
130 function isTestInstance () {
131 return process.env.NODE_ENV === 'test'
134 function isProdInstance () {
135 return process.env.NODE_ENV === 'production'
138 function getAppNumber () {
139 return process.env.NODE_APP_INSTANCE
145 if (rootPath) return rootPath
147 // We are in /helpers/utils.js
148 rootPath = join(__dirname, '..', '..')
150 if (basename(rootPath) === 'dist') rootPath = resolve(rootPath, '..')
155 // Thanks: https://stackoverflow.com/a/12034334
156 function escapeHTML (stringParam) {
157 if (!stringParam) return ''
170 return String(stringParam).replace(/[&<>"'`=/]/g, s => entityMap[s])
173 function pageToStartAndCount (page: number, itemsPerPage: number) {
174 const start = (page - 1) * itemsPerPage
176 return { start, count: itemsPerPage }
179 function mapToJSON (map: Map<any, any>) {
182 for (const [ k, v ] of map) {
189 function buildPath (path: string) {
190 if (isAbsolute(path)) return path
192 return join(root(), path)
195 // Consistent with .length, lodash truncate function is not
196 function peertubeTruncate (str: string, options: { length: number, separator?: RegExp, omission?: string }) {
197 const truncatedStr = truncate(str, options)
199 // The truncated string is okay, we can return it
200 if (truncatedStr.length <= options.length) return truncatedStr
202 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
203 // We always use the .length so we need to truncate more if needed
204 options.length -= truncatedStr.length - options.length
205 return truncate(str, options)
208 function sha256 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
209 return createHash('sha256').update(str).digest(encoding)
212 function sha1 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
213 return createHash('sha1').update(str).digest(encoding)
216 function execShell (command: string, options?: ExecOptions) {
217 return new Promise<{ err?: Error, stdout: string, stderr: string }>((res, rej) => {
218 exec(command, options, (err, stdout, stderr) => {
219 // eslint-disable-next-line prefer-promise-reject-errors
220 if (err) return rej({ err, stdout, stderr })
222 return res({ stdout, stderr })
227 function promisify0<A> (func: (cb: (err: any, result: A) => void) => void): () => Promise<A> {
228 return function promisified (): Promise<A> {
229 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
230 func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ])
235 // Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2
236 function promisify1<T, A> (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise<A> {
237 return function promisified (arg: T): Promise<A> {
238 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
239 func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ])
244 function promisify2<T, U, A> (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise<A> {
245 return function promisified (arg1: T, arg2: U): Promise<A> {
246 return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
247 func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ])
252 const randomBytesPromise = promisify1<number, Buffer>(randomBytes)
253 const createPrivateKey = promisify1<number, { key: string }>(pem.createPrivateKey)
254 const getPublicKey = promisify1<string, { publicKey: string }>(pem.getPublicKey)
255 const execPromise2 = promisify2<string, any, string>(exec)
256 const execPromise = promisify1<string, string>(exec)
258 // ---------------------------------------------------------------------------