首页 > 编程语言 > AAuto > python\AAuto解析BT种子,生成磁力链接.
2013
08-30

python\AAuto解析BT种子,生成磁力链接.

注:写完AAuto版的代码后,发现AAuto已经添加了种子解析库.此文仅作探讨.
python部分(设计这个磁力链协议的人比较喜欢用python,充分利用了python的几种数据类型)
1.安装bencode库
2.生成代码


import bencode, hashlib, base64, urllib
torrent = open('test.torrent', 'rb').read()

metadata = bencode.bdecode(torrent)

hashcontents = bencode.bencode(metadata['info'])
print metadata['info']
digest = hashlib.sha1(hashcontents).digest()

b32hash = base64.b32encode(digest)

params = {'xt': 'urn:btih:%s' % b32hash,

           'dn': metadata['info']['name'],

           'tr': metadata['announce'],

           'xl': metadata['info']['length']}

paramstr = urllib.urlencode(params)

magneturi = 'magnet:?%s' % paramstr

print magneturi

AAuto代码部分
直译的dencode库 AAuto代码(不保证可用,仅用于表现python和aauto语法区别)

import console

decodeInt = function(x,f){
	f+=1
	var newf = ..string.indexOf( x,"e",f )
	var n = tonumber(..string.sub( x,f,newf ))
	if x[[f]] == "-" {
		if x[[f+1]] == "0"
			error("ValueError",2)
	}
	elseif x[[f]] == '0' and newf != f+1 {
		error("ValueError",2)
	}
	return n,newf+1; 
}

decodeString = function(x,f){
	var colon = ..string.indexOf( x,":",f );
	var n = tonumber(..string.sub( x,f,colon ))
	if x[[f]] == "0" and colon != f+1
		error("ValueError",2)
	colon += 1
	return ..string.sub( x,colon,colon+n-1 ), colon+n; 
}

decodeList = function(x,f){
	r = {}
	f = f+1
	while(x[[f]]!="e"){
		v, f = decodeFunc[x[[f]]](x, f)
		if(type(v)==type.table){
			..string.save("c:\r.txt", ..table.tostring(v)++'\r\n',true)
		}
		else {
			..string.save("c:\r.txt", v++'\r\n',true)
		}

		..table.push( r,v )
	} 
	return r, f + 1
}

decodeDict = function(x,f){
	var r = {}
	f += 1
	while(x[[f]] != "e"){
		k, f = decodeString(x, f)
		v,f = decodeFunc[x[[f]]](x, f)
        r[k] = v
	}
	return r, f + 1
}

decodeFunc = {
	['l'] = decodeList;
	['d'] = decodeDict;
	['i'] = decodeInt;
	['0'] = decodeString;
	['1'] = decodeString;
	['2'] = decodeString;
	['3'] = decodeString;
	['4'] = decodeString;
	['5'] = decodeString;
	['6'] = decodeString;
	['7'] = decodeString;
	['8'] = decodeString;
	['9'] = decodeString;
}

bdecode = function(x){
	var r, l = decodeFunc[x[[1]]](x, 1)
	if(l!=(#x+1)){
		error("invalid bencoded value (data after valid prefix)")
	}
	return r; 
}

AAuto扩展库中的BT种子转磁力链的代码

import console;
import string.bdecode;

//一个简单的BT种子文件
var torrentData = 'd8:encoding5:UTF-84:infod6:lengthi5e4:name8:test.txt
12:piece lengthi16384e6:pieces20:+\xF3)\xAF\x03\xF5z\xD7\xE3\x9B}\x19\x04\x01\xDB\xF9\x8EE\xC55ee'
//解析种子
console.log( "转换为磁力链接",torrentInfo.getMagnetUri() )
最后编辑:
作者:NINE
这个作者貌似有点懒,什么都没有留下。

留下一个回复

你的email不会被公开。