Merge branch 'release/1.4.0' into develop
[oweals/peertube.git] / server / helpers / utils.ts
1 import { ResultList } from '../../shared'
2 import { ApplicationModel } from '../models/application/application'
3 import { execPromise, execPromise2, pseudoRandomBytesPromise, sha256 } from './core-utils'
4 import { logger } from './logger'
5 import { join } from 'path'
6 import { Instance as ParseTorrent } from 'parse-torrent'
7 import { remove } from 'fs-extra'
8 import * as memoizee from 'memoizee'
9 import { CONFIG } from '../initializers/config'
10
11 function deleteFileAsync (path: string) {
12   remove(path)
13     .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
14 }
15
16 async function generateRandomString (size: number) {
17   const raw = await pseudoRandomBytesPromise(size)
18
19   return raw.toString('hex')
20 }
21
22 interface FormattableToJSON<U, V> {
23   toFormattedJSON (args?: U): V
24 }
25
26 function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
27   const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
28
29   return {
30     total: objectsTotal,
31     data: formattedObjects
32   } as ResultList<V>
33 }
34
35 const getServerActor = memoizee(async function () {
36   const application = await ApplicationModel.load()
37   if (!application) throw Error('Could not load Application from database.')
38
39   const actor = application.Account.Actor
40   actor.Account = application.Account
41
42   return actor
43 })
44
45 function generateVideoImportTmpPath (target: string | ParseTorrent) {
46   const id = typeof target === 'string' ? target : target.infoHash
47
48   const hash = sha256(id)
49   return join(CONFIG.STORAGE.TMP_DIR, hash + '-import.mp4')
50 }
51
52 function getSecureTorrentName (originalName: string) {
53   return sha256(originalName) + '.torrent'
54 }
55
56 async function getServerCommit () {
57   try {
58     const tag = await execPromise2(
59       '[ ! -d .git ] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true',
60       { stdio: [ 0, 1, 2 ] }
61     )
62
63     if (tag) return tag.replace(/^v/, '')
64   } catch (err) {
65     logger.debug('Cannot get version from git tags.', { err })
66   }
67
68   try {
69     const version = await execPromise('[ ! -d .git ] || git rev-parse --short HEAD')
70
71     if (version) return version.toString().trim()
72   } catch (err) {
73     logger.debug('Cannot get version from git HEAD.', { err })
74   }
75
76   return ''
77 }
78
79 /**
80  * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
81  * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
82  * not contain a UUID, returns null.
83  */
84 function getUUIDFromFilename (filename: string) {
85   const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
86   const result = filename.match(regex)
87
88   if (!result || Array.isArray(result) === false) return null
89
90   return result[0]
91 }
92
93 // ---------------------------------------------------------------------------
94
95 export {
96   deleteFileAsync,
97   generateRandomString,
98   getFormattedObjects,
99   getSecureTorrentName,
100   getServerActor,
101   getServerCommit,
102   generateVideoImportTmpPath,
103   getUUIDFromFilename
104 }