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.

torrenttracker.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #! /usr/bin/env python
  2. import requests
  3. import time
  4. import hashlib
  5. import bencode
  6. class TorrentTracker:
  7. torrent = None
  8. session = None
  9. peer_id = ""
  10. port = 0
  11. user_agent = ""
  12. interval = 300
  13. uploaded = 0
  14. downloaded = 0
  15. left = 0
  16. def __init__(self, torrent, port=6882, user_agent="rtorrent/0.8.42/0.12.42"):
  17. self.torrent = torrent
  18. self.session = requests.session()
  19. self.peer_id = hashlib.sha1(str(time.time())).digest()
  20. self.port = port
  21. self.user_agent = user_agent
  22. def getInterval(self):
  23. return self.interval
  24. def request(self, event=""):
  25. params = {"info_hash": self.torrent.getHash().digest(),
  26. "peer_id": self.peer_id,
  27. "port": self.port,
  28. "uploaded": self.uploaded,
  29. "downloaded": self.downloaded,
  30. "left": self.left,
  31. "event": event}
  32. headers = {"User-Agent": self.user_agent}
  33. r = self.session.get(self.torrent.getAnnounce(), headers=headers, params=params)
  34. data = bencode.bdecode(r.content)
  35. if 'interval' in data:
  36. self.interval = int(data['interval'])
  37. return data;
  38. def start(self, left = 0):
  39. self.uploaded = 0
  40. self.downloaded = 0
  41. self.left = left
  42. return self.request("started")
  43. def stop(self):
  44. return self.request("stopped")
  45. def complete(self):
  46. self.left = 0
  47. return self.request("completed")
  48. def update(self, uploaded, downloaded = 0, left = 0):
  49. self.uploaded += uploaded
  50. self.downloaded += downloaded
  51. self.left -= left
  52. return self.request()