]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tests/shared/webtorrent.ts
Add runner server tests
[github/Chocobozzz/PeerTube.git] / server / tests / shared / webtorrent.ts
1 import { expect } from 'chai'
2 import { readFile } from 'fs-extra'
3 import parseTorrent from 'parse-torrent'
4 import { basename, join } from 'path'
5 import * as WebTorrent from 'webtorrent'
6 import { VideoFile } from '@shared/models'
7 import { PeerTubeServer } from '@shared/server-commands'
8
9 let webtorrent: WebTorrent.Instance
10
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
36 function webtorrentAdd (torrentId: string, refreshWebTorrent = false) {
37 const WebTorrent = require('webtorrent')
38
39 if (webtorrent && refreshWebTorrent) webtorrent.destroy()
40 if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent()
41
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 })
58 }