]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/utils.ts
Underline links in feed popover when hovering
[github/Chocobozzz/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, unlinkPromise } from './core-utils'
6 import { logger } from './logger'
7 import { join } from 'path'
8 import { Instance as ParseTorrent } from 'parse-torrent'
9
10 function deleteFileAsync (path: string) {
11 unlinkPromise(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 pseudoRandomBytesPromise(size)
17
18 return raw.toString('hex')
19 }
20
21 interface FormattableToJSON {
22 toFormattedJSON (args?: any)
23 }
24
25 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
26 const formattedObjects: U[] = []
27
28 objects.forEach(object => {
29 formattedObjects.push(object.toFormattedJSON(formattedArg))
30 })
31
32 return {
33 total: objectsTotal,
34 data: formattedObjects
35 } as ResultList<U>
36 }
37
38 async function getServerActor () {
39 if (getServerActor.serverActor === undefined) {
40 const application = await ApplicationModel.load()
41 if (!application) throw Error('Could not load Application from database.')
42
43 getServerActor.serverActor = application.Account.Actor
44 }
45
46 if (!getServerActor.serverActor) {
47 logger.error('Cannot load server actor.')
48 process.exit(0)
49 }
50
51 return Promise.resolve(getServerActor.serverActor)
52 }
53 namespace getServerActor {
54 export let serverActor: ActorModel
55 }
56
57 function generateVideoTmpPath (target: string | ParseTorrent) {
58 const id = typeof target === 'string' ? target : target.infoHash
59
60 const hash = sha256(id)
61 return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
62 }
63
64 function getSecureTorrentName (originalName: string) {
65 return sha256(originalName) + '.torrent'
66 }
67
68 // ---------------------------------------------------------------------------
69
70 export {
71 deleteFileAsync,
72 generateRandomString,
73 getFormattedObjects,
74 getSecureTorrentName,
75 getServerActor,
76 generateVideoTmpPath
77 }