Skip to content

Instantly share code, notes, and snippets.

@Davnit
Created July 25, 2016 14:53
Show Gist options
  • Save Davnit/30eacffaa20cebc5dd886252f61b3d27 to your computer and use it in GitHub Desktop.
Save Davnit/30eacffaa20cebc5dd886252f61b3d27 to your computer and use it in GitHub Desktop.
Reads torrent files
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
class TorrentReader():
def __init__(self, filePath):
self.data = open(filePath, "rb").read()
self.position = 0
self.type = ''
def peekChar(self):
return chr(self.data[self.position])
def readChar(self):
c = self.peekChar()
self.position += 1
return c
def readToChar(self, c):
endx = self.data[self.position:].index(bytes(c, "utf-8"))
return self.readBytes(endx + 1)[:-1]
def readBytes(self, count):
val = self.data[self.position:self.position+count].decode("ISO-8859-1")
self.position += count
return val
def readByteString(self):
if is_number(self.peekChar()):
length = int(self.readToChar(':'))
value = self.readBytes(length)
return value
else:
return False
def readKeyValue(self):
key = self.readByteString()
value = self.read()
return key, value
def read(self):
t = self.peekChar()
if t == 'd':
d = dict()
self.readChar()
while not self.peekChar() == 'e':
k, v = self.readKeyValue()
d[k] = v
self.readChar()
return d
elif t == 'l':
d = list()
self.readChar()
while not self.peekChar() == 'e':
v = self.read()
d.append(v)
self.readChar()
return d
elif t == 'i':
self.readChar()
return int(self.readToChar('e'))
elif is_number(t):
return self.readByteString()
else:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment