Skip to content

Instantly share code, notes, and snippets.

@nbrochu
Created September 10, 2009 05:35
Show Gist options
  • Save nbrochu/184332 to your computer and use it in GitHub Desktop.
Save nbrochu/184332 to your computer and use it in GitHub Desktop.
# Generating a unique passkey for each user(to use with XBT Tracker) and injecting it in the torrent file.
# This is for Rails.
require 'bencode' # sudo gem install bencode
require 'digest/sha1'
class TorrentsController < ApplicationController
def download_example_torrent
# Decode the torrent file using the bencode gem
decoded_torrent = BEncode.load_file("public/files/example.torrent") # This would normally be dynamic and fetched from the DB...
# Generate the info_hash
info_hash = ([Digest::SHA1.hexdigest(decoded_torrent["info"].bencode)].pack("H*")).downcase
uid = current_user.id # This assumes an Authlogic authentication system. Adjust accordingly!
torrent_pass_private_key = "1294e7bc8ca465b124319c70538c1f16" # This will usually be fetched from the xbt_config table
torrent_pass_version = 0 # This will usually be fetched from the xbt_users table
# Generate the passkey, following the XBT Tracker algorithm
substring = (Digest::SHA1.hexdigest("%s %d %d %s" % [torrent_pass_private_key, torrent_pass_version, uid, info_hash]).slice(0..23))
passkey = ("%08x%s" % [uid, substring])
# Tweak the announce URL for to include the passkey
announce_url = URI.parse("http://localhost:2710/announce")
announce_url.path = "/" + passkey + announce_url.path
decoded_torrent["announce"] = announce_url.to_s # New format: http://localhost:2710/passkey/announce
# Reencode the torrent metadata
torrent_data = decoded_torrent.bencode
# Stream the modified torrent file to the user!
send_data torrent_data, :filename => "passkeyed.torrent", :type => "application/x-bittorrent"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment