1 import { ResultList } from '../../shared'
2 import { CONFIG } from '../initializers'
3 import { ApplicationModel } from '../models/application/application'
4 import { execPromise, execPromise2, pseudoRandomBytesPromise, sha256 } from './core-utils'
5 import { logger } from './logger'
6 import { join } from 'path'
7 import { Instance as ParseTorrent } from 'parse-torrent'
8 import { remove } from 'fs-extra'
9 import * as memoizee from 'memoizee'
11 function deleteFileAsync (path: string) {
13 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
16 async function generateRandomString (size: number) {
17 const raw = await pseudoRandomBytesPromise(size)
19 return raw.toString('hex')
22 interface FormattableToJSON {
23 toFormattedJSON (args?: any)
26 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
27 const formattedObjects: U[] = []
29 objects.forEach(object => {
30 formattedObjects.push(object.toFormattedJSON(formattedArg))
35 data: formattedObjects
39 const getServerActor = memoizee(async function () {
40 const application = await ApplicationModel.load()
41 if (!application) throw Error('Could not load Application from database.')
43 const actor = application.Account.Actor
44 actor.Account = application.Account
49 function generateVideoTmpPath (target: string | ParseTorrent) {
50 const id = typeof target === 'string' ? target : target.infoHash
52 const hash = sha256(id)
53 return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
56 function getSecureTorrentName (originalName: string) {
57 return sha256(originalName) + '.torrent'
60 async function getServerCommit () {
62 const tag = await execPromise2(
63 '[ ! -d .git ] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true',
64 { stdio: [ 0, 1, 2 ] }
67 if (tag) return tag.replace(/^v/, '')
69 logger.debug('Cannot get version from git tags.', { err })
73 const version = await execPromise('[ ! -d .git ] || git rev-parse --short HEAD')
75 if (version) return version.toString().trim()
77 logger.debug('Cannot get version from git HEAD.', { err })
84 * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
85 * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
86 * not contain a UUID, returns null.
88 function getUUIDFromFilename (filename: string) {
89 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
90 const result = filename.match(regex)
92 if (!result || Array.isArray(result) === false) return null
97 // ---------------------------------------------------------------------------
101 generateRandomString,
103 getSecureTorrentName,
106 generateVideoTmpPath,