python-ox/ox/torrent.py

75 lines
2.1 KiB
Python
Raw Normal View History

2008-04-27 16:54:37 +00:00
# -*- coding: utf-8 -*-
2008-06-19 09:21:21 +00:00
# vi:si:et:sw=4:sts=4:ts=4
2008-07-06 13:00:06 +00:00
# GPL 2007
2008-04-27 16:54:37 +00:00
from threading import Event
2009-03-16 17:15:14 +00:00
import hashlib
2008-04-27 16:54:37 +00:00
from os import stat
2009-09-03 16:29:04 +00:00
import os
2008-04-27 16:54:37 +00:00
from BitTornado.BT1.makemetafile import make_meta_file
from bencode import bencode, bdecode
2008-04-27 16:54:37 +00:00
def createTorrent(file, url, params = {}, flag = Event(),
progress = lambda x: None, progress_percent = 1):
2008-06-19 09:21:21 +00:00
"Creates a torrent for a given file, using url as tracker url"
return make_meta_file(file, url, params, flag, progress, progress_percent)
2008-04-27 16:54:37 +00:00
def getInfoHash(torrentFile):
2008-06-19 09:21:21 +00:00
"Returns Torrent Info Hash from torrent file"
metainfo_file = open(torrentFile, 'rb')
metainfo = bdecode(metainfo_file.read())
info = metainfo['info']
2009-03-16 17:15:14 +00:00
return hashlib.sha1(bencode(info)).hexdigest().upper()
2008-04-27 16:54:37 +00:00
def getTorrentInfoFromFile(torrentFile):
2008-06-19 09:21:21 +00:00
f = open(torrentFile, 'rb')
data = f.read()
f.close()
tinfo = getTorrentInfo(data)
tinfo['timestamp'] = stat(torrentFile).st_ctime
return tinfo
def getTorrentInfo(data):
2008-06-19 09:21:21 +00:00
"Returns Torrent Info from torrent file"
tinfo = {}
metainfo = bdecode(data)
info = metainfo['info']
piece_length = info['piece length']
if info.has_key('length'):
# let's assume we just have one file
file_length = info['length']
else:
# let's assume we have a directory structure
file_length = 0;
for f in info['files']:
file_length += f['length']
for key in info:
if key != 'pieces':
tinfo[key] = info[key]
for key in metainfo:
if key != 'info':
tinfo[key] = metainfo[key]
tinfo['size'] = file_length
2009-03-16 17:15:14 +00:00
tinfo['hash'] = hashlib.sha1(bencode(info)).hexdigest()
2008-06-19 09:21:21 +00:00
tinfo['announce'] = metainfo['announce']
return tinfo
2008-04-27 16:54:37 +00:00
2009-09-03 16:29:04 +00:00
def getFiles(data):
files = []
info = getTorrentInfo(data)
if 'files' in info:
for f in info['files']:
path = [info['name'], ]
path.extend(f['path'])
files.append(os.path.join(*path))
else:
files.append(info['name'])
return files
2008-04-27 16:54:37 +00:00
def getTorrentSize(torrentFile):
2008-06-19 09:21:21 +00:00
"Returns Size of files in torrent file in bytes"
return getTorrentInfo(torrentFile)['size']
2008-04-27 16:54:37 +00:00