magnet-dl.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. import libtorrent as lt
  3. import sys
  4. import time
  5. from os import get_terminal_size
  6. from string import hexdigits
  7. ##magnet_string = 'magnet:?xt=urn:btih:fef84077088ca87ffd8afd644d0ef957d96243c3&dn=archlinux-2023.01.01-x86_64.iso'
  8. try:
  9. if len(sys.argv[1]) == 40 and all(c in hexdigits for c in sys.argv[1]):
  10. magnet_string = 'magnet:?xt=urn:btih:' + sys.argv[1]
  11. else:
  12. assert sys.argv[1][0:8] == 'magnet:?'
  13. magnet_string = sys.argv[1]
  14. except:
  15. print("please provide a magnet link in quotes or a 40 character hex hash as the only arguement")
  16. print("Example: ", sys.argv[0], '"magnet:?xt=urn:btih:fef84077088ca87ffd8afd644d0ef957d96243c3"')
  17. print("Example: ", sys.argv[0], "fef84077088ca87ffd8afd644d0ef957d96243c3")
  18. sys.exit(1)
  19. ses = lt.session({'listen_interfaces': '0.0.0.0:6881'})
  20. params = lt.parse_magnet_uri(magnet_string)
  21. params.save_path = '.'
  22. handle = ses.add_torrent(params)
  23. status = handle.status()
  24. print('\nResolving: ', magnet_string, end=" ", flush=True)
  25. while (not status.name):
  26. status = handle.status()
  27. time.sleep(1)
  28. print('.', end=" ", flush=True)
  29. print('\n\nStarting:', status.name, '\n')
  30. while (not status.is_seeding):
  31. status = handle.status()
  32. display = " {:.2f}% complete (down: {:.1f} kB/s up: {:.1f} kB/s peers: {:d}) {}".format(
  33. status.progress * 100,
  34. status.download_rate / 1000,
  35. status.upload_rate / 1000,
  36. status.num_peers,
  37. status.state
  38. )
  39. columns, rows = get_terminal_size(0)
  40. if sys.stdout.isatty():
  41. if columns < len(display):
  42. display = display[0:columns-1] + '\r'
  43. else:
  44. padding_size = columns - len(display) - 1
  45. padding = " " * padding_size
  46. display = display + padding + '\r'
  47. else:
  48. display = display + "\n"
  49. print(display, end="")
  50. alerts = ses.pop_alerts()
  51. for a in alerts:
  52. if a.category() & lt.alert.category_t.error_notification:
  53. print('\nERROR:', a, '\n')
  54. sys.stdout.flush()
  55. time.sleep(1)
  56. print("\n\nCompleted: ", status.name, "\n")