aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/tests/shared/webtorrent.ts
blob: d5bd86500dd8dec3f23409a22bbe74b8659bde12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { expect } from 'chai'
import { readFile } from 'fs-extra'
import parseTorrent from 'parse-torrent'
import { basename, join } from 'path'
import * as WebTorrent from 'webtorrent'
import { VideoFile } from '@shared/models'
import { PeerTubeServer } from '@shared/server-commands'

let webtorrent: WebTorrent.Instance

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
// ---------------------------------------------------------------------------

function webtorrentAdd (torrentId: string, refreshWebTorrent = false) {
  const WebTorrent = require('webtorrent')

  if (webtorrent && refreshWebTorrent) webtorrent.destroy()
  if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent()

  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)
    })
  })
}