本文整理汇总了Python中bencode.bencode方法的典型用法代码示例。如果您正苦于以下问题:Python bencode.bencode方法的具体用法?Python bencode.bencode怎么用?Python bencode.bencode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bencode
的用法示例。
在下文中一共展示了bencode.bencode方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: from_torrent_url
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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: torrent2magnet
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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
示例3: serialize
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def serialize(self,
use_bencode: bool=True,
include_suffix: bool=False,
include_moves: bool=False,
include_hash: bool=False):
"""
This function serialize block.
:param use_bencode: check if you want to encode using bencode.
:param include_suffix: check if you want to include suffix.
:param include_moves: check if you want to include linked moves.
:param include_hash: check if you want to include block hash.
"""
binary = (lambda x: x) if use_bencode else bytes.hex
serialized = dict(
id=self.id,
creator=self.creator,
prev_hash=self.prev_hash,
difficulty=self.difficulty,
root_hash=self.root_hash,
created_at=str(self.created_at),
version=self.version,
)
if include_suffix:
serialized['suffix'] = binary(self.suffix)
if include_moves:
serialized['moves'] = [m.serialize(
use_bencode=False,
include_signature=True,
include_id=True,
) for m in self.moves]
if include_hash:
serialized['hash'] = self.hash
if use_bencode:
if self.prev_hash is None:
del serialized['prev_hash']
serialized = bencode(serialized)
return serialized
示例4: serialize
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def serialize(self,
use_bencode=True,
include_signature=False,
include_id=False,
include_block=False):
"""
This function serialize block.
:param use_bencode: check if you want to encode using bencode.
:param include_signature: check if you want to include signature.
:param include_id: check if you want to include linked moves.
:param include_block: check if you want to include block.
"""
binary = (lambda x: x) if use_bencode else bytes.hex
serialized = dict(
user_address=self.user_address,
name=self.name,
details={k: str(v) for k, v in dict(self.details).items()},
tax=self.tax,
created_at=str(self.created_at),
)
if include_signature:
serialized.update(
signature=binary(self.signature),
user_public_key=binary(self.user_public_key),
)
if include_id:
serialized['id'] = self.id
if include_block:
if self.block:
serialized['block'] = self.block.serialize(False)
else:
serialized['block'] = None
if use_bencode:
serialized = bencode(serialized)
return serialized
示例5: playlistdata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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: send_ext_handshake
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def send_ext_handshake(the_socket):
msg = chr(BT_MSG_ID) + chr(EXT_HANDSHAKE_ID) + bencode({"m": {"ut_metadata": 1}})
send_message(the_socket, msg)
示例7: request_metadata
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def request_metadata(the_socket, ut_metadata, piece):
"""bep_0009"""
msg = chr(BT_MSG_ID) + chr(ut_metadata) + bencode({"msg_type": 0, "piece": piece})
send_message(the_socket, msg)
示例8: send_krpc
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def send_krpc(self, msg, address):
try:
self.ufd.sendto(bencode(msg), address)
except Exception:
pass
示例9: mask
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def mask(torrent_data):
'''
混淆种子内容
:param torrent_data: 种子文件内容
:return: (混淆后的种子文件内容,混淆字典)
'''
name_dict = _mask_filename(torrent_data)
torrent_data = bencode.bencode(torrent_data)
return torrent_data, name_dict
示例10: mask_file
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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)
示例11: send_ext_handshake
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def send_ext_handshake(the_socket):
msg = chr(BT_MSG_ID) + chr(EXT_HANDSHAKE_ID) + bencode({"m":{"ut_metadata": 1}})
send_message(the_socket, msg)
示例12: sendKRPC
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [as 别名]
def sendKRPC(self, msg, address):
"""
发送数据
"""
try:
self.transport.write(bencode(msg), address)
except socket.error:
pass
示例13: __init__
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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
示例14: transfer
# 需要导入模块: import bencode [as 别名]
# 或者: from bencode import bencode [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)