Showing posts with label torrent. Show all posts
Showing posts with label torrent. Show all posts

Friday, December 6, 2013

Converting Python OrderedDict To Bencoded Binary File

This post polishes up the two previous posts.  The idea here was to be able to open a torrent file and make a few modifications.  I had a torrent go down on me and hadn't download all the files.  I thought I would try removing the tracker and 'private' status and try to connect via DHT.  So far this hasn't been successful.  I think other peers would need to also enable DHT for their torrents :/ Regardless, it seemed natural to be able to create a file from the python ordered dictionry.  The python ordered dictionary is described in this post

from collections import OrderedDict
...
def PyToBEncode(pydict):
    bytestringlist = []
    def writed(dic):
        bytestringlist.append(b'd')
        for key in dic:
            strlen = len(key)
            bytestringlist.append(bytes(str(strlen), encoding='utf8'))
            bytestringlist.append(b':')
            bytestringlist.append(bytes(key))
            value = dic[key]
            if type(value) == type(OrderedDict()):
                writed(value)
            elif type(value) == type([]):
                writel(value)
            elif type(value) == type(int()):
                writei(value)
            else:
                bytestringlist.append(bytes(str(len(value)), encoding='utf8'))
                bytestringlist.append(b':')
                bytestringlist.append(bytes(value))
        bytestringlist.append(b'e')   
    def writel(lis):
        bytestringlist.append(b'l')
        for el in lis:
            if type(el) == type(OrderedDict()):
                writed(el)
            elif type(el) == type([]):
                writel(el)
            elif type(el) == type(int()):
                writei(el)
            else:
                bytestringlist.append(bytes(str(len(el)), encoding='utf8'))
                bytestringlist.append(b':')
                bytestringlist.append(bytes(el))
        bytestringlist.append(b'e')
    def writei(num):
        bytestringlist.append(b'i')
        bytestringlist.append(bytes(str(num), encoding='utf8'))
        bytestringlist.append(b'e')
    writed(pydict)
    return b''.join(bytestringlist)
   
Here is a graphic of creating a new torrent.  I am still waiting to make a connection.