PeerTube/server/tests/shared/webtorrent.ts

59 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-04-21 15:00:01 +02:00
import { expect } from 'chai'
2021-07-15 10:02:54 +02:00
import { readFile } from 'fs-extra'
2021-08-27 14:32:44 +02:00
import parseTorrent from 'parse-torrent'
2021-07-23 11:20:00 +02:00
import { basename, join } from 'path'
2021-07-13 09:43:59 +02:00
import * as WebTorrent from 'webtorrent'
2021-07-23 11:20:00 +02:00
import { VideoFile } from '@shared/models'
2023-04-21 15:00:01 +02:00
import { PeerTubeServer } from '@shared/server-commands'
2021-07-13 09:43:59 +02:00
let webtorrent: WebTorrent.Instance
2023-04-21 15:00:01 +02:00
export async function checkWebTorrentWorks (magnetUri: string, pathMatch?: RegExp) {
const torrent = await webtorrentAdd(magnetUri, true)
expect(torrent.files).to.be.an('array')
expect(torrent.files.length).to.equal(1)
expect(torrent.files[0].path).to.exist.and.to.not.equal('')
if (pathMatch) {
expect(torrent.files[0].path).match(pathMatch)
}
}
export async function parseTorrentVideo (server: PeerTubeServer, file: VideoFile) {
const torrentName = basename(file.torrentUrl)
const torrentPath = server.servers.buildDirectory(join('torrents', torrentName))
const data = await readFile(torrentPath)
return parseTorrent(data)
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
2021-09-02 09:53:27 +02:00
function webtorrentAdd (torrentId: string, refreshWebTorrent = false) {
2021-07-13 09:43:59 +02:00
const WebTorrent = require('webtorrent')
2021-11-24 09:19:02 +01:00
if (webtorrent && refreshWebTorrent) webtorrent.destroy()
if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent()
2021-07-13 09:43:59 +02:00
2021-09-02 09:53:27 +02:00
webtorrent.on('error', err => console.error('Error in webtorrent', err))
return new Promise<WebTorrent.Torrent>(res => {
const torrent = webtorrent.add(torrentId, res)
torrent.on('error', err => console.error('Error in webtorrent torrent', err))
torrent.on('warning', warn => {
const msg = typeof warn === 'string'
? warn
: warn.message
if (msg.includes('Unsupported')) return
console.error('Warning in webtorrent torrent', warn)
})
})
2021-07-13 09:43:59 +02:00
}