#!/usr/bin/env python3

import requests
import bencodepy
from pprint import pprint
import hashlib
import re

def hex_escape(str):
    return "".join(chr(i) if i < 127 and i > 19 else r'\x' + r'{0:02x}'.format(i).upper() for i in str)

with open('./ubuntu.torrent', 'rb') as content_file:
    content = content_file.read()
    
torrent_info = bencodepy.decode(content)

info_hash = hashlib.sha1(bencodepy.encode(torrent_info[b'info'])).digest()

tracker_url = str(torrent_info[b"announce"], "utf-8")
length = torrent_info[b"info"][b"length"]
piece_length = torrent_info[b"info"][b"piece length"]
name = torrent_info[b"info"][b"name"]
pieces = int(length/piece_length)

print("Number of pieces: %s" % pieces)
print("Piece length: %s" % piece_length)
print("Info hash: %s" % hex_escape(info_hash))
print("")

r = requests.get(
    tracker_url,
    params = {
        "info_hash": info_hash,
        "peer_id": "00000000000000000000",
        "uploaded": 0,
        "downloaded": 0,
        "port": 0,
        "left": pieces,
        "numwant": 10
    }
)

if r.status_code != 200:
    raise RuntimeError("Tracer request failed")

peer_data = bencodepy.decode(r.content)
for peer in peer_data[b'peers']:
    print(
        "Peer address: % 15s:%s, peer ID: '%s'" % (
            str(peer[b'ip'], 'utf-8'),
            peer[b'port'],
            hex_escape(peer[b'peer id'])
        )
    )
    
