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'
10 import { isArray } from './custom-validators/misc'
12 function deleteFileAsync (path: string) {
14 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
17 async function generateRandomString (size: number) {
18 const raw = await pseudoRandomBytesPromise(size)
20 return raw.toString('hex')
23 interface FormattableToJSON { toFormattedJSON (args?: any) }
24 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
25 const formattedObjects: U[] = []
27 objects.forEach(object => {
28 formattedObjects.push(object.toFormattedJSON(formattedArg))
33 data: formattedObjects
37 const getServerActor = memoizee(async function () {
38 const application = await ApplicationModel.load()
39 if (!application) throw Error('Could not load Application from database.')
41 const actor = application.Account.Actor
42 actor.Account = application.Account
47 function generateVideoImportTmpPath (target: string | ParseTorrent) {
48 const id = typeof target === 'string' ? target : target.infoHash
50 const hash = sha256(id)
51 return join(CONFIG.STORAGE.TMP_DIR, hash + '-import.mp4')
54 function getSecureTorrentName (originalName: string) {
55 return sha256(originalName) + '.torrent'
58 async function getServerCommit () {
60 const tag = await execPromise2(
61 '[ ! -d .git ] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true',
62 { stdio: [ 0, 1, 2 ] }
65 if (tag) return tag.replace(/^v/, '')
67 logger.debug('Cannot get version from git tags.', { err })
71 const version = await execPromise('[ ! -d .git ] || git rev-parse --short HEAD')
73 if (version) return version.toString().trim()
75 logger.debug('Cannot get version from git HEAD.', { err })
82 * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
83 * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
84 * not contain a UUID, returns null.
86 function getUUIDFromFilename (filename: string) {
87 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
88 const result = filename.match(regex)
90 if (!result || Array.isArray(result) === false) return null
95 // ---------------------------------------------------------------------------
101 getSecureTorrentName,
104 generateVideoImportTmpPath,