]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/utils.ts
Correctly cleanup sql command
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
CommitLineData
805b8619
C
1import { remove } from 'fs-extra'
2import { Instance as ParseTorrent } from 'parse-torrent'
3import { join } from 'path'
f304a158 4import { sha256 } from '@shared/extra-utils'
d17c7b4e 5import { ResultList } from '@shared/models'
805b8619 6import { CONFIG } from '../initializers/config'
c795e196 7import { randomBytesPromise } from './core-utils'
efc32059 8import { logger } from './logger'
cbe2f7c3 9
f6d6e7f8 10function deleteFileAndCatch (path: string) {
62689b94 11 remove(path)
cf7a61b5
C
12 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
13}
14
f5028693 15async function generateRandomString (size: number) {
a1587156 16 const raw = await randomBytesPromise(size)
f5028693
C
17
18 return raw.toString('hex')
e4c87ec2
C
19}
20
b5fecbf4
C
21interface FormattableToJSON<U, V> {
22 toFormattedJSON (args?: U): V
23}
24
a8b666e9
C
25function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
26 const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
55fa55a9 27
2186386c 28 return {
55fa55a9 29 total: objectsTotal,
0aef76c4 30 data: formattedObjects
a8b666e9 31 } as ResultList<V>
55fa55a9
C
32}
33
805b8619 34function generateVideoImportTmpPath (target: string | ParseTorrent, extension = '.mp4') {
d57d1d83
C
35 const id = typeof target === 'string'
36 ? target
37 : target.infoHash
38
990b6a0b 39 const hash = sha256(id)
d57d1d83 40 return join(CONFIG.STORAGE.TMP_DIR, `${hash}-import${extension}`)
ce33919c
C
41}
42
990b6a0b
C
43function getSecureTorrentName (originalName: string) {
44 return sha256(originalName) + '.torrent'
45}
792dbaf0 46
edb4ffc7
FA
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
9f10b292 61// ---------------------------------------------------------------------------
c45f7f84 62
65fcc311 63export {
f6d6e7f8 64 deleteFileAndCatch,
65fcc311 65 generateRandomString,
0aef76c4 66 getFormattedObjects,
990b6a0b 67 getSecureTorrentName,
6040f87d 68 generateVideoImportTmpPath,
edb4ffc7 69 getUUIDFromFilename
65fcc311 70}