diff options
author | Chocobozzz <me@florianbigard.com> | 2021-12-17 09:29:23 +0100 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2021-12-17 09:29:23 +0100 |
commit | bf54587a3e2ad9c2c186828f2a5682b91ee2cc00 (patch) | |
tree | 54b40aaf01bae210632473285c3c7571d51e4f89 /shared/server-commands/miscs/webtorrent.ts | |
parent | 6b5f72beda96d8b7e4d6329c4001827334de27dd (diff) | |
download | PeerTube-bf54587a3e2ad9c2c186828f2a5682b91ee2cc00.tar.gz PeerTube-bf54587a3e2ad9c2c186828f2a5682b91ee2cc00.tar.zst PeerTube-bf54587a3e2ad9c2c186828f2a5682b91ee2cc00.zip |
shared/ typescript types dir server-commands
Diffstat (limited to 'shared/server-commands/miscs/webtorrent.ts')
-rw-r--r-- | shared/server-commands/miscs/webtorrent.ts | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/shared/server-commands/miscs/webtorrent.ts b/shared/server-commands/miscs/webtorrent.ts new file mode 100644 index 000000000..0683f8893 --- /dev/null +++ b/shared/server-commands/miscs/webtorrent.ts | |||
@@ -0,0 +1,46 @@ | |||
1 | import { readFile } from 'fs-extra' | ||
2 | import parseTorrent from 'parse-torrent' | ||
3 | import { basename, join } from 'path' | ||
4 | import * as WebTorrent from 'webtorrent' | ||
5 | import { VideoFile } from '@shared/models' | ||
6 | import { PeerTubeServer } from '../server' | ||
7 | |||
8 | let webtorrent: WebTorrent.Instance | ||
9 | |||
10 | function webtorrentAdd (torrentId: string, refreshWebTorrent = false) { | ||
11 | const WebTorrent = require('webtorrent') | ||
12 | |||
13 | if (webtorrent && refreshWebTorrent) webtorrent.destroy() | ||
14 | if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent() | ||
15 | |||
16 | webtorrent.on('error', err => console.error('Error in webtorrent', err)) | ||
17 | |||
18 | return new Promise<WebTorrent.Torrent>(res => { | ||
19 | const torrent = webtorrent.add(torrentId, res) | ||
20 | |||
21 | torrent.on('error', err => console.error('Error in webtorrent torrent', err)) | ||
22 | torrent.on('warning', warn => { | ||
23 | const msg = typeof warn === 'string' | ||
24 | ? warn | ||
25 | : warn.message | ||
26 | |||
27 | if (msg.includes('Unsupported')) return | ||
28 | |||
29 | console.error('Warning in webtorrent torrent', warn) | ||
30 | }) | ||
31 | }) | ||
32 | } | ||
33 | |||
34 | async function parseTorrentVideo (server: PeerTubeServer, file: VideoFile) { | ||
35 | const torrentName = basename(file.torrentUrl) | ||
36 | const torrentPath = server.servers.buildDirectory(join('torrents', torrentName)) | ||
37 | |||
38 | const data = await readFile(torrentPath) | ||
39 | |||
40 | return parseTorrent(data) | ||
41 | } | ||
42 | |||
43 | export { | ||
44 | webtorrentAdd, | ||
45 | parseTorrentVideo | ||
46 | } | ||