本文整理汇总了Python中bencode.bdecode方法的典型用法代码示例。如果您正苦于以下问题:Python bencode.bdecode方法的具体用法?Python bencode.bdecode怎么用?Python bencode.bdecode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bencode
的用法示例。
在下文中一共展示了bencode.bdecode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: from_torrent_url
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def from_torrent_url(url):
import base64
import bencode
import hashlib
import urllib
from kmediatorrent.utils import url_get
torrent_data = url_get(url)
metadata = bencode.bdecode(torrent_data)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
params = {
'dn': metadata['info']['name'],
'tr': metadata['announce'],
}
plugin.log.info(params)
paramstr = urllib.urlencode(params)
return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr)
示例2: scrape_http
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def scrape_http(announce, info_hash, peer_id, length):
params = {'info_hash': info_hash,
'peer_id': peer_id,
'left': length}
response = requests.get(announce, params=params)
if response.status_code > 400:
errorMsg = ("Failed to connect to tracker.\n"
"Status Code: %s \n"
"Reason: %s") % (response.status_code, response.reason)
raise RuntimeError(errorMsg)
results = bencode.bdecode(response.content)
return results['peers']
示例3: torrent_metainfo
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def torrent_metainfo(torrent):
logger.debug('def torrent_metainfo started')
with open(torrent, 'rb') as f:
torrent_data = f.read()
metainfo = bencode.bdecode(torrent_data)
name = metainfo['info']['name']
return name
示例4: torrent2magnet
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def torrent2magnet(self, paths):
def trans(tpath):
if tpath.lower().endswith('torrent'):
string = open(tpath).read()
try:
dd = bencode.bdecode(string)
except Exception as e:
print s % (1, 91, ' !! torrent is wrong:'), e
return None
info = bencode.bencode(dd['info'])
hh = sha1(info).hexdigest()
print '# %s' % tpath
print 'magnet:?xt=urn:btih:%s' % hh, '\n'
for path in paths:
if os.path.exists(path):
if os.path.isdir(path):
for a, b, c in os.walk(path):
for i in c:
tpath = os.path.join(a, i)
trans(tpath)
elif os.path.isfile(path):
tpath = path
trans(tpath)
else:
print s % (1, 91, ' !! file doesn\'t existed'), \
s % (1, 93, '--'), path
示例5: playlistdata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def playlistdata(self):
self.playlist = []
try:
filelist = [x for x in os.listdir(str(config.directory)) if x.endswith(('.torrent','.torrent.added'))]
except:
self.logger.error("Can't load torrent files from %s" % config.directory)
return False
for filename in filelist:
infohash = None
idx = 0
try:
with open('%s/%s' % (config.directory, filename), "rb") as torrent_file: metainfo = bencode.bdecode(torrent_file.read())
infohash = hashlib.sha1(bencode.bencode(metainfo['info'])).hexdigest()
except: self.logger.error('The file %s may be corrupted. BencodeDecodeError!' % filename)
else:
self.logger.debug('%s' % filename)
if 'files'in metainfo['info']:
try:
for files in metainfo['info']['files']:
if ''.join(files['path']).endswith(self.videoextdefaults):
self.playlist.append([''.join(files['path']).translate({ord(c): None for c in '%~}{][^$#@*,-!?&`|><+='}), infohash, str(idx), metainfo['info']['name']])
idx+=1
except Exception as e:
self.logger.error("Can't decode content of: %s\r\n%s" % (filename,repr(e)))
else:
try:
self.playlist.append([metainfo['info']['name'].translate({ord(c): None for c in '%~}{][^$#@*,-!?&`|><+='}), infohash, '0', 'Other'])
except:
try:
self.playlist.append([filename.decode('utf-8').translate({ord(c): None for c in '%~}{][^$#@*,-!?&`|><+='}), infohash, '0', 'Other'])
except AttributeError:
self.playlist.append([filename.translate({ord(c): None for c in '%~}{][^$#@*,-!?&`|><+='}), infohash, '0', 'Other'])
self.playlist.sort(key=lambda data: (data[3], data[0]))
return True
示例6: run
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def run(self):
self.re_join_DHT()
while True:
try:
(data, address) = self.ufd.recvfrom(65536)
msg = bdecode(data)
self.on_message(msg, address)
except Exception:
pass
示例7: parse_metadata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def parse_metadata(self, data): #解析种子
info = {}
self.encoding = 'utf8'
try:
torrent = bdecode(data) #编码后解析
if not torrent.get('name'):
return None
except:
return None
detail = torrent
info['name'] = self.decode_utf8(detail, 'name')
if 'files' in detail:
info['files'] = []
for x in detail['files']:
if 'path.utf-8' in x:
v = {'path': self.decode('/'.join(x['path.utf-8'])), 'length': x['length']}
else:
v = {'path': self.decode('/'.join(x['path'])), 'length': x['length']}
if 'filehash' in x:
v['filehash'] = x['filehash'].encode('hex')
info['files'].append(v)
info['length'] = sum([x['length'] for x in info['files']])
else:
info['length'] = detail['length']
info['data_hash'] = hashlib.md5(detail['pieces']).hexdigest()
return info
示例8: download_metadata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def download_metadata(address, infohash, metadata_queue, timeout=5):
metadata = None
start_time = time()
try:
the_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
the_socket.settimeout(timeout)
the_socket.connect(address)
# handshake
send_handshake(the_socket, infohash)
packet = the_socket.recv(4096)
# handshake error
if not check_handshake(packet, infohash):
return
# ext handshake
send_ext_handshake(the_socket)
packet = the_socket.recv(4096)
# get ut_metadata and metadata_size
ut_metadata, metadata_size = get_ut_metadata(packet), get_metadata_size(packet)
#print 'ut_metadata_size: ', metadata_size
# request each piece of metadata
metadata = []
for piece in range(int(math.ceil(metadata_size / (16.0 * 1024)))):
request_metadata(the_socket, ut_metadata, piece)
packet = recvall(the_socket, timeout) #the_socket.recv(1024*17) #
metadata.append(packet[packet.index("ee") + 2:])
metadata = "".join(metadata)
#print 'Fetched', bdecode(metadata)["name"], "size: ", len(metadata)
except socket.timeout:
pass
except Exception:
pass
finally:
the_socket.close()
metadata_queue.put((infohash, address, metadata, 'pt', start_time))
示例9: mask_file
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def mask_file(torrent_file):
'''
混淆种子文件
:param torrent_file: 种子文件
:return: (混淆后的种子文件内容,混淆字典)
'''
with open(torrent_file, 'r') as fp:
torrent_data = bencode.bdecode(fp.read())
return mask(torrent_data)
示例10: download_metadata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def download_metadata(address, infohash, timeout=5):
try:
the_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
the_socket.settimeout(5)
the_socket.connect(address)
# handshake
send_handshake(the_socket, infohash)
packet = the_socket.recv(4096)
# handshake error
if not check_handshake(packet, infohash):
return
# ext handshake
send_ext_handshake(the_socket)
packet = the_socket.recv(4096)
# get ut_metadata and metadata_size
ut_metadata, metadata_size = get_ut_metadata(packet), get_metadata_size(packet)
print 'ut_metadata_size: ', metadata_size
# request each piece of metadata
metadata = []
for piece in range(int(math.ceil(metadata_size/(16.0*1024)))):
request_metadata(the_socket, ut_metadata, piece)
packet = recvall(the_socket, timeout) #the_socket.recv(1024*17) #
metadata.append(packet[packet.index("ee")+2:])
metadata = "".join(metadata)
print bdecode(metadata)["name"], "size: ", len(metadata)
# with open(infohash.encode("hex")+'.txt', 'w') as f:
# f.write(metadata)
# print 'write metadata, length:', len(metadata)
except socket.timeout:
pass
except Exception, e:
print e
示例11: datagramReceived
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def datagramReceived(self, data, address):
"""
数据接收
"""
try:
res = bdecode(data)
self.actionSwitch[res["y"]](res, address)
except(BTL.BTFailure, KeyError):
pass
示例12: __init__
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def __init__(self, trackerFile):
self.peer_id = '0987654321098765432-'
self.peers = []
self.pieces = deque([])
self.tracker = bencode.bdecode(open(trackerFile,'rb').read())
bencodeInfo = bencode.bencode(self.tracker['info'])
self.infoHash = hashlib.sha1(bencodeInfo).digest()
self.getPeers()
self.generatePieces()
self.numPiecesSoFar = 0
示例13: transfer
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def transfer(self, string, tpath, foo=None, bar=None):
self.dir_dict = {}
self.sub_dir_index = 0
dstring = bencode.bdecode(string)
files = []
file_index = 0
## change files' name
if dstring['info'].get('files'):
for fl in dstring['info']['files']:
filename = fl['path'][-1]
if args.type_ == 'n':
newfilename = re.sub(foo, bar, filename, re.I) \
if foo and bar else filename
if filename != newfilename:
print filename, s % (1, 92, '==>'), newfilename
path = [self._get_sub_dir_index(i) \
for i in fl['path'][:-1]] + [newfilename]
else:
ext = os.path.splitext(filename)[-1]
ext = self._check_ext(ext)
path = [self._get_sub_dir_index(i) \
for i in fl['path'][:-1]] \
+ ['%s%s' % (file_index, ext)]
file_index += 1
fl['path'] = path
elif args.type_ == 'be64':
fn, ext = os.path.splitext(filename)
ext = self._check_ext(ext)
tfn = '/'.join(fl['path'][:-1] + [fn])
e_fn = base64.urlsafe_b64encode(tfn)
fl['path'] = [e_fn + '.base64' + ext]
for item in fl.keys():
#if item not in ['path', 'length', 'filehash', 'ed2k']:
if item not in ['path', 'length', 'filehash']:
del fl[item]
files.append(fl)
dstring['info']['files'] = files
## change top directory
for i in dstring['info'].keys():
if i not in ['files', 'piece length', 'pieces', 'name', 'length']:
del dstring['info'][i]
elif 'name' in i:
if args.name:
dstring['info'][i] = args.name
## delete comment and creator
for i in dstring.keys():
if i not in ['creation date', 'announce', 'info', 'encoding']:
del dstring[i]
c = bencode.bencode(dstring)
with open(tpath, 'w') as g:
g.write(c)
示例14: _open
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def _open(self, url, silent = False):
try:
self.tries += 1
if self.tries > MAX_REDIRECTS:
raise IOError, ('http error', 500, 'Internal Server Error: Redirect Recursion')
scheme, netloc, path, pars, query, fragment = urlparse(url)
if scheme != 'http' and scheme != 'https':
raise IOError, ('url error',
'unknown url type',
scheme,
url)
wanturl = path
if pars:
wanturl += ';' + pars
if query:
wanturl += '?' + query
proxyhost = find_proxy(url)
if proxyhost is None:
desthost = netloc
desturl = wanturl
else:
desthost = proxyhost
desturl = scheme + '://' + netloc + wanturl
try:
self.response = None
if scheme == 'http':
self.connection = btHTTPcon(desthost)
else:
self.connection = btHTTPScon(desthost)
self.connection.request('GET', desturl, None, {'Host': netloc,
'User-Agent': VERSION,
'Accept-Encoding': 'gzip'})
self.response = self.connection.getresponse()
except HTTPException as e:
raise IOError, ('http error', str(e))
status = self.response.status
if status in (301, 302):
try:
self.connection.close()
except:
pass
self._open(self.response.getheader('Location'))
return
if status != 200:
try:
data = self._read()
d = bdecode(data)
if d.has_key('failure reason'):
self.error_return = data
return
except:
pass
raise IOError, ('http error', status, self.response.reason)
except Exception as e:
if not silent:
print_exc()
print >> sys.stderr, 'zurllib: URL was', url, e
示例15: parse_metadata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bdecode [as 别名]
def parse_metadata(data):
info = {}
encoding = 'utf8'
try:
torrent = bdecode(data)
if not torrent.get('name'):
return None
except:
return None
try:
info['create_time'] = datetime.datetime.fromtimestamp(float(torrent['creation date']))
except:
info['create_time'] = datetime.datetime.utcnow()
if torrent.get('encoding'):
encoding = torrent['encoding']
if torrent.get('announce'):
info['announce'] = decode_utf8(encoding, torrent, 'announce')
if torrent.get('comment'):
info['comment'] = decode_utf8(encoding, torrent, 'comment')[:200]
if torrent.get('publisher-url'):
info['publisher-url'] = decode_utf8(encoding, torrent, 'publisher-url')
if torrent.get('publisher'):
info['publisher'] = decode_utf8(encoding, torrent, 'publisher')
if torrent.get('created by'):
info['creator'] = decode_utf8(encoding, torrent, 'created by')[:15]
if 'info' in torrent:
detail = torrent['info']
else:
detail = torrent
info['name'] = decode_utf8(encoding, detail, 'name')
if 'files' in detail:
info['files'] = []
for x in detail['files']:
if 'path.utf-8' in x:
v = {'path': decode(encoding, '/'.join(x['path.utf-8'])), 'length': x['length']}
else:
v = {'path': decode(encoding, '/'.join(x['path'])), 'length': x['length']}
if 'filehash' in x:
v['filehash'] = x['filehash'].encode('hex')
info['files'].append(v)
info['length'] = sum([x['length'] for x in info['files']])
else:
info['length'] = detail['length']
info['data_hash'] = hashlib.md5(detail['pieces']).hexdigest()
if 'profiles' in detail:
info['profiles'] = detail['profiles']
return info