1
0
Fork 0
peertube/shared/server-commands/miscs/webtorrent.ts

47 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-07-15 04:02:54 -04:00
import { readFile } from 'fs-extra'
2021-08-27 08:32:44 -04:00
import parseTorrent from 'parse-torrent'
2021-07-23 05:20:00 -04:00
import { basename, join } from 'path'
2021-07-13 03:43:59 -04:00
import * as WebTorrent from 'webtorrent'
2021-07-23 05:20:00 -04:00
import { VideoFile } from '@shared/models'
2021-07-16 03:47:51 -04:00
import { PeerTubeServer } from '../server'
2021-07-13 03:43:59 -04:00
let webtorrent: WebTorrent.Instance
2021-09-02 03:53:27 -04:00
function webtorrentAdd (torrentId: string, refreshWebTorrent = false) {
2021-07-13 03:43:59 -04:00
const WebTorrent = require('webtorrent')
2021-11-24 03:19:02 -05:00
if (webtorrent && refreshWebTorrent) webtorrent.destroy()
if (!webtorrent || refreshWebTorrent) webtorrent = new WebTorrent()
2021-07-13 03:43:59 -04:00
2021-09-02 03:53:27 -04: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 03:43:59 -04:00
}
2021-07-23 05:20:00 -04:00
async function parseTorrentVideo (server: PeerTubeServer, file: VideoFile) {
const torrentName = basename(file.torrentUrl)
2021-07-16 03:04:35 -04:00
const torrentPath = server.servers.buildDirectory(join('torrents', torrentName))
2021-07-15 04:02:54 -04:00
const data = await readFile(torrentPath)
return parseTorrent(data)
}
2021-07-13 03:43:59 -04:00
export {
2021-07-15 04:02:54 -04:00
webtorrentAdd,
parseTorrentVideo
2021-07-13 03:43:59 -04:00
}