]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/utils.ts
Fix user create daily quota component
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
CommitLineData
6fcd19ba 1import { ResultList } from '../../shared'
0626e7af 2import { CONFIG } from '../initializers'
50d6de9c
C
3import { ActorModel } from '../models/activitypub/actor'
4import { ApplicationModel } from '../models/application/application'
62689b94 5import { pseudoRandomBytesPromise, sha256 } from './core-utils'
efc32059 6import { logger } from './logger'
3e17515e 7import { join } from 'path'
990b6a0b 8import { Instance as ParseTorrent } from 'parse-torrent'
62689b94 9import { remove } from 'fs-extra'
cbe2f7c3 10
cf7a61b5 11function deleteFileAsync (path: string) {
62689b94 12 remove(path)
cf7a61b5
C
13 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
14}
15
f5028693
C
16async function generateRandomString (size: number) {
17 const raw = await pseudoRandomBytesPromise(size)
18
19 return raw.toString('hex')
e4c87ec2
C
20}
21
40298b02 22interface FormattableToJSON {
2186386c 23 toFormattedJSON (args?: any)
154898b0
C
24}
25
2186386c 26function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
0aef76c4 27 const formattedObjects: U[] = []
55fa55a9 28
075f16ca 29 objects.forEach(object => {
2186386c 30 formattedObjects.push(object.toFormattedJSON(formattedArg))
55fa55a9
C
31 })
32
2186386c 33 return {
55fa55a9 34 total: objectsTotal,
0aef76c4 35 data: formattedObjects
2186386c 36 } as ResultList<U>
55fa55a9
C
37}
38
50d6de9c 39async function getServerActor () {
06215f15 40 if (getServerActor.serverActor === undefined) {
50d6de9c 41 const application = await ApplicationModel.load()
2cebd797
C
42 if (!application) throw Error('Could not load Application from database.')
43
06215f15 44 getServerActor.serverActor = application.Account.Actor
7a7724e6
C
45 }
46
06215f15 47 if (!getServerActor.serverActor) {
50d6de9c 48 logger.error('Cannot load server actor.')
efc32059
C
49 process.exit(0)
50 }
51
06215f15
C
52 return Promise.resolve(getServerActor.serverActor)
53}
54namespace getServerActor {
55 export let serverActor: ActorModel
7a7724e6
C
56}
57
990b6a0b
C
58function generateVideoTmpPath (target: string | ParseTorrent) {
59 const id = typeof target === 'string' ? target : target.infoHash
60
61 const hash = sha256(id)
ce33919c
C
62 return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
63}
64
990b6a0b
C
65function getSecureTorrentName (originalName: string) {
66 return sha256(originalName) + '.torrent'
67}
792dbaf0 68
9f10b292 69// ---------------------------------------------------------------------------
c45f7f84 70
65fcc311 71export {
cf7a61b5 72 deleteFileAsync,
65fcc311 73 generateRandomString,
0aef76c4 74 getFormattedObjects,
990b6a0b 75 getSecureTorrentName,
50d6de9c 76 getServerActor,
ce33919c 77 generateVideoTmpPath
65fcc311 78}