fileutils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from BTL.ConvertedMetainfo import ConvertedMetainfo
  2. from BTL.bencode import bencode, bdecode
  3. import os
  4. def file_from_path(path):
  5. assert os.path.splitext(path)[1].lower() == '.torrent'
  6. return open(path, 'rb').read()
  7. def metainfo_from_file(f):
  8. metainfo = ConvertedMetainfo(bdecode(f))
  9. return metainfo
  10. def metainfo_from_path(path):
  11. return metainfo_from_file(file_from_path(path))
  12. def infohash_from_path(path):
  13. return str(metainfo_from_path(path).infohash)
  14. def parse_infohash(ihash):
  15. """takes a hex-encoded infohash and returns an infohash or None
  16. if the infohash is invalid."""
  17. try:
  18. x = ihash.decode('hex')
  19. except ValueError:
  20. return None
  21. except TypeError:
  22. return None
  23. return x
  24. def is_valid_infohash(x):
  25. """Determine whether this is a valid hex-encoded infohash."""
  26. if not x or not len(x) == 40:
  27. return False
  28. return (parse_infohash(x) != None)
  29. def parse_uuid(uuid):
  30. """takes a hex-encoded uuid and returns an uuid or None
  31. if the uuid is invalid."""
  32. try:
  33. # Remove the '-'s at specific points
  34. uuidhash = uuid[:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:]
  35. if len(uuidhash) != 32:
  36. return None
  37. x = uuidhash.decode('hex')
  38. return uuid
  39. except:
  40. return None
  41. def is_valid_uuid(x):
  42. """Determine whether this is a valid hex-encoded uuid."""
  43. if not x or len(x) != 36:
  44. return False
  45. return (parse_uuid(x) != None)
  46. def infohash_from_infohash_or_path(x):
  47. """Expects a valid path to a .torrent file or a hex-encoded infohash.
  48. Returns a binary infohash."""
  49. if not len(x) == 40:
  50. return infohash_from_path(x)
  51. n = parse_infohash(x)
  52. if n:
  53. return n
  54. ## path happens to be 40 chars, or bad infohash
  55. return infohash_from_path(x)
  56. if __name__ == "__main__":
  57. # Test is_valid_infohash()
  58. assert is_valid_infohash("") == False
  59. assert is_valid_infohash("12345") == False
  60. assert is_valid_infohash("12345678901234567890123456789012345678901") == False
  61. assert is_valid_infohash("abcdefghijklmnopqrstuvwxyzabcdefghijklmn") == False
  62. assert is_valid_infohash("1234567890123456789012345678901234567890") == True
  63. assert is_valid_infohash("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef") == True