X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fhelpers%2Futils.ts;h=a42474417769c4aeb97f9c8b5cf0b3e8757d7afc;hb=39ba2e8e3a71961cd0087c57d25905f6a97a6b69;hp=7a32e286ca56a9c5c341dd03699bfad7a37b293f;hpb=c5911fd347c76e8bdc05ea9f3ee9efed4a58c236;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/helpers/utils.ts b/server/helpers/utils.ts index 7a32e286c..a42474417 100644 --- a/server/helpers/utils.ts +++ b/server/helpers/utils.ts @@ -1,54 +1,16 @@ -import * as express from 'express' -import * as multer from 'multer' -import { Model } from 'sequelize-typescript' import { ResultList } from '../../shared' -import { VideoResolution } from '../../shared/models/videos' -import { CONFIG, REMOTE_SCHEME, VIDEO_MIMETYPE_EXT } from '../initializers' -import { UserModel } from '../models/account/user' -import { ActorModel } from '../models/activitypub/actor' +import { CONFIG } from '../initializers' import { ApplicationModel } from '../models/application/application' -import { pseudoRandomBytesPromise } from './core-utils' +import { pseudoRandomBytesPromise, sha256 } from './core-utils' import { logger } from './logger' - -function getHostWithPort (host: string) { - const splitted = host.split(':') - - // The port was not specified - if (splitted.length === 1) { - if (REMOTE_SCHEME.HTTP === 'https') return host + ':443' - - return host + ':80' - } - - return host -} - -function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) { - return res.type('json').status(400).end() -} - -function createReqFiles (fieldName: string, storageDir: string, mimeTypes: { [ id: string ]: string }) { - const storage = multer.diskStorage({ - destination: (req, file, cb) => { - cb(null, storageDir) - }, - - filename: async (req, file, cb) => { - const extension = mimeTypes[file.mimetype] - let randomString = '' - - try { - randomString = await generateRandomString(16) - } catch (err) { - logger.error('Cannot generate random string for file name.', err) - randomString = 'fake-random-string' - } - - cb(null, randomString + extension) - } - }) - - return multer({ storage }).fields([{ name: fieldName, maxCount: 1 }]) +import { join } from 'path' +import { Instance as ParseTorrent } from 'parse-torrent' +import { remove } from 'fs-extra' +import * as memoizee from 'memoizee' + +function deleteFileAsync (path: string) { + remove(path) + .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err })) } async function generateRandomString (size: number) { @@ -58,95 +20,47 @@ async function generateRandomString (size: number) { } interface FormattableToJSON { - toFormattedJSON () + toFormattedJSON (args?: any) } -function getFormattedObjects (objects: T[], objectsTotal: number) { +function getFormattedObjects (objects: T[], objectsTotal: number, formattedArg?: any) { const formattedObjects: U[] = [] objects.forEach(object => { - formattedObjects.push(object.toFormattedJSON()) + formattedObjects.push(object.toFormattedJSON(formattedArg)) }) - const res: ResultList = { + return { total: objectsTotal, data: formattedObjects - } - - return res -} - -async function isSignupAllowed () { - if (CONFIG.SIGNUP.ENABLED === false) { - return false - } - - // No limit and signup is enabled - if (CONFIG.SIGNUP.LIMIT === -1) { - return true - } - - const totalUsers = await UserModel.countTotal() - - return totalUsers < CONFIG.SIGNUP.LIMIT + } as ResultList } -function computeResolutionsToTranscode (videoFileHeight: number) { - const resolutionsEnabled: number[] = [] - const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS +const getServerActor = memoizee(async function () { + const application = await ApplicationModel.load() + if (!application) throw Error('Could not load Application from database.') - const resolutions = [ - VideoResolution.H_240P, - VideoResolution.H_360P, - VideoResolution.H_480P, - VideoResolution.H_720P, - VideoResolution.H_1080P - ] + return application.Account.Actor +}) - for (const resolution of resolutions) { - if (configResolutions[resolution.toString()] === true && videoFileHeight > resolution) { - resolutionsEnabled.push(resolution) - } - } +function generateVideoTmpPath (target: string | ParseTorrent) { + const id = typeof target === 'string' ? target : target.infoHash - return resolutionsEnabled + const hash = sha256(id) + return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4') } -function resetSequelizeInstance (instance: Model, savedFields: object) { - Object.keys(savedFields).forEach(key => { - const value = savedFields[key] - instance.set(key, value) - }) -} - -let serverActor: ActorModel -async function getServerActor () { - if (serverActor === undefined) { - const application = await ApplicationModel.load() - serverActor = application.Account.Actor - } - - if (!serverActor) { - logger.error('Cannot load server actor.') - process.exit(0) - } - - return Promise.resolve(serverActor) +function getSecureTorrentName (originalName: string) { + return sha256(originalName) + '.torrent' } -type SortType = { sortModel: any, sortValue: string } - // --------------------------------------------------------------------------- export { - badRequest, + deleteFileAsync, generateRandomString, getFormattedObjects, - isSignupAllowed, - computeResolutionsToTranscode, - resetSequelizeInstance, + getSecureTorrentName, getServerActor, - SortType, - getHostWithPort, - createReqFiles + generateVideoTmpPath }