1 import { Model } from 'sequelize-typescript'
2 import * as ipaddr from 'ipaddr.js'
3 import { ResultList } from '../../shared'
4 import { VideoResolution } from '../../shared/models/videos'
5 import { CONFIG } from '../initializers'
6 import { UserModel } from '../models/account/user'
7 import { ActorModel } from '../models/activitypub/actor'
8 import { ApplicationModel } from '../models/application/application'
9 import { pseudoRandomBytesPromise, unlinkPromise } from './core-utils'
10 import { logger } from './logger'
11 import { isArray } from './custom-validators/misc'
12 import * as crypto from "crypto"
13 import { join } from "path"
15 const isCidr = require('is-cidr')
17 function cleanUpReqFiles (req: { files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[] }) {
18 const files = req.files
23 (files as Express.Multer.File[]).forEach(f => deleteFileAsync(f.path))
27 for (const key of Object.keys(files)) {
28 const file = files[key]
30 if (isArray(file)) file.forEach(f => deleteFileAsync(f.path))
31 else deleteFileAsync(file.path)
35 function deleteFileAsync (path: string) {
37 .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
40 async function generateRandomString (size: number) {
41 const raw = await pseudoRandomBytesPromise(size)
43 return raw.toString('hex')
46 interface FormattableToJSON {
47 toFormattedJSON (args?: any)
50 function getFormattedObjects<U, T extends FormattableToJSON> (objects: T[], objectsTotal: number, formattedArg?: any) {
51 const formattedObjects: U[] = []
53 objects.forEach(object => {
54 formattedObjects.push(object.toFormattedJSON(formattedArg))
59 data: formattedObjects
63 async function isSignupAllowed () {
64 if (CONFIG.SIGNUP.ENABLED === false) {
68 // No limit and signup is enabled
69 if (CONFIG.SIGNUP.LIMIT === -1) {
73 const totalUsers = await UserModel.countTotal()
75 return totalUsers < CONFIG.SIGNUP.LIMIT
78 function isSignupAllowedForCurrentIP (ip: string) {
79 const addr = ipaddr.parse(ip)
80 let excludeList = [ 'blacklist' ]
83 // if there is a valid, non-empty whitelist, we exclude all unknown adresses too
84 if (CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr(cidr)).length > 0) {
85 excludeList.push('unknown')
88 if (addr.kind() === 'ipv4') {
89 const addrV4 = ipaddr.IPv4.parse(ip)
91 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v4(cidr))
92 .map(cidr => ipaddr.IPv4.parseCIDR(cidr)),
93 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v4(cidr))
94 .map(cidr => ipaddr.IPv4.parseCIDR(cidr))
96 matched = ipaddr.subnetMatch(addrV4, rangeList, 'unknown')
97 } else if (addr.kind() === 'ipv6') {
98 const addrV6 = ipaddr.IPv6.parse(ip)
100 whitelist: CONFIG.SIGNUP.FILTERS.CIDR.WHITELIST.filter(cidr => isCidr.v6(cidr))
101 .map(cidr => ipaddr.IPv6.parseCIDR(cidr)),
102 blacklist: CONFIG.SIGNUP.FILTERS.CIDR.BLACKLIST.filter(cidr => isCidr.v6(cidr))
103 .map(cidr => ipaddr.IPv6.parseCIDR(cidr))
105 matched = ipaddr.subnetMatch(addrV6, rangeList, 'unknown')
108 return !excludeList.includes(matched)
111 function computeResolutionsToTranscode (videoFileHeight: number) {
112 const resolutionsEnabled: number[] = []
113 const configResolutions = CONFIG.TRANSCODING.RESOLUTIONS
115 // Put in the order we want to proceed jobs
116 const resolutions = [
117 VideoResolution.H_480P,
118 VideoResolution.H_360P,
119 VideoResolution.H_720P,
120 VideoResolution.H_240P,
121 VideoResolution.H_1080P
124 for (const resolution of resolutions) {
125 if (configResolutions[ resolution + 'p' ] === true && videoFileHeight > resolution) {
126 resolutionsEnabled.push(resolution)
130 return resolutionsEnabled
139 week: 3600000 * 24 * 7,
140 month: 3600000 * 24 * 30
142 export function parseDuration (duration: number | string): number {
143 if (typeof duration === 'number') return duration
145 if (typeof duration === 'string') {
146 const split = duration.match(/^([\d\.,]+)\s?(\w+)$/)
148 if (split.length === 3) {
149 const len = parseFloat(split[1])
150 let unit = split[2].replace(/s$/i,'').toLowerCase()
155 return (len || 1) * (timeTable[unit] || 0)
159 throw new Error('Duration could not be properly parsed')
162 function resetSequelizeInstance (instance: Model<any>, savedFields: object) {
163 Object.keys(savedFields).forEach(key => {
164 const value = savedFields[key]
165 instance.set(key, value)
169 let serverActor: ActorModel
170 async function getServerActor () {
171 if (serverActor === undefined) {
172 const application = await ApplicationModel.load()
173 if (!application) throw Error('Could not load Application from database.')
175 serverActor = application.Account.Actor
179 logger.error('Cannot load server actor.')
183 return Promise.resolve(serverActor)
186 function generateVideoTmpPath (id: string) {
187 const hash = crypto.createHash('sha256').update(id).digest('hex')
188 return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
191 type SortType = { sortModel: any, sortValue: string }
194 // ---------------------------------------------------------------------------
199 generateRandomString,
202 isSignupAllowedForCurrentIP,
203 computeResolutionsToTranscode,
204 resetSequelizeInstance,