1 |
rakin |
51 |
import fs from 'fs'; |
2 |
|
|
import Axios, { AxiosRequestHeaders, HeadersDefaults } from 'axios'; |
3 |
|
|
|
4 |
|
|
export function timeProcess(seconds: number) { |
5 |
|
|
let interval = seconds / (60 * 60 * 24 * 30 * 365); |
6 |
|
|
|
7 |
|
|
if (interval >= 1) { |
8 |
|
|
return Math.floor(interval) + " year" + (Math.floor(interval) === 1 ? '' : 's'); |
9 |
|
|
} |
10 |
|
|
|
11 |
|
|
interval = seconds / (60 * 60 * 24 * 30); |
12 |
|
|
|
13 |
|
|
if (interval >= 1) { |
14 |
|
|
return Math.floor(interval) + " month" + (Math.floor(interval) === 1 ? '' : 's'); |
15 |
|
|
} |
16 |
|
|
|
17 |
|
|
interval = seconds / (60 * 60 * 24); |
18 |
|
|
|
19 |
|
|
if (interval >= 1) { |
20 |
|
|
return Math.floor(interval) + " day" + (Math.floor(interval) === 1 ? '' : 's'); |
21 |
|
|
} |
22 |
|
|
|
23 |
|
|
interval = seconds / (60 * 60); |
24 |
|
|
|
25 |
|
|
if (interval >= 1) { |
26 |
|
|
return Math.floor(interval) + " hour" + (Math.floor(interval) === 1 ? '' : 's'); |
27 |
|
|
} |
28 |
|
|
|
29 |
|
|
interval = seconds / 60; |
30 |
|
|
|
31 |
|
|
if (interval >= 1) { |
32 |
|
|
return Math.floor(interval) + " minute" + (Math.floor(interval) === 1 ? '' : 's'); |
33 |
|
|
} |
34 |
|
|
|
35 |
|
|
interval = seconds; |
36 |
|
|
|
37 |
|
|
return Math.floor(interval) + " second" + (Math.floor(interval) === 1 ? '' : 's'); |
38 |
|
|
} |
39 |
|
|
|
40 |
|
|
export function escapeRegex(string: string) { |
41 |
|
|
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); |
42 |
|
|
} |
43 |
|
|
|
44 |
|
|
export function timeSince(date: number) { |
45 |
|
|
const seconds = Math.floor((Date.now() - date) / 1000); |
46 |
|
|
return timeProcess(seconds) + ' ago'; |
47 |
|
|
} |
48 |
|
|
|
49 |
|
|
export async function download(url: string, path: string, headers?: AxiosRequestHeaders) { |
50 |
|
|
const writer = fs.createWriteStream(path); |
51 |
|
|
|
52 |
|
|
const response = await Axios({ |
53 |
|
|
url, |
54 |
|
|
method: 'GET', |
55 |
|
|
responseType: 'stream', |
56 |
|
|
headers |
57 |
|
|
}); |
58 |
|
|
|
59 |
|
|
response.data.pipe(writer); |
60 |
|
|
|
61 |
|
|
return new Promise((resolve, reject) => { |
62 |
|
|
if (response.status !== 200) { |
63 |
|
|
reject(); |
64 |
|
|
} |
65 |
|
|
|
66 |
|
|
writer.on('finish', resolve); |
67 |
|
|
writer.on('error', reject); |
68 |
|
|
}); |
69 |
|
|
} |
70 |
|
|
|
71 |
|
|
export async function deleteFile(path: string) { |
72 |
|
|
fs.rm(path, (err: any) => { |
73 |
|
|
if (err) { |
74 |
|
|
throw new Error(err); |
75 |
|
|
} |
76 |
|
|
}); |
77 |
|
|
} |
78 |
|
|
|
79 |
|
|
export function random(arr: Array <any>) { |
80 |
|
|
let index = Math.floor(Math.random() * arr.length); |
81 |
|
|
return arr[index]; |
82 |
|
|
} |