]>
Commit | Line | Data |
---|---|---|
0e1dc3e7 C |
1 | import * as WebTorrent from 'webtorrent' |
2 | import { readFile, readdir } from 'fs' | |
3 | ||
4 | let webtorrent = new WebTorrent() | |
5 | ||
26d21b78 C |
6 | function immutableAssign <T, U> (target: T, source: U) { |
7 | return Object.assign<{}, T, U>({}, target, source) | |
8 | } | |
9 | ||
0e1dc3e7 C |
10 | function readFilePromise (path: string) { |
11 | return new Promise<Buffer>((res, rej) => { | |
12 | readFile(path, (err, data) => { | |
13 | if (err) return rej(err) | |
14 | ||
15 | return res(data) | |
16 | }) | |
17 | }) | |
18 | } | |
19 | ||
20 | function readdirPromise (path: string) { | |
21 | return new Promise<string[]>((res, rej) => { | |
22 | readdir(path, (err, files) => { | |
23 | if (err) return rej(err) | |
24 | ||
25 | return res(files) | |
26 | }) | |
27 | }) | |
28 | } | |
29 | ||
b1f5b93e C |
30 | // Default interval -> 5 minutes |
31 | function dateIsValid (dateString: string, interval = 300000) { | |
0e1dc3e7 C |
32 | const dateToCheck = new Date(dateString) |
33 | const now = new Date() | |
34 | ||
35 | return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval | |
36 | } | |
37 | ||
38 | function wait (milliseconds: number) { | |
39 | return new Promise(resolve => setTimeout(resolve, milliseconds)) | |
40 | } | |
41 | ||
42 | function webtorrentAdd (torrent: string, refreshWebTorrent = false) { | |
43 | if (refreshWebTorrent === true) webtorrent = new WebTorrent() | |
44 | ||
45 | return new Promise<WebTorrent.Torrent>(res => webtorrent.add(torrent, res)) | |
46 | } | |
47 | ||
48 | // --------------------------------------------------------------------------- | |
49 | ||
50 | export { | |
51 | readFilePromise, | |
52 | readdirPromise, | |
53 | dateIsValid, | |
54 | wait, | |
26d21b78 C |
55 | webtorrentAdd, |
56 | immutableAssign | |
0e1dc3e7 | 57 | } |