1 import { ResultList } from '../../shared'
2 import { ApplicationModel } from '../models/application/application'
3 import { execPromise, execPromise2, randomBytesPromise, sha256 } from './core-utils'
4 import { logger } from './logger'
5 import { join } from 'path'
6 import { Instance as ParseTorrent } from 'parse-torrent'
7 import { remove } from 'fs-extra'
8 import * as memoizee from 'memoizee'
9 import { CONFIG } from '../initializers/config'
10 import { isVideoFileExtnameValid } from './custom-validators/videos'
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 randomBytesPromise(size)
20 return raw.toString('hex')
23 interface FormattableToJSON<U, V> {
24 toFormattedJSON (args?: U): V
27 function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
28 const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
32 data: formattedObjects
36 const getServerActor = memoizee(async function () {
37 const application = await ApplicationModel.load()
38 if (!application) throw Error('Could not load Application from database.')
40 const actor = application.Account.Actor
41 actor.Account = application.Account
46 function generateVideoImportTmpPath (target: string | ParseTorrent, extensionArg?: string) {
47 const id = typeof target === 'string'
51 let extension = '.mp4'
52 if (extensionArg && isVideoFileExtnameValid(extensionArg)) {
53 extension = extensionArg
56 const hash = sha256(id)
57 return join(CONFIG.STORAGE.TMP_DIR, `${hash}-import${extension}`)
60 function getSecureTorrentName (originalName: string) {
61 return sha256(originalName) + '.torrent'
64 async function getServerCommit () {
66 const tag = await execPromise2(
67 '[ ! -d .git ] || git name-rev --name-only --tags --no-undefined HEAD 2>/dev/null || true',
68 { stdio: [ 0, 1, 2 ] }
71 if (tag) return tag.replace(/^v/, '')
73 logger.debug('Cannot get version from git tags.', { err })
77 const version = await execPromise('[ ! -d .git ] || git rev-parse --short HEAD')
79 if (version) return version.toString().trim()
81 logger.debug('Cannot get version from git HEAD.', { err })
88 * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
89 * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
90 * not contain a UUID, returns null.
92 function getUUIDFromFilename (filename: string) {
93 const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
94 const result = filename.match(regex)
96 if (!result || Array.isArray(result) === false) return null
101 // ---------------------------------------------------------------------------
105 generateRandomString,
107 getSecureTorrentName,
110 generateVideoImportTmpPath,