]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/utils.ts
Bumped to version v1.0.0-rc.1
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
... / ...
CommitLineData
1import { ResultList } from '../../shared'
2import { CONFIG } from '../initializers'
3import { ApplicationModel } from '../models/application/application'
4import { pseudoRandomBytesPromise, sha256 } from './core-utils'
5import { logger } from './logger'
6import { join } from 'path'
7import { Instance as ParseTorrent } from 'parse-torrent'
8import { remove } from 'fs-extra'
9import * as memoizee from 'memoizee'
10
11function deleteFileAsync (path: string) {
12 remove(path)
13 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
14}
15
16async function generateRandomString (size: number) {
17 const raw = await pseudoRandomBytesPromise(size)
18
19 return raw.toString('hex')
20}
21
22interface FormattableToJSON {
23 toFormattedJSON (args?: any)
24}
25
26function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
27 const formattedObjects: U[] = []
28
29 objects.forEach(object => {
30 formattedObjects.push(object.toFormattedJSON(formattedArg))
31 })
32
33 return {
34 total: objectsTotal,
35 data: formattedObjects
36 } as ResultList<U>
37}
38
39const getServerActor = memoizee(async function () {
40 const application = await ApplicationModel.load()
41 if (!application) throw Error('Could not load Application from database.')
42
43 return application.Account.Actor
44})
45
46function generateVideoTmpPath (target: string | ParseTorrent) {
47 const id = typeof target === 'string' ? target : target.infoHash
48
49 const hash = sha256(id)
50 return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
51}
52
53function getSecureTorrentName (originalName: string) {
54 return sha256(originalName) + '.torrent'
55}
56
57function getVersion () {
58 const tag = require('child_process')
59 .execSync('[[ ! -d .git ]] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true', { stdio: [0,1,2] })
60 if (tag) return tag.replace(/^v/, '')
61
62 const version = require('child_process')
63 .execSync('[[ ! -d .git ]] || git rev-parse --short HEAD').toString().trim()
64 if (version) return version
65
66 return require('../../../package.json').version
67}
68
69// ---------------------------------------------------------------------------
70
71export {
72 deleteFileAsync,
73 generateRandomString,
74 getFormattedObjects,
75 getSecureTorrentName,
76 getServerActor,
77 getVersion,
78 generateVideoTmpPath
79}