]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/utils.ts
Correctly cleanup sql command
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
1 import { remove } from 'fs-extra'
2 import { Instance as ParseTorrent } from 'parse-torrent'
3 import { join } from 'path'
4 import { sha256 } from '@shared/extra-utils'
5 import { ResultList } from '@shared/models'
6 import { CONFIG } from '../initializers/config'
7 import { randomBytesPromise } from './core-utils'
8 import { logger } from './logger'
9
10 function deleteFileAndCatch (path: string) {
11 remove(path)
12 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
13 }
14
15 async function generateRandomString (size: number) {
16 const raw = await randomBytesPromise(size)
17
18 return raw.toString('hex')
19 }
20
21 interface FormattableToJSON<U, V> {
22 toFormattedJSON (args?: U): V
23 }
24
25 function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
26 const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
27
28 return {
29 total: objectsTotal,
30 data: formattedObjects
31 } as ResultList<V>
32 }
33
34 function generateVideoImportTmpPath (target: string | ParseTorrent, extension = '.mp4') {
35 const id = typeof target === 'string'
36 ? target
37 : target.infoHash
38
39 const hash = sha256(id)
40 return join(CONFIG.STORAGE.TMP_DIR, `${hash}-import${extension}`)
41 }
42
43 function getSecureTorrentName (originalName: string) {
44 return sha256(originalName) + '.torrent'
45 }
46
47 /**
48 * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
49 * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
50 * not contain a UUID, returns null.
51 */
52 function getUUIDFromFilename (filename: string) {
53 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
54 const result = filename.match(regex)
55
56 if (!result || Array.isArray(result) === false) return null
57
58 return result[0]
59 }
60
61 // ---------------------------------------------------------------------------
62
63 export {
64 deleteFileAndCatch,
65 generateRandomString,
66 getFormattedObjects,
67 getSecureTorrentName,
68 generateVideoImportTmpPath,
69 getUUIDFromFilename
70 }