Esempio n. 1
0
def mktorrent(path, outfile, tracker=None, piecesize=2**18, private=0, magnet=False):
    """Main function, writes metainfo file, fixed piece size for now"""

    # Common dict items
    torrent = {}
    torrent['info'] = {}
    torrent['info']['piece length'] = piecesize
    torrent['info']['name'] = os.path.basename(path.rstrip(os.sep))

    if tracker:
        torrent['announce'] = tracker[0]

        if len(tracker) > 1:
            torrent['announce-list'] = [tracker]

        if private:
            torrent['info']['private'] = 1
    
    # Single file case
    if os.path.isfile(path):

        torrent['info']['length'] = os.path.getsize(path)
        torrent['info']['pieces'] = makePieces([path], piecesize)

    # Multiple file case
    elif os.path.isdir(path):

        torrent['info']['files'] = []

        filelist = []
        for root, _, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(root, filename)
                filelist.append(filepath)

                fileinfo = {'length': os.path.getsize(filepath),
                            'path': filepath.split(os.sep)[1:]} #Del root dir

                torrent['info']['files'].append(fileinfo)

        torrent['info']['pieces'] = makePieces(filelist, piecesize)

    # Write metainfo file
    outfile.write(bencode.Bencode(torrent))
    
    # Print minimal magnet link if requested
    if magnet:
        link = 'magnet:?xt=urn:btih:'
        infohash = hashlib.sha1(bencode.Bencode(torrent['info'])).hexdigest()
        print(link + infohash)

    return 0
Esempio n. 2
0
def main():

    native = {'z': ['héhé', 123, 1], 'a': 'foo', 'x': b'\x01\xff'}
    bencoded = b'd1:a3:foo1:x2:\x01\xff1:zl6:h\xc3\xa9h\xc3\xa9i123ei1eee'

    try:
        assert bencode.Bencode(native) == bencoded, 'encode'
        assert Bdecode(bencoded) == native, 'decode'

    except AssertionError as e:
        return e

    else:
        return 0
Esempio n. 3
0
 def dump(self):
     cache_dst = bencode.Bencode(self.cache)
     if self.cache_src == cache_dst:
         return  # no changes
     tmp_path = self.path.temporarySibling()
     try:
         with tmp_path.open("w") as tmp:
             os.fchmod(tmp.fileno(), 0o600)
             tmp.write(cache_dst)
             tmp.flush()
             os.rename(tmp_path.path, self.path.path)
     finally:
         try:
             tmp_path.remove()
         except (OSError, IOError):
             pass
     self.cache_src = cache_dst
Esempio n. 4
0
 def __init__(self, str_):
     self.info_dic = bencode.Bencode(str_).decode()
     assert type(self.info_dic) is dict