]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/tests/shared/webtorrent.ts
Add runner server tests
[github/Chocobozzz/PeerTube.git] / server / tests / shared / webtorrent.ts
CommitLineData
d102de1b 1import { expect } from 'chai'
d23dd9fb 2import { readFile } from 'fs-extra'
41fb13c3 3import parseTorrent from 'parse-torrent'
764b1a14 4import { basename, join } from 'path'
6c5065a0 5import * as WebTorrent from 'webtorrent'
764b1a14 6import { VideoFile } from '@shared/models'
d102de1b 7import { PeerTubeServer } from '@shared/server-commands'
6c5065a0
C
8
9let webtorrent: WebTorrent.Instance
10
d102de1b
C
11export 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
23export 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 36function 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}