Example #1
0
function runInfo (torrentId) {
  var parsedTorrent
  try {
    parsedTorrent = parseTorrent(torrentId)
  } catch (err) {
    // If torrent fails to parse, it could be a filesystem path, so don't consider it
    // an error yet.
  }

  if (!parsedTorrent || !parsedTorrent.infoHash) {
    try {
      parsedTorrent = parseTorrent(fs.readFileSync(torrentId))
    } catch (err) {
      return errorAndExit(err)
    }
  }

  delete parsedTorrent.info
  delete parsedTorrent.infoBuffer
  delete parsedTorrent.infoHashBuffer

  var output = JSON.stringify(parsedTorrent, undefined, 2)
  if (argv.out) {
    fs.writeFileSync(argv.out, output)
  } else {
    process.stdout.write(output)
  }
}
Example #2
0
// Makes sure two torrents have the same infohash and flags
function compareTorrentFiles (t, pathActual, pathExpected) {
  const bufActual = fs.readFileSync(pathActual)
  const bufExpected = fs.readFileSync(pathExpected)
  const fieldsActual = extractImportantFields(parseTorrent(bufActual))
  const fieldsExpected = extractImportantFields(parseTorrent(bufExpected))
  t.deepEqual(fieldsActual, fieldsExpected, 'torrent contents: ' + pathActual)
}
Example #3
0
Torrent.prototype._onMetadata = function (metadata) {
  var self = this

  self.metadata = metadata

  try {
    var info = bncode.decode(metadata)
    self.torrentFile = bncode.encode({
      'announce-list': [],
      infoHash: self.infoHash,
      info: info
    })
    self.parsedTorrent = parseTorrent(self.torrentFile)
  } catch (e) {
    console.error(e)
    return
  }

  self.name = self.parsedTorrent.name
  self.infoHash = self.parsedTorrent.infoHash

  self.storage = new Storage(self.parsedTorrent)
  self.storage.on('piece', self._onStoragePiece.bind(self))
  self.storage.on('file', function (file) {
    console.log('FILE', file.name)
  })
  self.storage.on('done', function () {
    console.log('done with torrent!')
  })

  self.swarm.wires.forEach(function (wire) {
    self._onWireWithMetadata(wire)
  })
}
Example #4
0
  }, function (err, torrent) {
    t.error(err)

    var parsedTorrent = parseTorrent(torrent)

    t.equals(parsedTorrent.name, 'multi')

    t.notOk(parsedTorrent.private)

    var createdTime = parsedTorrent.created / 1000
    t.ok(createdTime >= startTime, 'created time is after start time')
    t.ok(createdTime <= Date.now(), 'created time is before now')

    t.ok(Array.isArray(parsedTorrent.announce))

    t.deepEquals(path.normalize(parsedTorrent.files[0].path), path.normalize('multi/dir1/buf1.txt'))
    t.deepEquals(parsedTorrent.files[0].length, 2)

    t.deepEquals(path.normalize(parsedTorrent.files[1].path), path.normalize('multi/dir2/buf2.txt'))
    t.deepEquals(parsedTorrent.files[1].length, 2)

    t.equal(parsedTorrent.length, 4)
    t.equal(parsedTorrent.info.pieces.length, 20)
    t.equal(parsedTorrent.pieceLength, 16384)

    t.deepEquals(parsedTorrent.pieces, [
      '5bf1fd927dfb8679496a2e6cf00cbe50c1c87145'
    ])
    t.equals(sha1.sync(parsedTorrent.infoBuffer), '8fa3c08e640db9576156b21f31353402456a0208')
  })
Example #5
0
seeder.on('seed', function (link) {
  console.log('SEED', link)
  var t = parseTorrent(link)
  var tdir = path.join(dir, t.infoHash)
  fs.readdir(tdir, function (err, files) {
    if (!files) client.add(link, onadd)
    else {
      var tfiles = files.map(function (f) { return path.join(tdir, f) })
      client.seed(tfiles, onseed)
    }
  })
  function onadd (s) {
    var tdir = path.join(dir, t.infoHash)
    mkdirp(tdir, function () {
      t.files.forEach(function (file) {
        file.createReadStream()
          .pipe(fs.createWriteStream(path.join(tdir, t.infoHash)))
      })
    })
  }
  function onseed (s) {
    if (s.infoHash !== t.infoHash) {
      client.remove(s)
      client.add(link, onadd)
    }
  }
})
Example #6
0
          fs.writeFile(filePath, torrent, function (err) {
            if (err) return callback(err)

            const parsedTorrent = parseTorrent(torrent)
            video.set('infoHash', parsedTorrent.infoHash)
            video.validate().asCallback(callback)
          })
Example #7
0
		fileArray.forEach(function(el) {
			if (utils.parser(el).extension() == 'torrent') {
				var parseTorrent = require('parse-torrent');
				var data = parseTorrent(require('fs').readFileSync(el));
				var trackers = '';
				
				if (data) {
					
					if (data.name)
						trackers += '&dn=' + data.name.toLowerCase().split(' ').join('+');
				
					if (data.announce && data.announce.length)
						for (ldf = 0; data.announce[ldf]; ldf++)
							trackers += '&tr=' + encodeURIComponent(data.announce[ldf]);

				}
				
				var set = {
					url: "pow://" + data.infoHash + trackers,
					title: utils.parser(data.name).name()
				};
				torrent.files[data.infoHash] = el;
				set = load.pushArgs(set);
				player.addPlaylist(set);
			} else {
				ranURL = true;
				load.url(el);
			}
		});
Example #8
0
  function onTorrentId (torrentId) {
    parsedTorrent = parseTorrent(torrentId)
    self.infoHash = parsedTorrent.infoHash
    if (parsedTorrent.name) self.name = parsedTorrent.name // preliminary name

    // create swarm
    self.swarm = new Swarm(self.infoHash, self.client.peerId, {
      handshake: { dht: !!self.client.dht }
    })
    reemit(self.swarm, self, ['warning', 'error'])
    self.swarm.on('wire', self._onWire.bind(self))

    // update overall client stats
    self.swarm.on('download', self.client.downloadSpeed.bind(self.client))
    self.swarm.on('upload', self.client.uploadSpeed.bind(self.client))

    if (process.browser) {
      // in browser, swarm does not listen
      self._onSwarmListening(parsedTorrent)
    } else {
      // listen for peers
      self.swarm.listen(self.client.torrentPort, self._onSwarmListening.bind(self, parsedTorrent))
    }
    process.nextTick(function () {
      self.emit('infoHash')
    })
  }
Example #9
0
  }, function (err, torrent) {
    t.error(err)

    var parsedTorrent = parseTorrent(torrent)

    t.equals(parsedTorrent.name, 'numbers')

    t.notOk(parsedTorrent.private)

    t.ok(parsedTorrent.created.getTime() >= startTime, 'created time is after start time')

    t.ok(Array.isArray(parsedTorrent.announce))

    t.deepEquals(path.normalize(parsedTorrent.files[0].path), path.normalize('numbers/1.txt'))
    t.deepEquals(parsedTorrent.files[0].length, 1)

    t.deepEquals(path.normalize(parsedTorrent.files[1].path), path.normalize('numbers/2.txt'))
    t.deepEquals(parsedTorrent.files[1].length, 2)

    t.deepEquals(path.normalize(parsedTorrent.files[2].path), path.normalize('numbers/3.txt'))
    t.deepEquals(parsedTorrent.files[2].length, 3)

    t.equal(parsedTorrent.length, 6)
    t.equal(parsedTorrent.info.pieces.length, 20)
    t.equal(parsedTorrent.pieceLength, 32768)

    t.deepEquals(parsedTorrent.pieces, [
      '1f74648e50a6a6708ec54ab327a163d5536b7ced'
    ])
    t.equals(sha1.sync(parsedTorrent.infoBuffer), '80562f38656b385ea78959010e51a2cc9db41ea0')
  })
Example #10
0
  network.json(EZTV_URL + '/show/' + showInfo.imdb_id, null, null, function(err, data) {
    if (err) {
      callback(null, magnets);
    } else {
      if (data && 'episodes' in data) {
        for (var i = 0; i < data.episodes.length; i++) {
          if (data.episodes[i].season == seasonIndex && data.episodes[i].episode == episodeIndex) {
            for (var key in data.episodes[i].torrents) {
              var magnetLink       = data.episodes[i].torrents[key].url;
              var parsedMagnetLink = parseTorrent(magnetLink);

              if (!magnets.find(function(element, index, array) { return parseTorrent(element.link).infoHash == parsedMagnetLink.infoHash; })) {
                magnets.push({
                  title:  parsedMagnetLink.dn,
                  source: 'EZTV',
                  link:   magnetLink,
                  size:   0,
                  seeds:  -1,
                  peers:  -1
                });
              }
            }
            callback(null, magnets);
            return;
          }
        }
      }
      callback(null, magnets);
    }
  });
Example #11
0
		fs.readFile(torrentPath, function(_, buf) {
			swarm.resume();
			if (!buf) return;
			var torrent = parseTorrent(buf);
			metadata = encode(torrent);
			if (metadata) ontorrent(torrent);
		});
Example #12
0
    function onResponse (err, res, torrent) {
      if (self.destroyed) return cb(null)
      if (self.metadata) return cb(null)

      if (err) {
        self._debug('http error from xs param: %s', url)
        return cb(null)
      }
      if (res.statusCode !== 200) {
        self._debug('non-200 status code %s from xs param: %s', res.statusCode, url)
        return cb(null)
      }

      var parsedTorrent
      try {
        parsedTorrent = parseTorrent(torrent)
      } catch (err) {}

      if (!parsedTorrent) {
        self._debug('got invalid torrent file from xs param: %s', url)
        return cb(null)
      }

      if (parsedTorrent.infoHash !== self.infoHash) {
        self._debug('got torrent file with incorrect info hash from xs param: %s', url)
        return cb(null)
      }

      self._onMetadata(parsedTorrent)
      cb(null)
    }
Example #13
0
function scrape(magnetLink, callback) {
  try {
    var client = new bittorrentTracker(new Buffer('01234567890123456789'), 6881, parseTorrent(magnetLink));

    // client.on('error', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    // client.on('warning', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    client.on('scrape', function(data) {
      client.destroy();
      callback(null, { seeds: data.complete, peers: data.incomplete });
    });

    client.scrape();
  } catch (err)
  {
    callback(err, null);
  }
}
Torrent.prototype._onMetadata = function (metadata) {
  var self = this
  if (self.metadata) return

  if (metadata && metadata.infoHash) {
    // `metadata` is a parsed torrent (from parse-torrent module)
    self.metadata = parseTorrent.toBuffer(metadata)
  } else {
    self.metadata = metadata
  }

  try {
    self.parsedTorrent = parseTorrent(self.metadata)
  } catch (err) {
    return self.emit('error', err)
  }

  if (self._announce.length) {
    // If we got trackers from the magnet uri, let's use them
    self.parsedTorrent.announce = self._announce
  }

  self.name = self.parsedTorrent.name
  self.infoHash = self.parsedTorrent.infoHash

  process.nextTick(function () {
    self.emit('metadata')
  })

  if (self.swarm) {
    self._onMetadataAndSwarm()
  }
}
Example #15
0
	}).forEach( function(f) {
		var buff = fs.readFileSync(path.join(TS_DIR, f));
		load(parse(buff), function(err) {
			if(!err)
				console.log("Restored torrent", f);
		});
	});
Example #16
0
 cp.exec(CMD + ' info "' + leavesMagnetURI + '"', function (err, data) {
   t.error(err)
   data = JSON.parse(data)
   var parsedTorrent = parseTorrent(leavesMagnetURI)
   delete parsedTorrent.infoHashBuffer
   t.deepEqual(data, JSON.parse(JSON.stringify(parsedTorrent, undefined, 2)))
 })
Example #17
0
 createTorrent(Buffer.from('blah'), { name: 'blah.txt' }, function (err, torrent) {
   t.error(err)
   try {
     parseTorrent(torrent)
   } catch (err) {
     t.fail('failed to parse created torrent: ' + err.message)
   }
 })
Example #18
0
 getClient(function (err, client) {
   if (err) return util.error(err)
   util.logAppend('Downloading torrent from <strong>file</strong>' + file.name)
   var parsedTorrent = parseTorrent(file)
   parsedTorrent.announce = [ TRACKER_URL ]
   parsedTorrent.announceList = [ [ TRACKER_URL ] ]
   client.add(parsedTorrent, onTorrent)
 })
Example #19
0
 cp.exec(CMD + ' info ' + leavesPath, function (err, data) {
   t.error(err)
   data = JSON.parse(data)
   var parsedTorrent = parseTorrent(leaves)
   delete parsedTorrent.info
   delete parsedTorrent.infoBuffer
   t.deepEqual(data, JSON.parse(JSON.stringify(parsedTorrent, undefined, 2)))
 })
Example #20
0
 createTorrent(Buffer.from('blah'), { name: 'blah.txt' }, (err, torrent) => {
   t.error(err)
   try {
     parseTorrent(torrent)
   } catch (err) {
     t.fail(`failed to parse created torrent: ${err.message}`)
   }
 })
Example #21
0
seeder.on('unseed', function (link) {
  console.log('UNSEED', link)
  var t = parseTorrent(link)
  for (var i = 0; i < client.torrents.length; i++) {
    var c = client.torrents[i]
    if (c.infoHash === t.infoHash) c.destroy()
  }
})
Example #22
0
  res.on('end', function () {
    data = Buffer.concat(data) // Make one large Buffer of it

    var torrentParsed = parseTorrent(data) // Parse the Buffer

    var client = new WebTorrent()

    client.add(torrentParsed, onTorrent)

    function onTorrent (torrent) {
      var torrentFileName = path.basename(torrent.name, path.extname(torrent.name)) + '.torrent'

      util.log(
        '<a class="btn btn-primary btn-xs" href="' + torrent.magnetURI + '" role="button"><i class="fa fa-magnet"></i> Magnet URI</a> ' +
        '<a class="btn btn-primary btn-xs" href="' + torrent.torrentFileURL + '" target="_blank" download="' + torrentFileName + '" role="button"><i class="fa fa-download"></i> Download .torrent</a> ' +
        '<a id="downloadButton" class="btn btn-primary btn-xs" role="button"><i class="fa fa-download"></i> Download ' + torrent.name + '</a>'
      )

      function updateSpeed () {
        var progress = (100 * torrent.progress).toFixed(1)
        util.updateSpeed(
          '<b>Peers:</b> ' + torrent.swarm.wires.length + ' ' +
          '<b>Progress:</b> ' + progress + '% ' +
          '<b>Download speed:</b> ' + prettyBytes(client.downloadSpeed()) + '/s ' +
          '<b>Upload speed:</b> ' + prettyBytes(client.uploadSpeed()) + '/s'
        )
        progressBar.setAttribute('aria-valuenow', progress)
        progressBar.setAttribute('style', 'width: ' + progress + '%')
      }

      updateSpeed()
      setInterval(updateSpeed, 500)

      torrent.files.forEach(function (file) {
        // Create a video element
        file.appendTo('#player')

        downloadButton.addEventListener('click', function () {
          download.classList.remove('hidden')

          // Get a url for each file
          file.getBlobURL(function (err, url) {
            if (err) return util.error(err)

            // Hide download progress
            download.classList.add('hidden')

            // Add a link to the page
            var a = document.createElement('a')
            a.download = window.URL.createObjectURL(url)
            a.click()
            window.URL.revokeObjectURL(url)
          })
        })
      })
    }
  })
Example #23
0
 getSource(infile, function (body) {
   try {
     var parsed = parseTorrent(body)
   } catch (err) {
     console.error(err.stack)
     process.exit(1)
   }
   cb(parsed)
 })
Example #24
0
var torrents = [ 'leaves', 'pride' ].map(function (name) {
  var torrent = fs.readFileSync(__dirname + '/torrents/' + name + '.torrent')

  return {
    name : name,
    torrent : torrent,
    parsedTorrent : parseTorrent(torrent)
  }
})
Example #25
0
/**
 * A torrent
 *
 * @param {string|Buffer|Object} torrentId
 * @param {Object} opts
 */
function Torrent (torrentId, opts) {
  var self = this
  EventEmitter.call(self)
  debug('new torrent')

  self.client = opts.client

  self.hotswapEnabled = ('hotswap' in opts ? opts.hotswap : true)
  self.verify = opts.verify
  self.storageOpts = opts.storageOpts

  self.chokeTimeout = opts.chokeTimeout || CHOKE_TIMEOUT
  self.pieceTimeout = opts.pieceTimeout || PIECE_TIMEOUT
  self.strategy = opts.strategy || 'sequential'

  self._rechokeNumSlots = (opts.uploads === false || opts.uploads === 0) ? 0 : (+opts.uploads || 10)
  self._rechokeOptimisticWire = null
  self._rechokeOptimisticTime = 0
  self._rechokeIntervalId = null

  self.ready = false
  self.files = []
  self.metadata = null
  self.parsedTorrent = null
  self.storage = null
  self.numBlockedPeers = 0
  self._amInterested = false
  self._destroyed = false
  self._selections = []
  self._critical = []
  self._storageImpl = opts.storage || Storage

  // parse torrent id to get info hash (and preliminary name, if available)
  var parsed = parseTorrent(torrentId)
  if (!parsed || !parsed.infoHash) throw new Error('invalid torrent id')
  self.infoHash = parsed.infoHash // guaranteed to be present
  if (parsed.name) self.name = parsed.name

  // create swarm
  self.swarm = new Swarm(self.infoHash, self.client.peerId, {
    handshake: { dht: !!self.client.dht }
  })
  reemit(self.swarm, self, ['warning', 'error'])
  self.swarm.on('wire', self._onWire.bind(self))

  // update overall client stats
  self.swarm.on('download', self.client.downloadSpeed.bind(self.client))
  self.swarm.on('upload', self.client.uploadSpeed.bind(self.client))

  if (process.browser) {
    // in browser, swarm does not listen
    self._onSwarmListening(parsed)
  } else {
    // listen for peers
    self.swarm.listen(self.client.torrentPort, self._onSwarmListening.bind(self, parsed))
  }
}
Example #26
0
  createTorrent(buf1, (err, torrent) => {
    t.error(err)
    const parsedTorrent = parseTorrent(torrent)

    t.ok(parsedTorrent.name.includes('Unnamed Torrent'))

    t.equal(parsedTorrent.files.length, 1)
    t.ok(parsedTorrent.files[0].name.includes('Unnamed Torrent'))
    t.ok(parsedTorrent.files[0].path.includes('Unnamed Torrent'))
  })
Example #27
0
  createTorrent(buf1, function (err, torrent) {
    t.error(err)
    var parsedTorrent = parseTorrent(torrent)

    t.equal(parsedTorrent.name, 'My Cool File')

    t.equal(parsedTorrent.files.length, 1)
    t.equal(parsedTorrent.files[0].name, 'My Cool File')
    t.equal(parsedTorrent.files[0].path, 'My Cool File')
  })
Example #28
0
WebTorrent.prototype.get = function (torrentId) {
  var self = this
  var parsed = parseTorrent(torrentId)
  if (!parsed || !parsed.infoHash) return null
  for (var i = 0, len = self.torrents.length; i < len; i++) {
    var torrent = self.torrents[i]
    if (torrent.infoHash === parsed.infoHash) return torrent
  }
  return null
}
Example #29
0
      }, (err, torrent) => {
        var torrent = parseTorrent(torrent)
        console.log(`seeding ${file} ${torrent.infoHash}`)

        database[torrent.infoHash] = {
          file: file,
          torrent: torrent,
        }
        store_database()
      })
Example #30
0
  createTorrent(buf1, (err, torrent) => {
    t.error(err)
    const parsedTorrent = parseTorrent(torrent)

    t.equal(parsedTorrent.name, 'My Cool File')

    t.equal(parsedTorrent.files.length, 1)
    t.equal(parsedTorrent.files[0].name, 'My Cool File')
    t.equal(parsedTorrent.files[0].path, 'My Cool File')
  })