Add plugin static files cache
[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> { toFormattedJSON (args?: U): V }
23 function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
24   const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
25
26   return {
27     total: objectsTotal,
28     data: formattedObjects
29   } as ResultList<V>
30 }
31
32 const getServerActor = memoizee(async function () {
33   const application = await ApplicationModel.load()
34   if (!application) throw Error('Could not load Application from database.')
35
36   const actor = application.Account.Actor
37   actor.Account = application.Account
38
39   return actor
40 })
41
42 function generateVideoImportTmpPath (target: string | ParseTorrent) {
43   const id = typeof target === 'string' ? target : target.infoHash
44
45   const hash = sha256(id)
46   return join(CONFIG.STORAGE.TMP_DIR, hash + '-import.mp4')
47 }
48
49 function getSecureTorrentName (originalName: string) {
50   return sha256(originalName) + '.torrent'
51 }
52
53 async function getServerCommit () {
54   try {
55     const tag = await execPromise2(
56       '[ ! -d .git ] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true',
57       { stdio: [ 0, 1, 2 ] }
58     )
59
60     if (tag) return tag.replace(/^v/, '')
61   } catch (err) {
62     logger.debug('Cannot get version from git tags.', { err })
63   }
64
65   try {
66     const version = await execPromise('[ ! -d .git ] || git rev-parse --short HEAD')
67
68     if (version) return version.toString().trim()
69   } catch (err) {
70     logger.debug('Cannot get version from git HEAD.', { err })
71   }
72
73   return ''
74 }
75
76 /**
77  * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
78  * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
79  * not contain a UUID, returns null.
80  */
81 function getUUIDFromFilename (filename: string) {
82   const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
83   const result = filename.match(regex)
84
85   if (!result || Array.isArray(result) === false) return null
86
87   return result[0]
88 }
89
90 // ---------------------------------------------------------------------------
91
92 export {
93   deleteFileAsync,
94   generateRandomString,
95   getFormattedObjects,
96   getSecureTorrentName,
97   getServerActor,
98   getServerCommit,
99   generateVideoImportTmpPath,
100   getUUIDFromFilename
101 }