You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var fs = require("fs");
  2. var http = require("http");
  3. var https = require("https");
  4. var pathlib = require("path");
  5. var urllib = require("url");
  6. var fsutil = require("../fsutil");
  7. var player = require("./player");
  8. var httpStream = require("./http-stream");
  9. var torrentStreamer = require("./torrent-streamer");
  10. exports.httpPath = "/playback";
  11. exports.cleanupFiles = [];
  12. var app;
  13. var conf
  14. exports.init = function(_app, _conf) {
  15. app = _app;
  16. conf = _conf;
  17. player.init(app, conf);
  18. httpStream.init(app, conf);
  19. torrentStreamer.init(app, conf);
  20. }
  21. exports.playTorrent = function(magnet, cb) {
  22. // Stream torrent
  23. torrentStreamer.stream(magnet, (err, filesize, filename) => {
  24. if (err)
  25. return cb(err);
  26. cb();
  27. });
  28. }
  29. exports.playTorrentPage = function(url, cb) {
  30. function findMagnet(str) {
  31. var rx = /['"](magnet:[^'"]+)['"]/;
  32. var match = str.match(rx);
  33. if (!match)
  34. return null;
  35. return match[1];
  36. }
  37. var urlobj = urllib.parse(url);
  38. var o = urlobj.protocol === "https:" ? https : http;
  39. o.request(urlobj, res => {
  40. var str = "";
  41. res
  42. .on("data", d => str += d )
  43. .on("error", err => {
  44. console.trace(err);
  45. cb();
  46. })
  47. .on("end", () => {
  48. var magnet = findMagnet(str);
  49. if (!magnet) {
  50. cb("No magnet link on page!");
  51. return;
  52. }
  53. exports.playTorrent(magnet, cb);
  54. });
  55. }).end();
  56. }
  57. exports.isPlaying = player.isPlaying;
  58. player.onstop = function() {
  59. torrentStreamer.stop();
  60. httpStream.stop();
  61. exports.cleanupFiles.forEach(f => {
  62. try {
  63. fs.unlink(f, err => { if (err) console.trace(err) });
  64. } catch (err) {
  65. console.log(err.toString());
  66. }
  67. });
  68. exports.cleanupFiles = [];
  69. fsutil.rmdir(conf.tmpdir+"/torrent-stream");
  70. }