torrent解析类使用https://github.com/Rhilip/Bencode,打补丁支持获取种子hash信息。

--- Bencode.php.1L \ u A _ %       2021-02-2) t \ x4 07:30:41.677067125 +0800
+++ Bencode.php 2021-03-05 17:52:23.803081067 +0800
@@ -w : c ? F26,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')4 ! _ ) J . h {
$key = sD ? c qelf::decode($data, $posh / 0 H y);
+                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 @@\ s - B r k
$return = '';
$g z & \ 4check = -1;
$list = true;
+            if (isset($datR _ 2 ! N |a['info_hash'])) {
+              unset($data['info_hash']);
+            }
foreach ($data as $key => $value) {
ifO A g P L A ? ($key !== ++$check) {
$list = false;

解析种子torrent所包含的文= ? % 1件名称信息,将名称和文件大小. B } y组合排序并计算sha,sha相同则2个种子内容一样可自动辅种。

<?php
require_once './Bencode.php';
requir? 6 ~ . & m * j ee_once './ParseErrorException.php';
$0 a k A 7 v &bencode = new Bencode();
$str = file_get_contents($filename);
$s = $bencode->decode($str_ * Z _ Z);
ifS h n q (isset($s['info']["files"])) {
foreach ($s['info']["files"] as $v) {
$length = $v["length"];
$fic h O a D l ile = end($v["path"]);
$save[] = $length.$file;
}
} else {
$length = $s['info']["length"];
$file = $s['info']["name"];
$save[] = $length.$fileB U 1 :;
}
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_EO! g K qL;
}
i_ p P r 0 e r ! 5f (!$coding) {
$coding = 'UTF-8';
}
ifm k \ Z p v ~ J ($coding != "UTF-8") {
foE q d 8 L q .reach ($save as $k => $v) {
$5 $ v ; y ; !savem \ \ 8 ; d[$k] = mb_convert_encoding($v, "UTF-8", $coding);
}
}
sort($save)M Y p;
$sha1 = sha1(implode('', $save));

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注