a1ed8e72df461650e7f697c7bebf8cc94b62a5a2
[oweals/peertube.git] / server / helpers / utils.ts
1 import { ResultList } from '../../shared'
2 import { CONFIG } from '../initializers'
3 import { ActorModel } from '../models/activitypub/actor'
4 import { ApplicationModel } from '../models/application/application'
5 import { pseudoRandomBytesPromise, sha256 } from './core-utils'
6 import { logger } from './logger'
7 import { join } from 'path'
8 import { Instance as ParseTorrent } from 'parse-torrent'
9 import { remove } from 'fs-extra'
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 {
23   toFormattedJSON (args?: any)
24 }
25
26 function 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
39 async function getServerActor () {
40   if (getServerActor.serverActor === undefined) {
41     const application = await ApplicationModel.load()
42     if (!application) throw Error('Could not load Application from database.')
43
44     getServerActor.serverActor = application.Account.Actor
45   }
46
47   if (!getServerActor.serverActor) {
48     logger.error('Cannot load server actor.')
49     process.exit(0)
50   }
51
52   return Promise.resolve(getServerActor.serverActor)
53 }
54 namespace getServerActor {
55   export let serverActor: ActorModel
56 }
57
58 function generateVideoTmpPath (target: string | ParseTorrent) {
59   const id = typeof target === 'string' ? target : target.infoHash
60
61   const hash = sha256(id)
62   return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
63 }
64
65 function getSecureTorrentName (originalName: string) {
66   return sha256(originalName) + '.torrent'
67 }
68
69 // ---------------------------------------------------------------------------
70
71 export {
72   deleteFileAsync,
73   generateRandomString,
74   getFormattedObjects,
75   getSecureTorrentName,
76   getServerActor,
77   generateVideoTmpPath
78 }