2
1

core-utils.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /* eslint-disable no-useless-call */
  2. /*
  3. Different from 'utils' because we don't import other PeerTube modules.
  4. Useful to avoid circular dependencies.
  5. */
  6. import { createHash, HexBase64Latin1Encoding, randomBytes } from 'crypto'
  7. import { basename, isAbsolute, join, resolve } from 'path'
  8. import * as pem from 'pem'
  9. import { URL } from 'url'
  10. import { truncate } from 'lodash'
  11. import { exec, ExecOptions } from 'child_process'
  12. const objectConverter = (oldObject: any, keyConverter: (e: string) => string, valueConverter: (e: any) => any) => {
  13. if (!oldObject || typeof oldObject !== 'object') {
  14. return valueConverter(oldObject)
  15. }
  16. if (Array.isArray(oldObject)) {
  17. return oldObject.map(e => objectConverter(e, keyConverter, valueConverter))
  18. }
  19. const newObject = {}
  20. Object.keys(oldObject).forEach(oldKey => {
  21. const newKey = keyConverter(oldKey)
  22. newObject[newKey] = objectConverter(oldObject[oldKey], keyConverter, valueConverter)
  23. })
  24. return newObject
  25. }
  26. const timeTable = {
  27. ms: 1,
  28. second: 1000,
  29. minute: 60000,
  30. hour: 3600000,
  31. day: 3600000 * 24,
  32. week: 3600000 * 24 * 7,
  33. month: 3600000 * 24 * 30
  34. }
  35. export function parseDurationToMs (duration: number | string): number {
  36. if (typeof duration === 'number') return duration
  37. if (typeof duration === 'string') {
  38. const split = duration.match(/^([\d.,]+)\s?(\w+)$/)
  39. if (split.length === 3) {
  40. const len = parseFloat(split[1])
  41. let unit = split[2].replace(/s$/i, '').toLowerCase()
  42. if (unit === 'm') {
  43. unit = 'ms'
  44. }
  45. return (len || 1) * (timeTable[unit] || 0)
  46. }
  47. }
  48. throw new Error(`Duration ${duration} could not be properly parsed`)
  49. }
  50. export function parseBytes (value: string | number): number {
  51. if (typeof value === 'number') return value
  52. const tgm = /^(\d+)\s*TB\s*(\d+)\s*GB\s*(\d+)\s*MB$/
  53. const tg = /^(\d+)\s*TB\s*(\d+)\s*GB$/
  54. const tm = /^(\d+)\s*TB\s*(\d+)\s*MB$/
  55. const gm = /^(\d+)\s*GB\s*(\d+)\s*MB$/
  56. const t = /^(\d+)\s*TB$/
  57. const g = /^(\d+)\s*GB$/
  58. const m = /^(\d+)\s*MB$/
  59. const b = /^(\d+)\s*B$/
  60. let match
  61. if (value.match(tgm)) {
  62. match = value.match(tgm)
  63. return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
  64. parseInt(match[2], 10) * 1024 * 1024 * 1024 +
  65. parseInt(match[3], 10) * 1024 * 1024
  66. } else if (value.match(tg)) {
  67. match = value.match(tg)
  68. return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
  69. parseInt(match[2], 10) * 1024 * 1024 * 1024
  70. } else if (value.match(tm)) {
  71. match = value.match(tm)
  72. return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024 +
  73. parseInt(match[2], 10) * 1024 * 1024
  74. } else if (value.match(gm)) {
  75. match = value.match(gm)
  76. return parseInt(match[1], 10) * 1024 * 1024 * 1024 +
  77. parseInt(match[2], 10) * 1024 * 1024
  78. } else if (value.match(t)) {
  79. match = value.match(t)
  80. return parseInt(match[1], 10) * 1024 * 1024 * 1024 * 1024
  81. } else if (value.match(g)) {
  82. match = value.match(g)
  83. return parseInt(match[1], 10) * 1024 * 1024 * 1024
  84. } else if (value.match(m)) {
  85. match = value.match(m)
  86. return parseInt(match[1], 10) * 1024 * 1024
  87. } else if (value.match(b)) {
  88. match = value.match(b)
  89. return parseInt(match[1], 10) * 1024
  90. } else {
  91. return parseInt(value, 10)
  92. }
  93. }
  94. function sanitizeUrl (url: string) {
  95. const urlObject = new URL(url)
  96. if (urlObject.protocol === 'https:' && urlObject.port === '443') {
  97. urlObject.port = ''
  98. } else if (urlObject.protocol === 'http:' && urlObject.port === '80') {
  99. urlObject.port = ''
  100. }
  101. return urlObject.href.replace(/\/$/, '')
  102. }
  103. // Don't import remote scheme from constants because we are in core utils
  104. function sanitizeHost (host: string, remoteScheme: string) {
  105. const toRemove = remoteScheme === 'https' ? 443 : 80
  106. return host.replace(new RegExp(`:${toRemove}$`), '')
  107. }
  108. function isTestInstance () {
  109. return process.env.NODE_ENV === 'test'
  110. }
  111. function isProdInstance () {
  112. return process.env.NODE_ENV === 'production'
  113. }
  114. function getAppNumber () {
  115. return process.env.NODE_APP_INSTANCE
  116. }
  117. let rootPath: string
  118. function root () {
  119. if (rootPath) return rootPath
  120. // We are in /helpers/utils.js
  121. rootPath = join(__dirname, '..', '..')
  122. if (basename(rootPath) === 'dist') rootPath = resolve(rootPath, '..')
  123. return rootPath
  124. }
  125. // Thanks: https://stackoverflow.com/a/12034334
  126. function escapeHTML (stringParam) {
  127. if (!stringParam) return ''
  128. const entityMap = {
  129. '&': '&',
  130. '<': '&lt;',
  131. '>': '&gt;',
  132. '"': '&quot;',
  133. '\'': '&#39;',
  134. '/': '&#x2F;',
  135. '`': '&#x60;',
  136. '=': '&#x3D;'
  137. }
  138. return String(stringParam).replace(/[&<>"'`=/]/g, s => entityMap[s])
  139. }
  140. function pageToStartAndCount (page: number, itemsPerPage: number) {
  141. const start = (page - 1) * itemsPerPage
  142. return { start, count: itemsPerPage }
  143. }
  144. function buildPath (path: string) {
  145. if (isAbsolute(path)) return path
  146. return join(root(), path)
  147. }
  148. // Consistent with .length, lodash truncate function is not
  149. function peertubeTruncate (str: string, options: { length: number, separator?: RegExp, omission?: string }) {
  150. const truncatedStr = truncate(str, options)
  151. // The truncated string is okay, we can return it
  152. if (truncatedStr.length <= options.length) return truncatedStr
  153. // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
  154. // We always use the .length so we need to truncate more if needed
  155. options.length -= truncatedStr.length - options.length
  156. return truncate(str, options)
  157. }
  158. function sha256 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
  159. return createHash('sha256').update(str).digest(encoding)
  160. }
  161. function sha1 (str: string | Buffer, encoding: HexBase64Latin1Encoding = 'hex') {
  162. return createHash('sha1').update(str).digest(encoding)
  163. }
  164. function execShell (command: string, options?: ExecOptions) {
  165. return new Promise<{ err?: Error, stdout: string, stderr: string }>((res, rej) => {
  166. exec(command, options, (err, stdout, stderr) => {
  167. // eslint-disable-next-line prefer-promise-reject-errors
  168. if (err) return rej({ err, stdout, stderr })
  169. return res({ stdout, stderr })
  170. })
  171. })
  172. }
  173. function promisify0<A> (func: (cb: (err: any, result: A) => void) => void): () => Promise<A> {
  174. return function promisified (): Promise<A> {
  175. return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
  176. func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ])
  177. })
  178. }
  179. }
  180. // Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2
  181. function promisify1<T, A> (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise<A> {
  182. return function promisified (arg: T): Promise<A> {
  183. return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
  184. func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ])
  185. })
  186. }
  187. }
  188. function promisify2<T, U, A> (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise<A> {
  189. return function promisified (arg1: T, arg2: U): Promise<A> {
  190. return new Promise<A>((resolve: (arg: A) => void, reject: (err: any) => void) => {
  191. func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ])
  192. })
  193. }
  194. }
  195. const randomBytesPromise = promisify1<number, Buffer>(randomBytes)
  196. const createPrivateKey = promisify1<number, { key: string }>(pem.createPrivateKey)
  197. const getPublicKey = promisify1<string, { publicKey: string }>(pem.getPublicKey)
  198. const execPromise2 = promisify2<string, any, string>(exec)
  199. const execPromise = promisify1<string, string>(exec)
  200. // ---------------------------------------------------------------------------
  201. export {
  202. isTestInstance,
  203. isProdInstance,
  204. getAppNumber,
  205. objectConverter,
  206. root,
  207. escapeHTML,
  208. pageToStartAndCount,
  209. sanitizeUrl,
  210. sanitizeHost,
  211. buildPath,
  212. execShell,
  213. peertubeTruncate,
  214. sha256,
  215. sha1,
  216. promisify0,
  217. promisify1,
  218. promisify2,
  219. randomBytesPromise,
  220. createPrivateKey,
  221. getPublicKey,
  222. execPromise2,
  223. execPromise
  224. }