-
Notifications
You must be signed in to change notification settings - Fork 0
/
mag.php
89 lines (89 loc) · 2.36 KB
/
mag.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
/**
* https://github.com/popcorner/14smantra
* © 2018 popcorner
*/
function hex2mantra($str) {
return mb_convert_encoding(hex2bin(dechex((hexdec($str)>>6)+184).dechex((hexdec($str)&63)+161)),"UTF-8","GBK");
}
function mantra2hex($str) {
$deco = bin2hex(mb_convert_encoding($str,"GBK","UTF-8"));
$toppart = hexdec(substr($deco,0,2))-184;
$rearpart = hexdec(substr($deco,2))-161;
if($toppart<64 && $toppart>=0 && $rearpart<64 && $rearpart>=0) {
return str_pad(dechex(($toppart<<6)+$rearpart),3,'0',STR_PAD_LEFT);
}
}
function splitinfohash($str,$isbin=0) {
if($isbin){
$str = bin2hex($str);
}
if(strlen($str)<40) {
$str = str_pad($str,40,'0',STR_PAD_LEFT);
}
$str = str_pad($str,42,'0');
return str_split($str,3);
}
function magnet2infohash($mag) {
$maga = explode('?',$mag);
if(count($maga)>1) {
$maga = explode('&',explode('?',$mag)[1]);
} else {
$maga = [];
}
$return = '';
foreach($maga as $mitem) {
if(substr($mitem,0,2) == 'xt') {
$return = substr($mitem,12);
if(strlen($return)==32) {
include './base32.php';
$return = bin2hex(Base32::decode($return));
}
break;
}
}
if(strlen($return)==40) {
return $return;
} else {
return '';
}
}
function infohash2magnet($btih) {
return 'magnet:?xt=urn:btih:'.$btih;
}
function encode($param) {
$iia = magnet2infohash($param);
if($iia) {
$ifa = splitinfohash($iia);
$output = '';
foreach($ifa as $ia) {
$output .= hex2mantra($ia);
}
return substr_replace($output,',',21,0);
} else {
return 'naive';
}
}
function decode($param) {
$ifa = preg_split('//u',$param,null,PREG_SPLIT_NO_EMPTY);
$output = '';
foreach($ifa as $ia) {
$output .= mantra2hex($ia);
}
if(strlen($output)>39) {
return infohash2magnet(substr($output,0,40));
} else {
return 'naive';
}
}
function main_handler($event, $context) {
$param = json_decode($event->body,true);
if($param['method']=='encode') {
$result = encode($param['value']);
} elseif($param['method']=='decode') {
$result = decode($param['value']);
} else {
$result = '';
}
return json_encode(['result'=>$result]);
}