]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/utils.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
... / ...
CommitLineData
1import { remove } from 'fs-extra'
2import { Instance as ParseTorrent } from 'parse-torrent'
3import { join } from 'path'
4import { sha256 } from '@shared/extra-utils'
5import { ResultList } from '@shared/models'
6import { CONFIG } from '../initializers/config'
7import { randomBytesPromise } from './core-utils'
8import { logger } from './logger'
9
10function deleteFileAndCatch (path: string) {
11 remove(path)
12 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
13}
14
15async function generateRandomString (size: number) {
16 const raw = await randomBytesPromise(size)
17
18 return raw.toString('hex')
19}
20
21interface FormattableToJSON<U, V> {
22 toFormattedJSON (args?: U): V
23}
24
25function 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
34function 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
43function 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 */
52function 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
63export {
64 deleteFileAndCatch,
65 generateRandomString,
66 getFormattedObjects,
67 getSecureTorrentName,
68 generateVideoImportTmpPath,
69 getUUIDFromFilename
70}