Matt Joiner avatar Matt Joiner committed 20a7214

Tidy up metainfo module.

Comments (0)

Files changed (2)

+from . import bencode
+
+
+class Metainfo:
+
+    def __init__(self, raw):
+        import hashlib
+        self.raw = raw
+        h = hashlib.sha1()
+        h.update(bencode.encode(raw['info']))
+        self.info_hash = h.digest()
+        assert not len(raw['info']['pieces']) % 20
+
+        self.multi_file = 'length' not in raw['info']
+        def piece_hashes():
+            bs = raw['info']['pieces']
+            for i in range(0, len(bs), 20):
+                yield bs[i:i+20]
+        self.piece_hashes = tuple(piece_hashes())
+        if len(self.piece_hashes[-1]) != 20:
+            raise ValueError
+
+    def pretty_dict(self):
+        import copy, binascii
+        ret = copy.deepcopy(self.raw)
+        ret['info']['pieces'] = len(self.piece_hashes)
+        assert 'hash' not in ret['info']
+        ret['info']['hash'] = binascii.b2a_hex(self.info_hash).decode()
+        return ret
+
+    @property
+    def tracker_urls(self):
+        yield self.raw['announce'].decode()
+        for url in self.raw.get('announce-list', ()):
+            yield url.decode()

metainfo.py

-import collections
-import hashlib
-
-from bencoding import bencode
-
-
-class Metainfo(collections.OrderedDict):
-
-    def __init__(self, *args, **kwds):
-        super().__init__(*args, **kwds)
-        h = hashlib.sha1()
-        h.update(bencode(self['info']))
-        self.info_hash = h.digest()
-        assert not len(self['info']['pieces']) % 20
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.