]>
Commit | Line | Data |
---|---|---|
d102de1b | 1 | import { expect } from 'chai' |
d23dd9fb | 2 | import { readFile } from 'fs-extra' |
41fb13c3 | 3 | import parseTorrent from 'parse-torrent' |
764b1a14 | 4 | import { basename, join } from 'path' |
6c5065a0 | 5 | import * as WebTorrent from 'webtorrent' |
764b1a14 | 6 | import { VideoFile } from '@shared/models' |
d102de1b | 7 | import { PeerTubeServer } from '@shared/server-commands' |
6c5065a0 C |
8 | |
9 | let webtorrent: WebTorrent.Instance | |
10 | ||
d102de1b C |
11 | export async function checkWebTorrentWorks (magnetUri: string, pathMatch?: RegExp) { |
12 | const torrent = await webtorrentAdd(magnetUri, true) | |
13 | ||
14 | expect(torrent.files).to.be.an('array') | |
15 | expect(torrent.files.length).to.equal(1) | |
16 | expect(torrent.files[0].path).to.exist.and.to.not.equal('') | |
17 | ||
18 | if (pathMatch) { | |
19 | expect(torrent.files[0].path).match(pathMatch) | |
20 | } | |
21 | } | |
22 | ||
23 | export async function parseTorrentVideo (server: PeerTubeServer, file: VideoFile) { | |
24 | const torrentName = basename(file.torrentUrl) | |
25 | const torrentPath = server.servers.buildDirectory(join('torrents', torrentName)) | |
26 | ||
27 | const data = await readFile(torrentPath) | |
28 | ||
29 | return parseTorrent(data) | |
30 | } | |
31 | ||
32 | // --------------------------------------------------------------------------- | |
33 | // Private | |
34 | // --------------------------------------------------------------------------- | |
35 | ||
fbcd44d2 | 36 | function webtorrentAdd (torrentId: string, refreshWebTorrent = false) { |
6c5065a0 C |
37 | const WebTorrent = require('webtorrent') |
38 | ||
17e2705f C |
39 | if (webtorrent && refreshWebTorrent) webtorrent.destroy() |
40 | if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent() | |
6c5065a0 | 41 | |
fbcd44d2 C |
42 | webtorrent.on('error', err => console.error('Error in webtorrent', err)) |
43 | ||
44 | return new Promise<WebTorrent.Torrent>(res => { | |
45 | const torrent = webtorrent.add(torrentId, res) | |
46 | ||
47 | torrent.on('error', err => console.error('Error in webtorrent torrent', err)) | |
48 | torrent.on('warning', warn => { | |
49 | const msg = typeof warn === 'string' | |
50 | ? warn | |
51 | : warn.message | |
52 | ||
53 | if (msg.includes('Unsupported')) return | |
54 | ||
55 | console.error('Warning in webtorrent torrent', warn) | |
56 | }) | |
57 | }) | |
6c5065a0 | 58 | } |