webtorrent/parse-torrent

Editing parsed torrent object doesn't change encoded torrent file?

mildmojo opened this issue · 2 comments

I'm trying to write a script to truncate long filenames inside a torrent file so it'll download successfully using Transmission in an encrypted Linux volume.

I can parse the torrent file, pick out the file paths and names, truncate them and store them back to the object, then use .toTorrentFile to get a buffer I can write to disk. Logging the values from the torrent object, I see the truncated filenames. Inspecting the output file (using the parse-torrent executable), I see the original filenames.

Any advice? Script below.

#!/usr/bin/env node

/* fix-torrent-filenames.js */

const fs = require('fs');
const path = require('path');
const parseTorrent = require('parse-torrent');

const torrentFile = process.argv[2];

if (!torrentFile) {
  console.warn('Usage: ' + path.basename(__filename) + ' <torrent file>');
}

const torrent = parseTorrent(fs.readFileSync(torrentFile));

for (var i = 0; i < torrent.files.length; i++) {
  var file = torrent.files[i];
  var ext = path.extname(file.path.toString());
  var basename = path.basename(file.path.toString()).replace(new RegExp(ext + '$'), '');
  var pathname = path.dirname(file.path.toString());
  var filename = basename.substr(0, 96) + ext;
  torrent.files[i].path = new Buffer(path.join(pathname, filename));
  torrent.files[i].name = new Buffer(filename);
}

const buf = parseTorrent.toTorrentFile(torrent);
fs.writeFileSync(torrentFile + '.new.torrent', buf);

console.log('Wrote ' + buf.length + ' bytes to ' + torrentFile + '.new.torrent');

You need to change the values inside of torrent.info, since those are what actually get used by parseTorrent.toTorrentFile(). You can see the code that runs here: https://github.com/feross/parse-torrent-file/blob/77d26288d5c54af8552c0f87e474521410782d6d/index.js#L107

It would be great if you could send a PR to update the documentation to help others in the future!

Ah, thanks for the tip and the pointer to the code. I'll take a swing at the docs if I can get the time.