torrent解析类使用https://github.com/Rhilip/Bencode,打补丁支持获取种子hash信息。
--- Bencode.php.1 2021-02-24 07:30:41.677067125 +0800
+++ Bencode.php 2021-03-05 17:52:23.803081067 +0800
@@ -26,6 +26,9 @@
*/
class Bencode
{
+ public function info_hash($data, $info_hash) {
+ return sha1(substr($data, $info_hash['pos'], $info_hash['length']));
+ }
/**
* Decode bencoded data from string
*
@@ -46,7 +49,15 @@
$return = [];
while ($data[$pos] !== 'e') {
$key = self::decode($data, $pos);
+ if (!strcmp($key, "info")) {
+ //if ($key === "info") {
+ $return['info_hash']['pos'] = $pos;
+ }
$value = self::decode($data, $pos);
+ if (!strcmp($key, "info")) {
+ //if ($key === "info") {
+ $return['info_hash']['length'] = ($pos - $return['info_hash']['pos']);
+ }
if ($key === null || $value === null) {
break;
}
@@ -125,6 +136,9 @@
$return = '';
$check = -1;
$list = true;
+ if (isset($data['info_hash'])) {
+ unset($data['info_hash']);
+ }
foreach ($data as $key => $value) {
if ($key !== ++$check) {
$list = false;
解析种子torrent所包含的文件名称信息,将名称和文件大小组合排序并计算sha,sha相同则2个种子内容一样可自动辅种。
<?php
require_once './Bencode.php';
require_once './ParseErrorException.php';
$bencode = new Bencode();
$str = file_get_contents($filename);
$s = $bencode->decode($str);
if (isset($s['info']["files"])) {
foreach ($s['info']["files"] as $v) {
$length = $v["length"];
$file = end($v["path"]);
$save[] = $length.$file;
}
} else {
$length = $s['info']["length"];
$file = $s['info']["name"];
$save[] = $length.$file;
}
if (isset($s["encoding"])) {
$coding = $s["encoding"];
} else {
$coding = mb_detect_encoding(implode('', $save), ['UTF-8', 'GB18030', 'GBK', 'GB2312', 'ISO-8859-1']);
echo 'detect encoding: '.$coding.PHP_EOL;
}
if (!$coding) {
$coding = 'UTF-8';
}
if ($coding != "UTF-8") {
foreach ($save as $k => $v) {
$save[$k] = mb_convert_encoding($v, "UTF-8", $coding);
}
}
sort($save);
$sha1 = sha1(implode('', $save));