Compare commits

...

33 Commits

Author SHA1 Message Date
David
945df1a9cb Merge pull request #56 from GrayXu/master
新增站点:蝴蝶
2021-09-05 16:44:36 +08:00
Gray Xu
88420c4260 新增站点:蝴蝶 2021-09-05 16:36:19 +08:00
david
136c9ee2ba 加版本号 2021-07-09 18:25:55 +08:00
david
9497cea867 优化URL替换规则,支持新站点 2021-07-09 18:22:19 +08:00
david
6f23c966e1 修改用户绑定接口地址 2021-07-01 23:58:53 +08:00
david
9d8eee73d9 新增站点:蒲公英、阿童木 2021-03-06 11:26:17 +08:00
david
d9698dfe7f 累加版本号 2021-01-13 14:11:13 +08:00
david
a6e2be82c9 加入.gitignore 2021-01-13 14:05:50 +08:00
david
e9214738c9 add 2021-01-13 13:59:11 +08:00
david
e61b47f3e8 移除、添加文件 2021-01-13 13:53:54 +08:00
david
87d9f81bad 修复entrypoint.sh权限给太高,某些情况下无法执行的问题。 2020-12-31 00:30:17 +08:00
david
7b2e82c506 修复entrypoint.sh在UNRAID中777权限无法执行问题 2020-12-31 00:23:41 +08:00
david
ae63bfca89 加入操作辅种docker容器的相关命令示例 2020-12-23 16:32:57 +08:00
david
6c1211708c v1.10.17 2020-12-22 12:04:59 +08:00
david
40387fdb5b + push.sh 2020-12-22 12:03:11 +08:00
david
e10c36295c 优化Dockerfile防止更新权限覆盖 2020-12-22 01:19:45 +08:00
david
801d7b016f 优化entrypoint.sh脚本 2020-12-22 01:14:40 +08:00
david
1ff415ea91 && chmod -R 777 /IYUU/docker/entrypoint.sh \ 2020-12-22 00:24:35 +08:00
david
849370e26a 优化docker 2020-12-22 00:14:52 +08:00
david
815156b252 修复重复注入拼接规则bug 2020-12-14 15:16:51 +08:00
david
d62be67927 修改docker定时 2020-12-14 11:47:59 +08:00
david
d513b1bedf 修改 Dockerfile 2020-12-14 02:36:38 +08:00
david
b566181968 优化辅种前置检查 2020-12-13 21:06:13 +08:00
david
60b4939aee fix 2020-12-12 15:47:08 +08:00
david
dad8afa8d4 fix 2020-12-12 15:16:54 +08:00
david
a60e5f859c 补充新规则的配置参数 2020-12-12 14:46:49 +08:00
david
59622691e1 重要更新:
1.hdhome、pthome、ourbits,加入新的辅种下载规则;
2.新增支持HDAI站点。
3.合作站验证参数,改为云端获取;
4.辅种检查参数,改为云端获取。
2020-12-12 14:29:12 +08:00
david
3a97c17e66 编辑示例配置注释 2020-12-06 21:49:33 +08:00
david
6d3b937097 新增3群号码 2020-12-01 13:54:22 +08:00
david
4277568346 新增站点:pttime 2020-11-30 16:27:49 +08:00
david
84f75ea443 移除失效站点信息,优化代码 2020-11-13 00:23:36 +08:00
david
715be0e7eb 修正注释描述 2020-11-04 15:00:54 +08:00
david
6eebc7d26c 修改ttg配置的顺序 2020-09-04 23:45:52 +08:00
37 changed files with 2521 additions and 1582 deletions

79
.gitignore vendored Normal file
View File

@@ -0,0 +1,79 @@
/composer
/config/config.php
/config/*.json
/php
/torrent
/runtime
/*.bat
/composer.lock
.idea
.php_cs.cache
composer.phar
.fuse_hidden*
.directory
.Trash-*
.nfs*
### OSX ###
# General
.DS_Store
.AppleDouble
.LSOverride
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/osx,linux,windows,visualstudiocode,composer

View File

@@ -1,4 +1,5 @@
#FROM alpine:latest
#FROM alpine:3.12
FROM alpine:3.8
#FROM swoft/alphp:base
#FROM swoft/alphp:cli
@@ -18,7 +19,7 @@ ARG app_env=prod
ENV APP_ENV=${app_env:-"prod"} \
TIMEZONE=${timezone:-"Asia/Shanghai"} \
cron="8 11 * * 0"
cron="3 */10 * * *"
##
# ---------- building ----------
@@ -26,7 +27,7 @@ ENV APP_ENV=${app_env:-"prod"} \
RUN set -ex \
# change apk source repo
# && sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/' /etc/apk/repositories \
#&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/' /etc/apk/repositories \
&& apk update \
&& apk add --no-cache \
# Install base packages ('ca-certificates' will install 'nghttp2-libs')
@@ -62,6 +63,7 @@ RUN set -ex \
# php7-pdo_mysql \
# php7-pdo_sqlite \
# php7-phar \
# php7-pcntl \
# php7-posix \
# php7-redis \
php7-simplexml \
@@ -75,10 +77,12 @@ RUN set -ex \
# php7-tokenizer \
php7-zip \
# php7-zlib \
php7-xml \
&& git clone https://gitee.com/ledc/IYUUAutoReseed.git /var/www \
&& cp /var/www/config/config.sample.php /var/www/config/config.php \
&& ln -sf /var/www/config/config.php /config.php \
php7-xml \
&& git clone https://gitee.com/ledc/IYUUAutoReseed.git /IYUU \
&& cp /IYUU/config/config.sample.php /IYUU/config/config.php \
&& ln -sf /IYUU/config/config.php /config.php \
&& cp /IYUU/docker/entrypoint.sh /entrypoint.sh \
&& chmod +x /entrypoint.sh \
&& apk del --purge *-dev \
&& rm -rf /var/cache/apk/* /tmp/* /usr/share/man /usr/share/php7 \
# ---------- some config,clear work ----------
@@ -93,7 +97,8 @@ RUN set -ex \
# - config timezone
&& ln -sf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime \
&& echo "${TIMEZONE}" > /etc/timezone \
&& echo '2 */5 * * * cd /var/www && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root \
&& echo '2 */5 * * * cd /IYUU && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root \
#&& echo "${cron} /usr/bin/php /IYUU/iyuu.php &> /dev/null" >> /etc/crontabs/root \
# ---------- some config work ----------
# - ensure 'www-data' user exists(82 is the standard uid/gid for "www-data" in Alpine)
# && addgroup -g 82 -S ${add_user} \
@@ -103,8 +108,7 @@ RUN set -ex \
# && chown -R ${add_user}:${add_user} /data \
&& echo -e "\033[42;37m Build Completed :).\033[0m\n"
EXPOSE 9000
# VOLUME ["/var/www", "/data"]
WORKDIR /var/www
CMD ["sh", "-c", "/usr/bin/php /var/www/iyuu.php ; /usr/sbin/crond ; (crontab -l ;echo \"$cron /usr/bin/php /var/www/iyuu.php &> /dev/null\") | crontab - ; tail -f /dev/null"]
# EXPOSE 9000
# VOLUME ["/IYUU", "/data"]
WORKDIR /IYUU
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -13,17 +13,17 @@ use IYUU\Library\Table;
class AutoReseed
{
// 版本号
const VER = '1.10.8';
const VER = '1.10.23';
// RPC连接
private static $links = [];
// 客户端配置
private static $clients = [];
// 站点列表
private static $sites = [];
// 不辅种的站点 'pt','hdchina'
// 推荐的合作站点
private static $recommend = [];
// 不辅种的站点
private static $noReseed = [];
// cookie检查
private static $cookieCheck = ['hdchina','hdcity','hdsky'];
// 缓存路径
public static $cacheDir = TORRENT_PATH.'cache'.DS;
public static $cacheHash = TORRENT_PATH.'cachehash'.DS;
@@ -31,13 +31,17 @@ class AutoReseed
// API接口配置
public static $apiUrl = 'http://api.iyuu.cn';
public static $endpoints = array(
'login' => '/user/login',
'login' => '/App.Api.Bind',
'sites' => '/api/sites',
'infohash'=> '/api/infohash',
'hash' => '/api/hash',
'notify' => '/api/notify',
'recommendSites' => '/Api/GetRecommendSites',
'getSign' => '/Api/GetSign'
);
// curl
/**
* @var null | Curl
*/
private static $curl = null;
// 退出状态码
public static $ExitCode = 0;
@@ -64,7 +68,11 @@ class AutoReseed
'torrent_id'=> 0,
'error' => '',
);
// 初始化
/**
* 初始化
* @throws \ErrorException
*/
public static function init()
{
global $configALL;
@@ -77,11 +85,18 @@ class AutoReseed
self::$curl->setOpt(CURLOPT_SSL_VERIFYHOST, 2);
// 合作站点鉴权绑定
Oauth::login(self::$apiUrl . self::$endpoints['login']);
$recommend_sites = [];
$ret = self::$curl->get(self::$apiUrl . self::$endpoints['recommendSites']);
$ret = json_decode($ret->response, true);
if (isset($ret['ret']) && $ret['ret'] === 200 && isset($ret['data']['recommend']) && is_array($ret['data']['recommend'])) {
$recommend_sites = $ret['data']['recommend'];
self::$recommend = array_column($recommend_sites, 'site'); // init
}
Oauth::login(self::$apiUrl . self::$endpoints['login'], $recommend_sites);
// 显示支持站点列表
self::ShowTableSites();
self::$clients = isset($configALL['default']['clients']) && $configALL['default']['clients'] ? $configALL['default']['clients'] : array();
self::$clients = empty($configALL['default']['clients']) ? [] : $configALL['default']['clients']; // init
// 递归删除上次历史记录
IFile::rmdir(self::$cacheDir, true);
@@ -92,6 +107,7 @@ class AutoReseed
// 连接全局客户端
self::links();
}
/**
* 显示支持站点列表
*/
@@ -102,28 +118,22 @@ class AutoReseed
'github源码仓库https://github.com/ledccn/IYUUAutoReseed',
'教程https://gitee.com/ledc/IYUUAutoReseed/tree/master/wiki',
'问答社区http://wenda.iyuu.cn',
'【IYUU自动辅种交流】QQ群859882209、931954050'.PHP_EOL,
'【IYUU自动辅种交流】QQ群859882209、931954050、924099912'.PHP_EOL,
'正在连接IYUUAutoReseed服务器查询支持列表……'.PHP_EOL
];
foreach ($list as $v) {
array_walk($list, function ($v, $k) {
echo $v.PHP_EOL;
}
});
$res = self::$curl->get(self::$apiUrl.self::$endpoints['sites'].'?sign='.Oauth::getSign().'&version='.self::VER);
$rs = json_decode($res->response, true);
$sites = isset($rs['data']['sites']) && $rs['data']['sites'] ? $rs['data']['sites'] : [];
// 数据写入本地
$sites = empty($rs['data']['sites']) ? [] : $rs['data']['sites'];
if (empty($sites)) {
if (!empty($rs['msg'])) {
die($rs['msg'].PHP_EOL);
}
die('网络故障或远端服务器无响应,请稍后再试!!!');
}
self::$sites = array_column($sites, null, 'id');
$json = array_column($sites, null, 'site');
ksort($json);
$sitesConfig = ROOT_PATH.DS.'config'.DS.'sites.json';
file_put_contents($sitesConfig, \json_encode($json, JSON_UNESCAPED_UNICODE));
$data = [];
$i = $j = $k = 0; // i列、j序号、k行
@@ -142,7 +152,14 @@ class AutoReseed
$table = new Table();
$table->setRows($data);
echo($table->render());
// 生成IYUUPTT使用的JSON
$_sites = array_column($sites, null, 'site');
ksort($_sites);
$sitesConfig = ROOT_PATH.DS.'config'.DS.'sites.json';
file_put_contents($sitesConfig, \json_encode($_sites, JSON_UNESCAPED_UNICODE));
}
/**
* 连接远端RPC下载器
*/
@@ -152,7 +169,7 @@ class AutoReseed
// 跳过未配置的客户端
if (empty($v['username']) || empty($v['password'])) {
self::$links[$k] = array();
echo "clients_".$k." 用户名或密码未配置,已跳过".PHP_EOL.PHP_EOL;
echo "clients_".$k." 用户名或密码未配置,已跳过".PHP_EOL.PHP_EOL;
continue;
}
try {
@@ -166,17 +183,20 @@ class AutoReseed
print $v['type'].''.$v['host']." Rpc连接 [{$result}]".PHP_EOL;
// 检查转移做种 (self::$move为空移动配置为真)
if (is_null(self::$move) && !empty($v['move'])) {
self::$move = array($k,$v['move']);
self::$move = array($k, $v['move']);
}
} catch (\Exception $e) {
die('[连接错误] ' . $e->getMessage() . PHP_EOL);
die('[连接错误] '. $v['host'] . $e->getMessage() . PHP_EOL);
}
}
}
/**
* @brief 添加下载任务
* @param $rpcKey
* @param string $torrent 种子元数据
* @param string $save_path 保存路径
* @param array $extra_options
* @return bool
*/
public static function add($rpcKey, $torrent, $save_path = '', $extra_options = array())
@@ -246,18 +266,20 @@ class AutoReseed
}
return false;
}
/**
* 辅种或转移,总入口
*/
public static function call()
{
if (self::$move!==null) {
if (self::$move !== null) {
self::move();
}
self::reseed();
self::wechatMessage();
exit(self::$ExitCode);
}
/**
* IYUUAutoReseed辅种
*/
@@ -273,16 +295,16 @@ class AutoReseed
continue;
}
// 过滤无需辅种的客户端
if (self::$move!==null && self::$move[0]!=$k && self::$move[1]==2) {
if ((self::$move !== null) && (self::$move[0] != $k) && (self::$move[1] == 2)) {
echo "clients_".$k." 根据设置无需辅种,已跳过!";
continue;
}
echo "正在从下载器 clients_".$k." 获取种子哈希……".PHP_EOL;
$hashArray = self::$links[$k]['rpc']->getList();
$hashArray = self::$links[$k]['rpc']->all();
if (empty($hashArray)) {
continue;
}
self::backup('clients_'.$k, $hashArray);
$infohash_Dir = $hashArray['hashString']; // 哈希目录对应字典
unset($hashArray['hashString']);
// 签名
@@ -291,11 +313,11 @@ class AutoReseed
$hashArray['version'] = self::VER;
// 写请求日志
wlog($hashArray, 'hashString'.$k);
self::$wechatMsg['hashCount'] +=count($infohash_Dir);
self::$wechatMsg['hashCount'] += count($infohash_Dir);
// 此处优化大于一万条做种时,设置超时
if (count($infohash_Dir) > 5000) {
$connecttimeout = isset($configALL['default']['CONNECTTIMEOUT']) && $configALL['default']['CONNECTTIMEOUT']>60 ? $configALL['default']['CONNECTTIMEOUT'] : 60;
$timeout = isset($configALL['default']['TIMEOUT']) && $configALL['default']['TIMEOUT']>600 ? $configALL['default']['TIMEOUT'] : 600;
$connecttimeout = isset($configALL['default']['CONNECTTIMEOUT']) && $configALL['default']['CONNECTTIMEOUT'] > 60 ? $configALL['default']['CONNECTTIMEOUT'] : 60;
$timeout = isset($configALL['default']['TIMEOUT']) && $configALL['default']['TIMEOUT'] > 600 ? $configALL['default']['TIMEOUT'] : 600;
self::$curl->setOpt(CURLOPT_CONNECTTIMEOUT, $connecttimeout);
self::$curl->setOpt(CURLOPT_TIMEOUT, $timeout);
}
@@ -311,7 +333,7 @@ class AutoReseed
continue;
}
// 判断返回值
if (isset($res['ret']) && $res['ret']==200) {
if (isset($res['ret']) && $res['ret'] === 200) {
echo "clients_".$k." 辅种数据下载成功!!!".PHP_EOL.PHP_EOL;
echo '【提醒】未配置passkey的站点都会跳过'.PHP_EOL.PHP_EOL;
} else {
@@ -344,6 +366,21 @@ class AutoReseed
// 种子页规则
$download_page = str_replace('{}', $torrent_id, self::$sites[$sid]['download_page']);
// 辅种检查规则 2020年12月12日新增
if (!is_array(self::$sites[$sid]['reseed_check'])) {
// 初始化
if (!empty(self::$sites[$sid]['reseed_check'])) {
$reseed_check = explode(',', self::$sites[$sid]['reseed_check']);
array_walk($reseed_check, function (&$v, $k) {
$v = trim($v);
});
self::$sites[$sid]['reseed_check'] = $reseed_check;
} else {
self::$sites[$sid]['reseed_check'] = [];
}
}
$reseed_check = self::$sites[$sid]['reseed_check']; // 赋值
// 临时种子连接(会写入辅种日志)
$_url = $protocol . self::$sites[$sid]['base_url']. '/' .$download_page;
/**
@@ -355,7 +392,7 @@ class AutoReseed
/**
* 种子推送方式区分
*/
if (in_array($siteName, self::$cookieCheck)) {
if (in_array('cookie', $reseed_check)) {
// 特殊站点:种子元数据推送给下载器
$reseedPass = false; // 标志:跳过辅种
$cookie = trim($configALL[$siteName]['cookie']);
@@ -488,7 +525,7 @@ class AutoReseed
}
$downloadUrl = $_url;
} else {
$url = self::getTorrentUrl($siteName, $_url);
$url = self::getTorrentUrl($siteName, $sid, $_url);
$downloadUrl = $url;
}
@@ -583,7 +620,7 @@ class AutoReseed
}
echo "正在从下载器 clients_".$k." 获取种子哈希……".PHP_EOL;
$move = []; // 客户端做种列表 传址
$hashArray = self::$links[$k]['rpc']->getList($move);
$hashArray = self::$links[$k]['rpc']->all($move);
if (empty($hashArray)) {
// 失败
continue;
@@ -614,6 +651,7 @@ class AutoReseed
}
// 种子目录:脚本要能够读取到
$path = self::$links[$k]['BT_backup'];
$torrentPath = '';
// 待删除种子
$torrentDelete = '';
// 获取种子原文件的实际路径
@@ -637,7 +675,6 @@ class AutoReseed
$torrentDelete = $info_hash;
break;
default:
# code...
break;
}
if (!is_file($torrentPath)) {
@@ -659,7 +696,6 @@ class AutoReseed
if (isset($configALL['default']['move']['skip_check']) && $configALL['default']['move']['skip_check'] === 1) {
$extra_options['skip_checking'] = "true"; //转移成功,跳校验
}
} else {
}
// 添加转移任务成功返回true
@@ -702,20 +738,19 @@ class AutoReseed
$torrent_id = $torrent['torrent_id'];
$info_hash = $torrent['info_hash'];
$siteName = self::$sites[$sid]['site'];
// passkey检测 [优先检查passkey排除用户没有的站点]
if (empty($configALL[$siteName]) || empty($configALL[$siteName]['passkey'])) {
//echo '-------因当前' .$siteName. "站点未设置passkey已跳过".PHP_EOL.PHP_EOL;
self::$wechatMsg['reseedSkip']++;
return false;
} else {
echo "clients_".$k."正在辅种... {$siteName}".PHP_EOL;
}
// cookie检测
if (in_array($siteName, self::$cookieCheck) && empty($configALL[$siteName]['cookie'])) {
echo '-------因当前' .$siteName. '站点未设置cookie已跳过' .PHP_EOL.PHP_EOL;
self::$wechatMsg['reseedSkip']++;
return false;
$reseed_check = self::$sites[$sid]['reseed_check'];
if ($reseed_check && is_array($reseed_check)) {
// 循环检查所有项目
foreach ($reseed_check as $item) {
echo "clients_".$k."正在循环检查所有项目... {$siteName}".PHP_EOL;
$item = ($item === 'uid' ? 'id' : $item); // 兼容性处理
if (empty($configALL[$siteName]) || empty($configALL[$siteName][$item])) {
$msg = '-------因当前' .$siteName. "站点未设置".$item.",已跳过!!".PHP_EOL.PHP_EOL;
echo $msg;
self::$wechatMsg['reseedSkip']++;
return false;
}
}
}
// 重复做种检测
if (isset($infohash_Dir[$info_hash])) {
@@ -725,7 +760,7 @@ class AutoReseed
}
// 历史添加检测
if (is_file(self::$cacheHash . $info_hash.'.txt')) {
echo '-------当前种子上次辅种已成功添加,已跳过! '.$_url.PHP_EOL.PHP_EOL;
echo '-------当前种子上次辅种已成功添加【'.self::$cacheHash . $info_hash.'】,已跳过! '.$_url.PHP_EOL.PHP_EOL;
self::$wechatMsg['reseedPass']++;
return false;
}
@@ -795,14 +830,16 @@ class AutoReseed
}
return empty($infohash_Dir) ? true : false;
}
/**
* 实际路径与相对路径之间互相转换
* @param string $path
* @return string | null string转换成功
*/
private static function pathReplace($path = '')
{
global $configALL;
$type = $configALL['default']['move']['type'];
$type = intval($configALL['default']['move']['type']);
$pathArray = $configALL['default']['move']['path'];
$path = rtrim($path, DIRECTORY_SEPARATOR); // 提高Windows转移兼容性
switch ($type) {
@@ -844,11 +881,13 @@ class AutoReseed
global $configALL;
$path = rtrim($path, DIRECTORY_SEPARATOR); // 提高Windows转移兼容性
// 转移过滤器、选择器 David/2020年7月11日
$path_filter = isset($configALL['default']['move']['path_filter']) && !empty($configALL['default']['move']['path_filter']) ? $configALL['default']['move']['path_filter'] : null;
$path_selector = isset($configALL['default']['move']['path_selector']) && !empty($configALL['default']['move']['path_selector']) ? $configALL['default']['move']['path_selector'] : null;
$path_filter = !empty($configALL['default']['move']['path_filter']) ? $configALL['default']['move']['path_filter'] : null;
$path_selector = !empty($configALL['default']['move']['path_selector']) ? $configALL['default']['move']['path_selector'] : null;
if (\is_null($path_filter) && \is_null($path_selector)) {
return false;
} elseif (\is_null($path_filter)) {
}
if (\is_null($path_filter)) {
//选择器
if (\is_array($path_selector)) {
foreach ($path_selector as $pathName) {
@@ -896,27 +935,29 @@ class AutoReseed
/**
* 获取站点种子的URL
* @param string $site
* @param int $sid
* @param string $url
* @return string 带host的完整种子下载连接
*/
private static function getTorrentUrl($site = '', $url = '')
private static function getTorrentUrl($site = '', $sid = 0, $url = '')
{
global $configALL;
// 兼容旧配置,进行补全
if (isset($configALL[$site]['passkey']) && $configALL[$site]['passkey']) {
if (empty($configALL[$site]['url_replace'])) {
$configALL[$site]['url_replace'] = array('{passkey}' => trim($configALL[$site]['passkey']));
}
if (empty($configALL[$site]['url_join'])) {
$configALL[$site]['url_join'] = array();
if (in_array($site, array('m-team','mocat','hdbd'))) {
if (isset($configALL[$site]['ip_type'])) {
$configALL[$site]['url_join'][] = $configALL[$site]['ip_type'].'=1';
}
$configALL[$site]['url_join'][] = 'https=1';
// 注入URL替换规则
if (in_array($site, self::$recommend)) {
$url = self::getRecommendTorrentUrl($site, $url);
} else {
$reseed_check = self::$sites[$sid]['reseed_check'];
if ($reseed_check && is_array($reseed_check)) {
$replace = [];
foreach ($reseed_check as $value) {
$value = ($value === 'uid' ? 'id' : $value); // 兼容性处理
$key = '{' . $value .'}';
$replace[$key] = empty($configALL[$site][$value]) ? '' : $configALL[$site][$value];
}
$configALL[$site]['url_replace'] = $replace;
}
}
// 通用操作:替换
if (isset($configALL[$site]['url_replace']) && $configALL[$site]['url_replace']) {
$url = strtr($url, $configALL[$site]['url_replace']);
@@ -927,6 +968,101 @@ class AutoReseed
}
return $url;
}
/**
* 注入合作站种子的URL规则
* @param string $site
* @param string $url
* @return string
*/
private static function getRecommendTorrentUrl($site = '', $url = '')
{
global $configALL;
if (in_array($site, self::$recommend)) {
$now = time();
$uid = isset($configALL[$site]['id']) ? $configALL[$site]['id'] : 0;
$pk = isset($configALL[$site]['passkey']) ? trim($configALL[$site]['passkey']) : $now;
$hash = md5(trim($pk));
$signString = self::getDownloadTorrentSign($site); // 检查签名有效期,如果过期获取新的签名
switch ($site) {
case 'ourbits':
// 兼容旧版本的IYUU
if ($uid) {
$url = str_replace('passkey={passkey}', 'uid={uid}&hash={hash}', $url);
}
// TODO... 注入流控规则 60S/20pcs、3600S/100pcs
break;
default:
break;
}
// 注入替换规则
$replace = [
'{uid}' => $uid,
'{hash}'=> $hash,
'{passkey}' => $pk, // 兼容旧版本的IYUU
];
$configALL[$site]['url_replace'] = $replace;
// 注入拼接规则
if (empty($configALL[$site]['url_join'])) {
$configALL[$site]['runtime_url_join'] = []; //保存用户配置规则
$configALL[$site]['url_join'] = array($signString);
} else {
// 用户已配置过url_join 1.先保存用户原来的规则2.恢复规则3.注入签名规则
if (!isset($configALL[$site]['runtime_url_join'])) {
$configALL[$site]['runtime_url_join'] = $configALL[$site]['url_join']; //保存用户配置规则
} else {
$configALL[$site]['url_join'] = $configALL[$site]['runtime_url_join']; //恢复用户配置规则
}
$configALL[$site]['url_join'][] = $signString;
}
}
return $url;
}
/**
* 获取下载合作站种子的签名
* @descr 检查签名有效期,如果过期将获取新的签名
* @param string $site
* @return string
*/
private static function getDownloadTorrentSign($site = '')
{
global $configALL;
$signKEY = 'signString';
$expireKEY = 'signExpire';
if (isset($configALL[$site][$signKEY]) && isset($configALL[$site][$expireKEY]) && ($configALL[$site][$expireKEY] > time())) {
return $configALL[$site][$signKEY]; // 缓存在有效期内,直接返回
}
// 请求IYUU获取签名
$data = [
'sign' => $configALL['iyuu.cn'],
'timestamp' => time(),
'version' => self::VER,
'site' => $site,
'uid' => isset($configALL[$site]['id']) ? $configALL[$site]['id'] : 0,
];
$res = self::$curl->get(self::$apiUrl . self::$endpoints['getSign'], $data);
$ret = json_decode($res->response, true);
$signString = '';
if (isset($ret['ret']) && $ret['ret'] === 200) {
if (isset($ret['data'][$signKEY]) && isset($ret['data']['expire'])) {
$signString = $ret['data'][$signKEY];
$expire = $ret['data']['expire'];
$configALL[$site][$signKEY] = $signString;
$configALL[$site][$expireKEY] = time() + $expire - 60; // 提前60秒过期
}
} else {
echo $site.' 很抱歉请求IYUU辅种签名时失败啦请稍后重新尝试辅种详情'.$ret['msg'].PHP_EOL;
}
return $signString;
}
/**
* 微信模板消息拼接方法
* @return string 发送情况json
@@ -935,7 +1071,7 @@ class AutoReseed
{
global $configALL;
if (isset($configALL['notify_on_change']) && $configALL['notify_on_change'] && self::$wechatMsg['reseedSuccess'] == 0 && self::$wechatMsg['reseedError'] == 0) {
return;
return '';
}
$br = PHP_EOL;
$text = 'IYUU自动辅种-统计报表';

View File

@@ -1,66 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: David <367013672@qq.com>
* Date: 2020-2-14
* Time: 21:31:49
*/
namespace IYUU\Client;
abstract class AbstractClient
{
/**
* 公共方法:创建客户端实例
*/
public static function create($config = array())
{
$type = $config['type'];
$host = $config['host'];
$username = $config['username'];
$password = $config['password'];
$file = __DIR__ . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $type .'.php';
if (!is_file($file)) {
die($file.' 文件不存在');
}
$className = "\IYUU\Client\\" . $type . "\\" . $type;
if (class_exists($className)) {
echo $type." 客户端正在实例化!".PHP_EOL;
return new $className($host, $username, $password);
} else {
die($className.' 客户端不存在');
}
}
/**
* 查询Bittorrent客户端状态
*
* @return string
*/
abstract public function status();
/**
* 获取种子列表
* @return array(
'hash' => string json,
'sha1' => string,
'hashString '=> array
)
*/
abstract public function getList(&$move = array());
/**
* 添加种子连接
*/
abstract public function add($torrent_url, $save_path = '', $extra_options = array());
/**
* 添加种子原数据
*/
abstract public function add_metainfo($torrent_url, $save_path = '', $extra_options = array());
/**
* 删除种子
*/
abstract public function delete($hash, $deleteFiles = false);
}

View File

@@ -1,351 +0,0 @@
<?php
namespace IYUU\Client\qBittorrent;
use Curl\Curl;
use IYUU\Client\AbstractClient;
/**
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation
*/
class qBittorrent extends AbstractClient
{
private $debug;
private $url;
private $api_version;
private $curl;
protected $delimiter;
private $endpoints = [
'login' => [
'1' => '/login',
'2' => '/api/v2/auth/login'
],
'app_version' => [
'1' => '/version/qbittorrent',
'2' => '/api/v2/app/version'
],
'api_version' => [
'1' => '/version/api',
'2' => '/api/v2/app/webapiVersion'
],
'build_info' => [
'1' => null,
'2' => '/api/v2/app/buildInfo'
],
'preferences' => [
'1' => null,
'2' => '/api/v2/app/preferences'
],
'setPreferences' => [
'1' => null,
'2' => '/api/v2/app/setPreferences'
],
'defaultSavePath' => [
'1' => null,
'2' => '/api/v2/app/defaultSavePath'
],
'torrent_list' => [
'1' => null,
'2' => '/api/v2/torrents/info'
],
'torrent_add' => [
'1' => null,
'2' => '/api/v2/torrents/add'
],
'torrent_delete' => [
'1' => null,
'2' => '/api/v2/torrents/delete'
],
'torrent_pause' => [
'1' => null,
'2' => '/api/v2/torrents/pause'
],
'torrent_resume' => [
'1' => null,
'2' => '/api/v2/torrents/resume'
],
'set_torrent_location' => [
'1' => null,
'2' => '/api/v2/torrents/setLocation'
],
'maindata' => [
'1' => null,
'2' => '/api/v2/sync/maindata'
]
];
public function __construct($url='', $username='', $password='', $api_version = 2, $debug = false)
{
$this->debug = $debug;
$this->url = rtrim($url, '/');
$this->username = $username;
$this->password = $password;
$this->api_version = $api_version;
$this->curl = new Curl();
$this->curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); // 禁止验证证书
$this->curl->setOpt(CURLOPT_SSL_VERIFYHOST, 2); // 不检查证书
$this->curl->setOpt(CURLOPT_CONNECTTIMEOUT, 60); // 超时
$this->curl->setOpt(CURLOPT_TIMEOUT, 600); // 超时
// Authenticate and get cookie, else throw exception
if (!$this->authenticate()) {
throw new \Exception("qBittorrent Unable to authenticate with Web Api.");
}
}
public function appVersion()
{
return $this->getData('app_version');
}
public function apiVersion()
{
return $this->getData('api_version');
}
public function buildInfo()
{
return $this->getData('build_info');
}
public function preferences($data = null)
{
if (!empty($data)) {
return $this->postData('setPreferences', ['json' => json_encode($data)]);
}
return $this->getData('preferences');
}
public function torrentList()
{
return $this->getData('torrent_list');
}
/**
* @param array $extra_options
array(
'urls' => '',
'savepath' => '',
'cookie' => '',
'category' => '',
'skip_checking' => true,
'paused' => true,
'root_folder' => true,
)
* @return array
*/
public function add($torrent_url, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['urls'] = $torrent_url;
#$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】
$post_data = $this->buildUrls($extra_options);
#p($post_data);
// 设置请求头
$this->curl->setHeader('Content-Type', 'multipart/form-data; boundary='.$this->delimiter);
$this->curl->setHeader('Content-Length', strlen($post_data));
return $this->postData('torrent_add', $post_data);
}
public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['torrents'] = $torrent_metainfo;
#$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】
$post_data = $this->buildData($extra_options);
// 设置请求头
$this->curl->setHeader('Content-Type', 'multipart/form-data; boundary='.$this->delimiter);
$this->curl->setHeader('Content-Length', strlen($post_data));
return $this->postData('torrent_add', $post_data);
}
public function torrentDeleteAll($deleteFiles = false)
{
$torrents = json_decode($this->torrentList());
$response = '';
foreach ($torrents as $torrent) {
$response .= $this->delete($torrent->hash, $deleteFiles);
}
return $response;
}
public function torrentPause($hash)
{
return $this->postData('torrent_pause', ['hashes' => $hash]);
}
public function torrentResume($hash)
{
return $this->postData('torrent_resume', ['hashes' => $hash]);
}
public function setTorrentLocation($hash, $location)
{
return $this->postData('set_torrent_location', ['hashes' => $hash, 'location' => $location]);
}
private function getData($endpoint)
{
$this->curl->get($this->url . $this->endpoints[$endpoint][$this->api_version]);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
}
if ($this->curl->error) {
return $this->errorMessage();
}
return $this->curl->response;
}
private function postData($endpoint, $data)
{
$this->curl->post($this->url . $this->endpoints[$endpoint][$this->api_version], $data);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
}
if ($this->curl->error) {
return $this->errorMessage();
}
return $this->curl->response;
}
private function authenticate()
{
$this->curl->post($this->url . $this->endpoints['login'][$this->api_version], [
'username' => $this->username,
'password' => $this->password
]);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
}
// Find authentication cookie and set in curl connection
foreach ($this->curl->response_headers as $header) {
if (preg_match('/SID=(\S[^;]+)/', $header, $matches)) {
$qb415 = '; QB_'.$matches[0]; // 兼容qBittorrent v4.1.5[小钢炮等]
$this->curl->setHeader('Cookie', $matches[0].$qb415);
return true;
}
};
return false;
}
private function errorMessage()
{
return 'Curl Error Code: ' . $this->curl->error_code . ' (' . $this->curl->response . ')';
}
/**
* 拼接种子urls multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
*/
private function buildUrls($param)
{
$this->delimiter = uniqid();
$eol = "\r\n";
$data = '';
// 拼接文件流
foreach ($param as $name => $content) {
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' .$name. '"' . $eol . $eol;
$data .= $content . $eol;
}
$data .= "--" . $this->delimiter . "--" . $eol;
return $data;
}
/**
* 拼接种子上传文件流 multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
*/
private function buildData($param)
{
$this->delimiter = uniqid();
$eol = "\r\n";
$data = '';
// 拼接文件流
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' .$param['name']. '"; filename="'.$param['filename'].'"' . $eol;
$data .= 'Content-Type: application/x-bittorrent' . $eol . $eol;
$data .= $param['torrents'] . $eol;
unset($param['name']);
unset($param['filename']);
unset($param['torrents']);
if (!empty($param)) {
foreach ($param as $name => $content) {
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' . $name . '"' . $eol . $eol;
$data .= $content . $eol;
}
}
$data .= "--" . $this->delimiter . "--" . $eol;
return $data;
}
/**
* 抽象方法,子类实现
*/
public function status()
{
return $this->appVersion();
}
/**
* 抽象方法,子类实现
*/
public function getList(&$move = array())
{
$result = $this->getData('torrent_list');
$res = json_decode($result, true);
if (empty($res)) {
echo "获取种子列表失败可能qBittorrent暂时无响应请稍后重试".PHP_EOL;
return array();
}
// 过滤,只保留正常做种
$res = array_filter($res, function ($v) {
if (isset($v['state']) && in_array($v['state'], array('uploading','stalledUP','pausedUP','queuedUP','checkingUP','forcedUP'))) {
return true;
}
return false;
}, ARRAY_FILTER_USE_BOTH);
if (empty($res)) {
echo "未获取到正常做种数据,请多保种,然后重试!".PHP_EOL;
return array();
}
// 提取数组hashString
$info_hash = array_column($res, 'hash');
// 升序排序
sort($info_hash);
$json = json_encode($info_hash, JSON_UNESCAPED_UNICODE);
// 去重 应该从文件读入,防止重复提交
$sha1 = sha1($json);
// 组装返回数据
$hashArray['hash'] = $json;
$hashArray['sha1'] = $sha1;
// 变换数组hashString为键
$hashArray['hashString'] = array_column($res, "save_path", 'hash');
return $hashArray;
}
/**
* 抽象方法,子类实现
*/
public function delete($hash='', $deleteFiles = false)
{
return $this->postData('torrent_delete', ['hashes' => $hash, 'deleteFiles' => $deleteFiles ? 'true':'false']);
}
}

View File

@@ -1,48 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Rhilip
* Date: 1/17/2020
* Time: 2020
*/
namespace IYUU\Client\transmission;
/**
* This is the type of exception the TransmissionRPC class will throw
*/
class TransmissionRPCException extends \Exception
{
/**
* Exception: Invalid arguments
*/
const E_INVALIDARG = -1;
/**
* Exception: Invalid Session-Id
*/
const E_SESSIONID = -2;
/**
* Exception: Error while connecting
*/
const E_CONNECTION = -3;
/**
* Exception: Error 401 returned, unauthorized
*/
const E_AUTHENTICATION = -4;
/**
* Exception constructor
*/
public function __construct($message = null, $code = 0, \Exception $previous = null)
{
// PHP version 5.3.0 and above support Exception linking
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
parent::__construct($message, $code, $previous);
} else {
parent::__construct($message, $code);
}
}
}

View File

@@ -1,763 +0,0 @@
<?php
/**
* Transmission bittorrent client/daemon RPC communication class
* Copyright (C) 2010 Johan Adriaans <johan.adriaans@gmail.com>,
* Bryce Chidester <bryce@cobryce.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* PHP version specific information
* version_compare() (PHP 4 >= 4.1.0, PHP 5)
* ctype_digit() (PHP 4 >= 4.0.4, PHP 5)
* stream_context_create (PHP 4 >= 4.3.0, PHP 5)
* PHP Class support (PHP 5) (PHP 4 might work, untested)
*/
namespace IYUU\Client\transmission;
use IYUU\Client\AbstractClient;
/**
* A friendly little version check...
*/
if (version_compare(PHP_VERSION, '5.2.10', '<')) {
die("The TransmissionRPC class requires PHP version 5.2.10 or above." . PHP_EOL);
}
/**
* Transmission bittorrent client/daemon RPC communication class
*
* Usage example:
* <code>
* $rpc = new TransmissionRPC($rpc_url);
* $result = $rpc->add_file( $url_or_path_to_torrent, $target_folder );
* </code>
*
*/
class transmission extends AbstractClient
{
/**
* User agent used in all http communication
*/
const HTTP_UA = 'TransmissionRPC for PHP/0.3';
/**
* The URL to the bittorent client you want to communicate with
* the port (default: 9091) can be set in you Transmission preferences
* @var string
*/
public $url = '';
/**
* If your Transmission RPC requires authentication, supply username here
* @var string
*/
public $username = '';
/**
* If your Transmission RPC requires authentication, supply password here
* @var string
*/
public $password = '';
/**
* Print debugging information, default is off
* @var bool
*/
public $debug = false;
/**
* Transmission RPC version
* @var int
*/
protected $rpc_version = 0;
/**
* Transmission uses a session id to prevent CSRF attacks
* @var string
*/
protected $session_id = '';
/**
* Default values for stream context
* @var array
*/
private $default_context_opts = array(
'http' => array(
'user_agent' => self::HTTP_UA,
'timeout' => '60', // Don't want to be too slow
'ignore_errors' => true, // Leave the error parsing/handling to the code
),
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
)
);
/**
* Constants for torrent status
*/
const TR_STATUS_STOPPED = 0;
const TR_STATUS_CHECK_WAIT = 1;
const TR_STATUS_CHECK = 2;
const TR_STATUS_DOWNLOAD_WAIT = 3;
const TR_STATUS_DOWNLOAD = 4;
const TR_STATUS_SEED_WAIT = 5;
const TR_STATUS_SEED = 6;
const RPC_LT_14_TR_STATUS_CHECK_WAIT = 1;
const RPC_LT_14_TR_STATUS_CHECK = 2;
const RPC_LT_14_TR_STATUS_DOWNLOAD = 4;
const RPC_LT_14_TR_STATUS_SEED = 8;
const RPC_LT_14_TR_STATUS_STOPPED = 16;
/**
* Takes the connection parameters
*
* @param string $url
* @param string $username
* @param string $password
*/
public function __construct($url = 'http://127.0.0.1:9091/transmission/rpc', $username = null, $password = null)
{
$this->url = rtrim($url, '/');
$this->username = $username;
$this->password = $password;
}
/**
* Start one or more torrents
*
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function start($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-start", $request);
}
/**
* Stop one or more torrents
*
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function stop($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-stop", $request);
}
/**
* Reannounce one or more torrents
*
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function reannounce($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-reannounce", $request);
}
/**
* Verify one or more torrents
*
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function verify($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-verify", $request);
}
/**
* Get information on torrents in transmission, if the ids parameter is
* empty all torrents will be returned. The fields array can be used to return certain
* fields. Default fields are: "id", "name", "status", "doneDate", "haveValid", "totalSize".
* See https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt for available fields
*
* @param array fields An array of return fields
* @param int|array ids A list of transmission torrent ids
*
* Request:
* {
* "arguments": {
* "fields": [ "id", "name", "totalSize" ],
* "ids": [ 7, 10 ]
* },
* "method": "torrent-get",
* "tag": 39693
* }
*
* Response:
* {
* "arguments": {
* "torrents": [
* {
* "id": 10,
* "name": "Fedora x86_64 DVD",
* "totalSize": 34983493932,
* },
* {
* "id": 7,
* "name": "Ubuntu x86_64 DVD",
* "totalSize", 9923890123,
* }
* ]
* },
* "result": "success",
* "tag": 39693
* }
* @return mixed
* @throws TransmissionRPCException
*/
public function get($ids = array(), $fields = array())
{
if (!is_array($ids)) {
$ids = array($ids);
} // Convert $ids to an array if only a single id was passed
if (count($fields) == 0) {
$fields = array("id", "name", "status", "doneDate", "haveValid", "totalSize");
} // Defaults
$request = array(
"fields" => $fields,
"ids" => $ids
);
return $this->request("torrent-get", $request);
}
/**
* Set properties on one or more torrents, available fields are:
* "bandwidthPriority" | number this torrent's bandwidth tr_priority_t
* "downloadLimit" | number maximum download speed (in K/s)
* "downloadLimited" | boolean true if "downloadLimit" is honored
* "files-wanted" | array indices of file(s) to download
* "files-unwanted" | array indices of file(s) to not download
* "honorsSessionLimits" | boolean true if session upload limits are honored
* "ids" | array torrent list, as described in 3.1
* "location" | string new location of the torrent's content
* "peer-limit" | number maximum number of peers
* "priority-high" | array indices of high-priority file(s)
* "priority-low" | array indices of low-priority file(s)
* "priority-normal" | array indices of normal-priority file(s)
* "seedRatioLimit" | double session seeding ratio
* "seedRatioMode" | number which ratio to use. See tr_ratiolimit
* "uploadLimit" | number maximum upload speed (in K/s)
* "uploadLimited" | boolean true if "uploadLimit" is honored
* See https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt for more information
*
* @param array arguments An associative array of arguments to set
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function set($ids = array(), $arguments = array())
{
// See https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt for available fields
if (!is_array($ids)) {
$ids = array($ids);
} // Convert $ids to an array if only a single id was passed
if (!isset($arguments['ids'])) {
$arguments['ids'] = $ids;
} // Any $ids given in $arguments overrides the method parameter
return $this->request("torrent-set", $arguments);
}
/**
* Add a new torrent
*
* Available extra options:
* key | value type & description
* ---------------------+-------------------------------------------------
* "download-dir" | string path to download the torrent to
* "filename" | string filename or URL of the .torrent file
* "metainfo" | string base64-encoded .torrent content
* "paused" | boolean if true, don't start the torrent
* "peer-limit" | number maximum number of peers
* "bandwidthPriority" | number torrent's bandwidth tr_priority_t
* "files-wanted" | array indices of file(s) to download
* "files-unwanted" | array indices of file(s) to not download
* "priority-high" | array indices of high-priority file(s)
* "priority-low" | array indices of low-priority file(s)
* "priority-normal" | array indices of normal-priority file(s)
*
* Either "filename" OR "metainfo" MUST be included.
* All other arguments are optional.
*
* @param string $torrent_location The URL or path to the torrent file
* @param string $save_path Folder to save torrent in
* @param array $extra_options Optional extra torrent options
* @return mixed
* @throws TransmissionRPCException
*/
public function add_file($torrent_location, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['download-dir'] = $save_path;
}
$extra_options['filename'] = $torrent_location;
return $this->request("torrent-add", $extra_options);
}
/* Add a new torrent using a file path or a URL (For backwards compatibility)
* @param torrent_location The URL or path to the torrent file
* @param save_path Folder to save torrent in
* @param extra options Optional extra torrent options
*/
public function add($torrent_location, $save_path = '', $extra_options = array())
{
return $this->add_file($torrent_location, $save_path, $extra_options);
}
/**
* Add a torrent using the raw torrent data
*
* @param string $torrent_metainfo The raw, unencoded contents (metainfo) of a torrent
* @param string $save_path Folder to save torrent in
* @param array $extra_options Optional extra torrent options
* @return mixed
* @throws TransmissionRPCException
*/
public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['download-dir'] = $save_path;
}
$extra_options['metainfo'] = base64_encode($torrent_metainfo);
return $this->request("torrent-add", $extra_options);
}
/**
* Remove torrent from transmission
*
* @param bool delete_local_data Also remove local data?
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws TransmissionRPCException
*/
public function delete($ids, $delete_local_data = false)
{
if (!is_array($ids)) {
$ids = array($ids);
} // Convert $ids to an array if only a single id was passed
$request = array(
"ids" => $ids,
"delete-local-data" => $delete_local_data
);
return $this->request("torrent-remove", $request);
}
/**
* Move local storage location
*
* @param int|array ids A list of transmission torrent ids
* @param string target_location The new storage location
* @param string move_existing_data Move existing data or scan new location for available data
* @return mixed
* @throws TransmissionRPCException
*/
public function move($ids, $target_location, $move_existing_data = true)
{
if (!is_array($ids)) {
$ids = array($ids);
} // Convert $ids to an array if only a single id was passed
$request = array(
"ids" => $ids,
"location" => $target_location,
"move" => $move_existing_data
);
return $this->request("torrent-set-location", $request);
}
/**
* 3.7. Renaming a Torrent's Path
*
* Method name: "torrent-rename-path"
*
* For more information on the use of this function, see the transmission.h
* documentation of tr_torrentRenamePath(). In particular, note that if this
* call succeeds you'll want to update the torrent's "files" and "name" field
* with torrent-get.
*
* Request arguments:
*
* string | value type & description
* ---------------------------------+-------------------------------------------------
* "ids" | array the torrent torrent list, as described in 3.1
* | (must only be 1 torrent)
* "path" | string the path to the file or folder that will be renamed
* "name" | string the file or folder's new name
* Response arguments: "path", "name", and "id", holding the torrent ID integer
*
* @param int|array ids A 1-element list of transmission torrent ids
* @param string path The path to the file or folder that will be renamed
* @param string name The file or folder's new name
* @return mixed
* @throws TransmissionRPCException
*/
public function rename($ids, $path, $name)
{
if (!is_array($ids)) {
$ids = array($ids);
} // Convert $id to an array if only a single id was passed
if (count($ids) !== 1) {
throw new TransmissionRPCException('A single id is accepted', TransmissionRPCException::E_INVALIDARG);
}
$request = array(
"ids" => $ids,
"path" => $path,
"name" => $name
);
return $this->request("torrent-rename-path", $request);
}
/**
* Retrieve session statistics
*
* @returns array of statistics
*/
public function sstats()
{
return $this->request("session-stats", array());
}
/**
* Retrieve all session variables
*
* @returns array of session information
*/
public function sget()
{
return $this->request("session-get", array());
}
/**
* Set session variable(s)
*
* @param array of session variables to set
* @return mixed
* @throws TransmissionRPCException
*/
public function sset($arguments)
{
return $this->request("session-set", $arguments);
}
/**
* Return the interpretation of the torrent status
*
* @param int The integer "torrent status"
* @returns string The translated meaning
* @return string
*/
public function getStatusString($intstatus)
{
if ($this->rpc_version < 14) {
if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK) {
return "Verifying local files";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_DOWNLOAD) {
return "Downloading";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_SEED) {
return "Seeding";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_STOPPED) {
return "Stopped";
}
} else {
if ($intstatus == self::TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files";
}
if ($intstatus == self::TR_STATUS_CHECK) {
return "Verifying local files";
}
if ($intstatus == self::TR_STATUS_DOWNLOAD) {
return "Downloading";
}
if ($intstatus == self::TR_STATUS_SEED) {
return "Seeding";
}
if ($intstatus == self::TR_STATUS_STOPPED) {
return "Stopped";
}
if ($intstatus == self::TR_STATUS_SEED_WAIT) {
return "Queued for seeding";
}
if ($intstatus == self::TR_STATUS_DOWNLOAD_WAIT) {
return "Queued for download";
}
}
return "Unknown";
}
/**
* Here be dragons (Internal methods)
*/
/**
* Clean up the request array. Removes any empty fields from the request
*
* @param array array The request associative array to clean
* @returns array The cleaned array
* @return array|null
*/
protected function cleanRequestData($array)
{
if (!is_array($array) || count($array) == 0) {
return null;
} // Nothing to clean
setlocale(LC_NUMERIC, 'en_US.utf8'); // Override the locale - if the system locale is wrong, then 12.34 will encode as 12,34 which is invalid JSON
foreach ($array as $index => $value) {
if (is_object($value)) {
$array[$index] = $value->toArray();
} // Convert objects to arrays so they can be JSON encoded
if (is_array($value)) {
$array[$index] = $this->cleanRequestData($value);
} // Recursion
if (empty($value) && $value !== 0) { // Remove empty members
unset($array[$index]);
continue; // Skip the rest of the tests - they may re-add the element.
}
if (is_numeric($value)) {
$array[$index] = $value + 0;
} // Force type-casting for proper JSON encoding (+0 is a cheap way to maintain int/float/etc)
if (is_bool($value)) {
$array[$index] = ($value ? 1 : 0);
} // Store boolean values as 0 or 1
if (is_string($value)) {
$type = mb_detect_encoding($value, "auto");
if ($type !== 'UTF-8') {
$array[$index] = mb_convert_encoding($value, "UTF-8");
//utf8_encode( $value ); // Make sure all data is UTF-8 encoded for Transmission
}
}
}
return $array;
}
/**
* 执行 rpc 请求
*
* @param string $method 请求类型/方法, 详见 $this->allowMethods
* @param array $arguments 附加参数, 可选
* @return array
* @throws TransmissionRPCException
*/
protected function request($method, $arguments = array())
{
// Check the parameters
if (!is_scalar($method)) {
throw new TransmissionRPCException('Method name has no scalar value', TransmissionRPCException::E_INVALIDARG);
}
if (!is_array($arguments)) {
throw new TransmissionRPCException('Arguments must be given as array', TransmissionRPCException::E_INVALIDARG);
}
$arguments = $this->cleanRequestData($arguments); // Sanitize input
// Grab the X-Transmission-Session-Id if we don't have it already
if (!$this->session_id) {
if (!$this->GetSessionID()) {
throw new TransmissionRPCException('Unable to acquire X-Transmission-Session-Id', TransmissionRPCException::E_SESSIONID);
}
}
$data = array(
'method' => $method,
'arguments' => $arguments
);
$header = array(
'Content-Type: application/json',
'Authorization: Basic ' . base64_encode(sprintf("%s:%s", $this->username, $this->password)),
'X-Transmission-Session-Id: ' . $this->session_id
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
if (stripos($this->url, 'https://') === 0) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁止验证证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 不检查证书
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 600);
$content = curl_exec($ch);
curl_close($ch);
if (!$content) {
$content = array('result' => 'failed');
}
return json_decode($content, true);
}
/**
* Performs an empty GET on the Transmission RPC to get the X-Transmission-Session-Id
* and store it in $this->session_id
*
* @return string
* @throws TransmissionRPCException
*/
public function GetSessionID()
{
if (!$this->url) {
throw new TransmissionRPCException("Class must be initialized before GetSessionID() can be called.", TransmissionRPCException::E_INVALIDARG);
}
// Setup the context
$contextopts = $this->default_context_opts; // Start with the defaults
// Make sure it's blank/empty (reset)
$this->session_id = null;
// Setup authentication (if provided)
if ($this->username && $this->password) {
$contextopts['http']['header'] = sprintf("Authorization: Basic %s\r\n", base64_encode($this->username . ':' . $this->password));
}
if ($this->debug) {
echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream context created with options:" .
PHP_EOL . print_r($contextopts, true);
}
$context = stream_context_create($contextopts); // Create the context for this request
if (!$fp = @fopen($this->url, 'r', false, $context)) { // Open a filepointer to the data, and use fgets to get the result
throw new TransmissionRPCException('Unable to connect to ' . $this->url, TransmissionRPCException::E_CONNECTION);
}
// Check the response (headers etc)
$stream_meta = stream_get_meta_data($fp);
fclose($fp);
if ($this->debug) {
echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream meta info: " .
PHP_EOL . print_r($stream_meta, true);
}
if ($stream_meta['timed_out']) {
throw new TransmissionRPCException("Timed out connecting to {$this->url}", TransmissionRPCException::E_CONNECTION);
}
if (substr($stream_meta['wrapper_data'][0], 9, 3) == "401") {
throw new TransmissionRPCException("Invalid username/password.", TransmissionRPCException::E_AUTHENTICATION);
} elseif (substr($stream_meta['wrapper_data'][0], 9, 3) == "409") { // This is what we're hoping to find
// Loop through the returned headers and extract the X-Transmission-Session-Id
foreach ($stream_meta['wrapper_data'] as $header) {
if (strpos($header, 'X-Transmission-Session-Id: ') === 0) {
if ($this->debug) {
echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Session-Id header: " .
PHP_EOL . print_r($header, true);
}
$this->session_id = trim(substr($header, 27));
break;
}
}
if (!$this->session_id) { // Didn't find a session_id
throw new TransmissionRPCException("Unable to retrieve X-Transmission-Session-Id", TransmissionRPCException::E_SESSIONID);
}
} else {
throw new TransmissionRPCException("Unexpected response from Transmission RPC: " . $stream_meta['wrapper_data'][0]);
}
return $this->session_id;
}
/**
* 抽象方法,子类实现
*/
public function status()
{
$rs = $this->sstats();
return isset($rs['result']) ? $rs['result'] : 'error';
}
/**
* 抽象方法,子类实现
*/
public function getList(&$move = array())
{
$ids = array();
$fields = array( "id", "status", "name", "hashString", "downloadDir", "torrentFile" );
$res = $this->get($ids, $fields);
if (isset($res['result']) && $res['result'] == 'success') {
// 成功
} else {
// 失败
echo "获取种子列表失败可能transmission暂时无响应请稍后重试".PHP_EOL;
return array();
}
if (empty($res['arguments']['torrents'])) {
echo "未获取到正常做种数据,请多保种,然后重试!".PHP_EOL;
return array();
}
$res = $res['arguments']['torrents'];
// 过滤,只保留正常做种
$res = array_filter($res, function ($v) {
return isset($v['status']) && $v['status']===6;
}, ARRAY_FILTER_USE_BOTH);
if (empty($res)) {
echo "未获取到正常做种数据,请多保种,然后重试!".PHP_EOL;
return array();
}
// 提取数组hashString
$info_hash = array_column($res, 'hashString');
// 升序排序
sort($info_hash);
$json = json_encode($info_hash, JSON_UNESCAPED_UNICODE);
// 去重 应该从文件读入,防止重复提交
$sha1 = sha1($json);
// 组装返回数据
$hashArray['hash'] = $json;
$hashArray['sha1'] = $sha1;
// 变换数组hashString为键
$hashArray['hashString'] = array_column($res, "downloadDir", 'hashString');
$move = array_column($res, null, 'hashString');
return $hashArray;
}
}

View File

@@ -100,9 +100,10 @@ class IFile
/**
* @brief 创建文件夹
* @param String $path 路径
* @param int $chmod 文件夹权限
* @param String $path 路径
* @param int $chmod 文件夹权限
* @note $chmod 参数不能是字符串(加引号)否则linux会出现权限问题
* @return bool
*/
public static function mkdir($path, $chmod=0777)
{
@@ -113,7 +114,7 @@ class IFile
* @brief 复制文件
* @param String $from 源文件路径
* @param String $to 目标文件路径
* @param String $mod 操作模式c:复制(默认); x:剪切(删除$from文件)
* @param String $mode 操作模式c:复制(默认); x:剪切(删除$from文件)
* @return bool 操作结果 true:成功; false:失败;
*/
public static function copy($from, $to, $mode = 'c')
@@ -178,7 +179,7 @@ class IFile
/**
* @brief 获取文件类型
* @param String $fileName 文件名
* @return String $filetype 文件类型
* @return String|array $filetype 文件类型
* @note 如果文件不存在返回false,如果文件后缀名不在识别列表之内返回NULL对于docx及elsx格式文档识别在会出现识别为ZIP格式的错误这是office2007的bug目前尚未修复请谨慎使用
*/
public static function getFileType($fileName)

View File

@@ -8,93 +8,94 @@ use Curl\Curl;
*/
class Oauth
{
// 合作的站点
public static $sites = ['ourbits','hddolby','hdhome','pthome','chdbits'];
// 爱语飞飞token
public static $token = '';
// 合作站点用户id
public static $user_id = 0;
// 合作站点密钥
public static $passkey = '';
// 合作站名字
public static $site = '';
// 登录缓存路径
public static $SiteLoginCache = ROOT_PATH.DS.'config'.DS.'siteLoginCache_{}.json';
const SiteLoginCache = ROOT_PATH.DS.'config'.DS.'siteLoginCache_{}.json';
/**
* 从配置文件内读取爱语飞飞token作为鉴权参数
*/
public static function getSign()
{
global $configALL;
// 爱语飞飞
$token = isset($configALL['iyuu.cn']) && $configALL['iyuu.cn'] ? $configALL['iyuu.cn'] : '';
if (empty($token) || strlen($token)<46) {
echo "缺少辅种接口请求参数爱语飞飞token \n";
echo "请访问https://iyuu.cn 用微信扫码申请并填入配置文件config.php内。\n\n";
$token = empty($configALL['iyuu.cn']) ? '' : $configALL['iyuu.cn'];
if (empty($token) || strlen($token) < 46) {
echo "缺少辅种接口请求参数爱语飞飞token ".PHP_EOL;
echo "请访问https://iyuu.cn 用微信扫码申请并填入配置文件config.php内。".PHP_EOL.PHP_EOL;
exit(1);
}
return $token;
}
/**
* 用户注册与登录
* 作用在服务器端实现微信用户与合作站点用户id的关联
* 参数爱语飞飞token + 合作站点用户id + sha1(合作站点密钥passkey) + 合作站点标识
* @param string $apiUrl
* @param array $sites
* @return bool
* @throws \ErrorException
*/
public static function login($apiUrl = '', $sites = array())
{
global $configALL;
// 云端下发合作的站点标识
self::$sites = $sites ? $sites : self::$sites;
if (empty($sites)) {
die('云端下发合作站点信息失败,请稍后重试');
}
$_sites = array_column($sites, 'site');
$ret = false;
self::$token = self::getSign();
foreach (self::$sites as $name) {
if (is_file(str_replace('{}', $name, self::$SiteLoginCache))) {
$token = self::getSign();
foreach ($_sites as $k => $site) {
if (is_file(str_replace('{}', $site, self::SiteLoginCache))) {
// 存在鉴权缓存
$ret = true;
continue;
}
if (isset($configALL[$name]['passkey']) && $configALL[$name]['passkey'] && isset($configALL[$name]['id']) && $configALL[$name]['id']) {
self::$user_id = $configALL[$name]['id'];
self::$passkey = sha1($configALL[$name]['passkey']); // 避免泄露用户passkey秘钥
self::$site = $name;
if (isset($configALL[$site]['passkey']) && $configALL[$site]['passkey'] && isset($configALL[$site]['id']) && $configALL[$site]['id']) {
$user_id = $configALL[$site]['id'];
$passkey = $configALL[$site]['passkey'];
$curl = new Curl();
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
$data = [
'token' => self::$token,
'id' => self::$user_id,
'passkey'=> self::$passkey,
'site' => self::$site,
'token' => $token,
'id' => $user_id,
'passkey'=> sha1($passkey), // 避免泄露用户passkey秘钥
'site' => $site,
];
$res = $curl->get($apiUrl, $data);
p($res->response);
$rs = json_decode($res->response, true);
if (isset($rs['ret']) && $rs['ret'] == 200 && isset($rs['data']['success']) && $rs['data']['success']) {
self::setSiteLoginCache($name, $rs);
if (isset($rs['ret']) && ($rs['ret'] === 200) && isset($rs['data']['success']) && $rs['data']['success']) {
self::setSiteLoginCache($site, $rs);
$ret = true;
} else {
$msg = isset($rs['msg']) && $rs['msg'] ? $rs['msg'] : '远端服务器无响应,请稍后重试!';
$msg = isset($rs['data']['errmsg']) && $rs['data']['errmsg'] ? $rs['data']['errmsg'] : $msg;
$msg = !empty($rs['msg']) ? $rs['msg'] : '远端服务器无响应,请稍后重试!';
$msg = !empty($rs['data']['errmsg']) ? $rs['data']['errmsg'] : $msg;
echo $msg . PHP_EOL;
}
} else {
echo $name.'合作站点参数配置不完整请同时填写passkey和用户id。' . PHP_EOL;
echo $site.'合作站点参数配置不完整请同时填写passkey和用户id。' . PHP_EOL;
echo '合作站点鉴权配置请查阅https://www.iyuu.cn/archives/337/'. PHP_EOL. PHP_EOL;
}
}
return $ret;
}
/**
* 写鉴权成功缓存
* @desc 作用:减少对服务器请求,跳过鉴权提示信息;
* @param string $site
* @param array $array
* @return bool|int
*/
private static function setSiteLoginCache($key = '', $array = [])
private static function setSiteLoginCache($site = '', $array = [])
{
$json = json_encode($array, JSON_UNESCAPED_UNICODE);
$myfile = str_replace('{}', $key, self::$SiteLoginCache);
$myfile = str_replace('{}', $site, self::SiteLoginCache);
$file_pointer = @fopen($myfile, "w");
$worldsnum = @fwrite($file_pointer, $json);
@fclose($file_pointer);
return $worldsnum;
}
}

View File

@@ -197,14 +197,14 @@ function convertToMB($from)
/**
* 字节数Byte转换为KB、MB、GB、TB
*
* @param $num
* @return string
*/
function getFilesize($num)
{
$p = 0;
$format='bytes';
if ($num>0 && $num<1024) {
$p = 0;
return number_format($num).' '.$format;
}
if ($num>=1024 && $num<pow(1024, 2)) {
@@ -393,8 +393,9 @@ function sign($timestamp)
/**
* @brief 分离token中的用户uid
* token算法IYUU + uid + T + sha1(openid+time+盐)
* @param string $token 用户请求token
* @desc token算法IYUU + uid + T + sha1(openid+time+盐)
* @param string $token 用户请求token
* @return bool|string
*/
function getUid($token)
{

View File

@@ -13,7 +13,8 @@
"ext-json": "*",
"ext-mbstring": "*",
"ext-curl": "*",
"curl/curl": "^2.2"
"curl/curl": "^2.3",
"ledccn/bittorrentclient": "dev-master"
},
"autoload": {
"psr-4": {

83
composer.lock generated
View File

@@ -1,83 +0,0 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "10281f19c929443b7db18d1ab159ec63",
"packages": [
{
"name": "curl/curl",
"version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/php-mod/curl.git",
"reference": "d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-mod/curl/zipball/d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff",
"reference": "d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-curl": "*",
"php": "^5.6 | ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^5.7",
"squizlabs/php_codesniffer": "~2.1"
},
"type": "library",
"autoload": {
"psr-0": {
"Curl": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Hassan Amouhzi",
"email": "hassan@anezi.net",
"homepage": "http://hassan.amouhzi.com"
},
{
"name": "php-curl-class",
"homepage": "https://github.com/php-curl-class"
},
{
"name": "user52",
"homepage": "https://github.com/user52"
}
],
"description": "cURL class for PHP",
"homepage": "https://github.com/php-mod/curl",
"keywords": [
"curl",
"dot"
],
"time": "2018-12-04T19:47:03+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"ext-json": "*",
"ext-mbstring": "*",
"ext-curl": "*"
},
"platform-dev": []
}

View File

@@ -45,7 +45,7 @@ return array(
'host' => 'http://127.0.0.1:8083',
'username' => 'admin',
'password' => '',
'root_folder'=> 1, // 0不创建根目录1创建根目录(下载器默认1)
'root_folder'=> 1, // 创建多文件子目录:0不创建1创建(下载器默认1)【此处必须与下载器真实配置相同,否则添加任务不会校验!】
'BT_backup' => '/BT_backup', // 移动做种必须配置Linux搜索方法find / -name BT_backup
'move' => 0, // 0不移动1移动并辅种2移动且只在当前客户端辅种
),
@@ -131,6 +131,8 @@ return array(
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
// 如果需要辅种,必须配置
'rss' => '',
'id' => 0, // 用户ID(不是用户名)
'url_replace' => array(),
'url_join' => array(),
@@ -145,6 +147,8 @@ return array(
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
// 如果需要辅种,必须配置
'rss' => '',
'id' => 0, // 用户ID(不是用户名)
'url_replace' => array(),
'url_join' => array(),
@@ -159,6 +163,8 @@ return array(
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
// 如果需要辅种,必须配置
'rss' => '',
'id' => 0, // 用户ID(不是用户名)
'url_replace' => array(),
'url_join' => array(),
@@ -177,22 +183,15 @@ return array(
'url_replace' => array(),
'url_join' => array(),
),
// MoeCat
'moecat' => array(
// HDAI
'hdai' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项)
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
'id' => 0, // 用户ID(不是用户名)
'url_replace' => array(),
'url_join' => array(
//'ipv6=1', // 种子Tracker的IP地址选择 可选ipv4ipv6
'https=1',
),
'limitRule' => array(
'count' => 20, // 每次辅种20个
'sleep' => 15, // 最少休眠15秒
),
'url_join' => array(),
),
// m-team
'm-team' => array(
@@ -252,7 +251,7 @@ return array(
),
// HDSky
'hdsky' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项
// 如果需要自动辅种,必须配置此项
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
@@ -288,9 +287,9 @@ return array(
// 如果需要自动辅种,必须配置
'passkey' => '',
// 如果需要rss订阅必须配置
'rss' => '',
'url_replace' => array(),
'url_join' => array(),
'rss' => '',
),
// nanyangpt
'nanyangpt' => array(
@@ -656,5 +655,43 @@ return array(
'url_replace' => array(),
'url_join' => array(),
),
// pttime PT时间
'pttime' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项)
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
'url_replace' => array(),
'url_join' => array(),
),
// npupt 蒲公英
'npupt' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项)
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
),
// hdatmos 阿童木
'hdatmos' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项)
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '',
),
'greatposterwall' => array(
// 如果需要用下载免费种脚本,须配置(只是自动辅种,可以不配置此项)
'cookie' => '',
// 如果需要自动辅种,必须配置
'passkey' => '', // torrent_pass
'torrent_pass' => '', // torrent_pass
'authkey' => '', // authkey
),
// hudbt 华科蝴蝶
'hudbt' => array(
'cookie' => '',
'passkey' => '',
'url_replace' => array(),
'url_join' => array(),
),
// 配置结束,后面的一行不能删除,必须保留!!!
);

View File

@@ -19,7 +19,7 @@ ARG app_env=prod
ENV APP_ENV=${app_env:-"prod"} \
TIMEZONE=${timezone:-"Asia/Shanghai"} \
cron="0 10 * * 0"
cron="3 */10 * * *"
##
# ---------- building ----------
@@ -27,7 +27,7 @@ ENV APP_ENV=${app_env:-"prod"} \
RUN set -ex \
# change apk source repo
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/' /etc/apk/repositories \
#&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/' /etc/apk/repositories \
&& apk update \
&& apk add --no-cache \
# Install base packages ('ca-certificates' will install 'nghttp2-libs')
@@ -46,7 +46,7 @@ RUN set -ex \
# php7-common \
# php7-bcmath \
php7-curl \
# php7-ctype \
# php7-ctype \
php7-dom \
# php7-fileinfo \
# php7-gettext \
@@ -77,10 +77,12 @@ RUN set -ex \
# php7-tokenizer \
php7-zip \
# php7-zlib \
php7-xml \
&& git clone https://gitee.com/ledc/IYUUAutoReseed.git /var/www \
&& cp /var/www/config/config.sample.php /var/www/config/config.php \
&& ln -sf /var/www/config/config.php /config.php \
php7-xml \
&& git clone https://gitee.com/ledc/IYUUAutoReseed.git /IYUU \
&& cp /IYUU/config/config.sample.php /IYUU/config/config.php \
&& ln -sf /IYUU/config/config.php /config.php \
&& cp /IYUU/docker/entrypoint.sh /entrypoint.sh \
&& chmod +x /entrypoint.sh \
&& apk del --purge *-dev \
&& rm -rf /var/cache/apk/* /tmp/* /usr/share/man /usr/share/php7 \
# ---------- some config,clear work ----------
@@ -95,7 +97,8 @@ RUN set -ex \
# - config timezone
&& ln -sf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime \
&& echo "${TIMEZONE}" > /etc/timezone \
&& echo '2 */5 * * * cd /var/www && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root \
&& echo '2 */5 * * * cd /IYUU && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root \
#&& echo "${cron} /usr/bin/php /IYUU/iyuu.php &> /dev/null" >> /etc/crontabs/root \
# ---------- some config work ----------
# - ensure 'www-data' user exists(82 is the standard uid/gid for "www-data" in Alpine)
# && addgroup -g 82 -S ${add_user} \
@@ -105,8 +108,7 @@ RUN set -ex \
# && chown -R ${add_user}:${add_user} /data \
&& echo -e "\033[42;37m Build Completed :).\033[0m\n"
EXPOSE 9000
# VOLUME ["/var/www", "/data"]
WORKDIR /var/www
CMD ["sh", "-c", "/usr/bin/php /var/www/iyuu.php ; /usr/sbin/crond ; (crontab -l ;echo \"$cron /usr/bin/php /var/www/iyuu.php &> /dev/null\") | crontab - ; tail -f /dev/null"]
# EXPOSE 9000
# VOLUME ["/IYUU", "/data"]
WORKDIR /IYUU
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -1,9 +1,10 @@
# FROM arm64v8/alpine
# FROM arm64v8/alpine:latest
FROM arm64v8/alpine:3.12
ENV TZ Asia/Shanghai
ENV cron="0 9 * * 0"
ENV cron="3 */10 * * *"
RUN set -ex \
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/' /etc/apk/repositories \
@@ -16,12 +17,16 @@ RUN set -ex \
&& git clone https://gitee.com/ledc/IYUUAutoReseed.git /IYUU \
&& cp /IYUU/config/config.sample.php /IYUU/config/config.php \
&& ln -sf /IYUU/config/config.php /config.php \
&& cp /IYUU/docker/entrypoint.sh /entrypoint.sh \
&& chmod +x /entrypoint.sh \
&& apk del --purge *-dev \
&& rm -rf /var/cache/apk/* /tmp/* /usr/share/man \
&& echo "${TZ}" > /etc/timezone \
&& ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
&& echo '2 */6 * * * cd /IYUU && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root
WORKDIR /IYUU
# && echo '* * * * * echo "iyuu.cn" >/dev/null 2>&1' >> /etc/crontabs/root \
&& echo '3 */6 * * * cd /IYUU && git fetch --all && git reset --hard origin/master' >> /etc/crontabs/root \
# && echo "${cron} /usr/bin/php /IYUU/iyuu.php >/dev/null 2>&1" >> /etc/crontabs/root \
&& echo -e "\033[42;37m Build Completed :).\033[0m\n"
CMD ["sh", "-c", "/usr/bin/php /IYUU/iyuu.php ; /usr/sbin/crond ; (crontab -l ;echo \"$cron /usr/bin/php /IYUU/iyuu.php &> /dev/null\") | crontab - ; tail -f /dev/null"]
WORKDIR /IYUU
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -1,3 +0,0 @@
#!/bin/sh
export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/bin
docker exec IYUUAutoReseed php iyuu.php

2
docker/Arm64v8/push.sh Normal file
View File

@@ -0,0 +1,2 @@
docker image tag iyuu:arm64v8 iyuucn/iyuuautoreseed:arm64v8
docker image push iyuucn/iyuuautoreseed:arm64v8

8
docker/entrypoint.sh Normal file
View File

@@ -0,0 +1,8 @@
#!/bin/sh
DEFAULT_CRON="9 */6 * * *"
cron=${cron:-$DEFAULT_CRON}
set -e
echo "$cron /usr/bin/php /IYUU/iyuu.php" | crontab -
cd /IYUU && git fetch --all && git reset --hard origin/master
/usr/bin/php /IYUU/iyuu.php
/usr/sbin/crond -f

20
docker/iyuu.sh Normal file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/bin
## 相关命令
# 1. 手动执行辅种
docker exec IYUUAutoReseed php iyuu.php
# 2. 手动删除辅种缓存
docker exec -it IYUUAutoReseed rm -rf ./torrent/cachehash
# 3. 手动删除转移缓存
docker exec -it IYUUAutoReseed rm -rf ./torrent/cachemove
# 4. 查看当前定时任务
docker exec -it IYUUAutoReseed crontab -l
# 5. 修改定时任务推荐修改docker容器的环境变量参数cron
docker exec -it IYUUAutoReseed crontab -e
# 6. 进入容器内交互终端
docker exec -it IYUUAutoReseed sh

View File

@@ -5,5 +5,4 @@ echo $pwddir
cd $(dirname $0)
git fetch --all
git reset --hard origin/master
git pull
php ./iyuu.php

View File

@@ -55,7 +55,7 @@ IYUU自动辅种工具英文名IYUUAutoReseed是一款PHP语言编
2. qBittorrent
## 支持自动辅种的站点
学校、杜比、家园、天空、朋友、馒头、萌猫、我堡、猫站、铂金家、烧包、北洋、TCCF、南洋、TTG、映客、城市、52pt、brobits、备胎、SSD、CHD、ptmsg、leaguehd、聆音、瓷器、hdarea、eastgame(TLF)、1ptba、hdtime、hd4fans、opencd、hdbug、hdstreet、joyhd、u2、upxin(HDU)、oshen、discfan(GZT)、cnscg圣城(已删除)、北邮、CCFBits、dicmusic、天雪、葡萄、HDRoute、伊甸园hdbd、海胆haidan、HDfans、龙之家、百川PT。
学校、杜比、家园、天空、朋友、馒头、萌猫、我堡、猫站、铂金家、烧包、北洋、TCCF、南洋、TTG、映客、城市、52pt、brobits、备胎、SSD、CHD、ptmsg、leaguehd、聆音、瓷器、hdarea、eastgame(TLF)、1ptba、hdtime、hd4fans、opencd、hdbug、hdstreet、joyhd、u2、upxin(HDU)、oshen、discfan(GZT)、cnscg圣城(已删除)、北邮、CCFBits、dicmusic、天雪、葡萄、HDRoute、伊甸园hdbd、海胆haidan、HDfans、龙之家、百川PT、HDAI、蒲公英、阿童木、蝴蝶
## 运行环境
具备PHP运行环境的所有平台例如Linux、Windows、MacOS
@@ -94,7 +94,7 @@ IYUU自动辅种工具英文名IYUUAutoReseed是一款PHP语言编
## 需求提交/错误反馈
- QQ群859882209[2000人.入门群]931954050[1000人.进阶群]
- QQ群859882209[2000人群]931954050[1000人群],924099912[2000人群]
- 问答社区http://wenda.iyuu.cn
- 博客https://www.iyuu.cn/
- issues https://gitee.com/ledc/IYUUAutoReseed/issues

2
vendor/autoload.php vendored
View File

@@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e::getLoader();
return ComposerAutoloaderInit7e764d8cfe0bacfc97fde5b65088dcb3::getLoader();

View File

@@ -6,5 +6,6 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'IYUU\\Client\\' => array($vendorDir . '/ledccn/bittorrentclient/src'),
'IYUU\\' => array($baseDir . '/app'),
);

View File

@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e
class ComposerAutoloaderInit7e764d8cfe0bacfc97fde5b65088dcb3
{
private static $loader;
@@ -19,15 +19,15 @@ class ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit7e764d8cfe0bacfc97fde5b65088dcb3', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit7e764d8cfe0bacfc97fde5b65088dcb3', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitd8553673db02b2a444a853f28e16196e::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
@@ -48,19 +48,19 @@ class ComposerAutoloaderInitd8553673db02b2a444a853f28e16196e
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInitd8553673db02b2a444a853f28e16196e::$files;
$includeFiles = Composer\Autoload\ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequired8553673db02b2a444a853f28e16196e($fileIdentifier, $file);
composerRequire7e764d8cfe0bacfc97fde5b65088dcb3($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequired8553673db02b2a444a853f28e16196e($fileIdentifier, $file)
function composerRequire7e764d8cfe0bacfc97fde5b65088dcb3($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;

View File

@@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInitd8553673db02b2a444a853f28e16196e
class ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3
{
public static $files = array (
'45702aba72a3d88d5dd1a153f5231b73' => __DIR__ . '/../..' . '/app/helper.php',
@@ -13,11 +13,16 @@ class ComposerStaticInitd8553673db02b2a444a853f28e16196e
public static $prefixLengthsPsr4 = array (
'I' =>
array (
'IYUU\\Client\\' => 12,
'IYUU\\' => 5,
),
);
public static $prefixDirsPsr4 = array (
'IYUU\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/ledccn/bittorrentclient/src',
),
'IYUU\\' =>
array (
0 => __DIR__ . '/../..' . '/app',
@@ -37,9 +42,9 @@ class ComposerStaticInitd8553673db02b2a444a853f28e16196e
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitd8553673db02b2a444a853f28e16196e::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitd8553673db02b2a444a853f28e16196e::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitd8553673db02b2a444a853f28e16196e::$prefixesPsr0;
$loader->prefixLengthsPsr4 = ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit7e764d8cfe0bacfc97fde5b65088dcb3::$prefixesPsr0;
}, null, ClassLoader::class);
}

View File

@@ -1,17 +1,17 @@
[
{
"name": "curl/curl",
"version": "2.2.0",
"version_normalized": "2.2.0.0",
"version": "2.3.0",
"version_normalized": "2.3.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-mod/curl.git",
"reference": "d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff"
"reference": "3ad560b1fc1bbdf5c7681356ab953fb961f255e5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-mod/curl/zipball/d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff",
"reference": "d22086dd2eee5ca02e4c29b9a5bdf3645bfdbbff",
"url": "https://api.github.com/repos/php-mod/curl/zipball/3ad560b1fc1bbdf5c7681356ab953fb961f255e5",
"reference": "3ad560b1fc1bbdf5c7681356ab953fb961f255e5",
"shasum": "",
"mirrors": [
{
@@ -28,7 +28,7 @@
"phpunit/phpunit": "^5.7",
"squizlabs/php_codesniffer": "~2.1"
},
"time": "2018-12-04T19:47:03+00:00",
"time": "2020-03-19T20:07:26+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -41,15 +41,15 @@
"MIT"
],
"authors": [
{
"name": "php-curl-class",
"homepage": "https://github.com/php-curl-class"
},
{
"name": "Hassan Amouhzi",
"email": "hassan@anezi.net",
"homepage": "http://hassan.amouhzi.com"
},
{
"name": "php-curl-class",
"homepage": "https://github.com/php-curl-class"
},
{
"name": "user52",
"homepage": "https://github.com/user52"
@@ -63,18 +63,18 @@
]
},
{
"name": "owner888/phpspider",
"version": "v2.1.6",
"version_normalized": "2.1.6.0",
"name": "ledccn/bittorrentclient",
"version": "dev-master",
"version_normalized": "9999999-dev",
"source": {
"type": "git",
"url": "https://github.com/owner888/phpspider.git",
"reference": "e6021148adec201418c16ba26f39bc013ba5b4d9"
"url": "https://github.com/ledccn/BittorrentClient.git",
"reference": "d8302133ee50f5bc2f4e95531562cd54dcee6b50"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/owner888/phpspider/zipball/e6021148adec201418c16ba26f39bc013ba5b4d9",
"reference": "e6021148adec201418c16ba26f39bc013ba5b4d9",
"url": "https://api.github.com/repos/ledccn/BittorrentClient/zipball/d8302133ee50f5bc2f4e95531562cd54dcee6b50",
"reference": "d8302133ee50f5bc2f4e95531562cd54dcee6b50",
"shasum": "",
"mirrors": [
{
@@ -84,36 +84,35 @@
]
},
"require": {
"php": ">=5.5.0"
"curl/curl": "^2.3",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"php": "^5.6 | ^7.0"
},
"suggest": {
"ext-pcntl、ext-redis": "For better performance. "
},
"time": "2018-08-15T08:04:29+00:00",
"time": "2021-01-13T05:14:10+00:00",
"type": "library",
"installation-source": "dist",
"installation-source": "source",
"autoload": {
"psr-4": {
"phpspider\\": "./"
"IYUU\\Client\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
"GPL-3.0-or-later"
],
"authors": [
{
"name": "Seatle Yang",
"email": "seatle@foxmail.com",
"homepage": "http://www.phpspider.org",
"role": "Developer"
"name": "David",
"email": "367013672@qq.com"
}
],
"description": "The PHPSpider Framework.",
"homepage": "http://www.phpspider.org",
"description": "实现对下载服务器管理的代码库",
"homepage": "https://github.com/ledccn/BittorrentClient",
"keywords": [
"framework",
"phpspider"
"qbittorrent",
"transmission"
]
}
]

View File

@@ -27,7 +27,6 @@ tests-php5.6:
- php --version
- if [ ! -f composer.phar ]; then DOWLOAD_COMPOSER=1 ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php composer-setup.php ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "unlink('composer-setup.php');" ; fi;
- php composer.phar install
@@ -36,7 +35,6 @@ tests-php5.6:
cache:
key: php5.6
paths:
- composer.phar
- vendor
tests-php7.0:
@@ -51,7 +49,6 @@ tests-php7.0:
- php --version
- if [ ! -f composer.phar ]; then DOWLOAD_COMPOSER=1 ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php composer-setup.php ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "unlink('composer-setup.php');" ; fi;
- php composer.phar install
@@ -75,7 +72,6 @@ tests-php7.1:
- php --version
- if [ ! -f composer.phar ]; then DOWLOAD_COMPOSER=1 ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php composer-setup.php ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "unlink('composer-setup.php');" ; fi;
- php composer.phar install
@@ -89,25 +85,37 @@ tests-php7.1:
- vendor
tests-php7.2:
image: alpine:3.8
image: alpine:3.9
stage: test
services:
- name: "$CI_REGISTRY_IMAGE:server-test"
alias: server_test
script:
- apk add --no-cache php7-cli php7-curl php7-gd php7-phar php7-json php7-openssl php7-dom php7-simplexml php7-tokenizer php7-mbstring php7-xml
- apk add --no-cache composer php7-cli php7-curl php7-gd php7-phar php7-json php7-openssl php7-dom php7-simplexml php7-tokenizer php7-mbstring php7-xml
- php --version
- if [ ! -f composer.phar ]; then DOWLOAD_COMPOSER=1 ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php composer-setup.php ; fi;
- if [ -n "$DOWLOAD_COMPOSER" ] ; then php -r "unlink('composer-setup.php');" ; fi;
- php composer.phar install
- composer install
- vendor/bin/phpcs --warning-severity=0 --standard=PSR2 src
- nohup php -S localhost:8000 -t tests/server/php-curl-test > phpd.log 2>&1 &
- vendor/bin/phpunit
cache:
key: php7.2
paths:
- composer.phar
- vendor
tests-php7.3:
image: alpine:3.11
stage: test
services:
- name: "$CI_REGISTRY_IMAGE:server-test"
alias: server_test
script:
- apk add --no-cache composer php7-cli php7-curl php7-gd php7-phar php7-json php7-openssl php7-dom php7-simplexml php7-tokenizer php7-mbstring php7-xml
- php --version
- composer install
- vendor/bin/phpcs --warning-severity=0 --standard=PSR2 src
- nohup php -S localhost:8000 -t tests/server/php-curl-test > phpd.log 2>&1 &
- vendor/bin/phpunit
cache:
key: php7.3
paths:
- vendor

View File

@@ -78,12 +78,12 @@ class Curl
public $curl;
/**
* @var bool Whether an error occured or not
* @var bool Whether an error occurred or not
*/
public $error = false;
/**
* @var int Contains the error code of the curren request, 0 means no error happend
* @var int Contains the error code of the current request, 0 means no error happened
*/
public $error_code = 0;
@@ -93,12 +93,12 @@ class Curl
public $error_message = null;
/**
* @var bool Whether an error occured or not
* @var bool Whether an error occurred or not
*/
public $curl_error = false;
/**
* @var int Contains the error code of the curren request, 0 means no error happend.
* @var int Contains the error code of the current request, 0 means no error happened.
* @see https://curl.haxx.se/libcurl/c/libcurl-errors.html
*/
public $curl_error_code = 0;
@@ -109,7 +109,7 @@ class Curl
public $curl_error_message = null;
/**
* @var bool Whether an error occured or not
* @var bool Whether an error occurred or not
*/
public $http_error = false;
@@ -124,17 +124,17 @@ class Curl
public $http_error_message = null;
/**
* @var string|array TBD (ensure type) Contains the request header informations
* @var string|array TBD (ensure type) Contains the request header information
*/
public $request_headers = null;
/**
* @var string|array TBD (ensure type) Contains the response header informations
* @var string|array TBD (ensure type) Contains the response header information
*/
public $response_headers = array();
/**
* @var string Contains the response from the curl request
* @var string|false|null Contains the response from the curl request
*/
public $response = null;
@@ -146,12 +146,12 @@ class Curl
/**
* Constructor ensures the available curl extension is loaded.
*
* @throws \ErrorException
* @throws \RuntimeException
*/
public function __construct()
{
if (!extension_loaded('curl')) {
throw new \ErrorException('The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php');
throw new \RuntimeException('The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php');
}
$this->init();
@@ -162,7 +162,7 @@ class Curl
/**
* Initializer for the curl resource.
*
* Is called by the __construct() of the class or when the curl request is reseted.
* Is called by the __construct() of the class or when the curl request is reset.
* @return self
*/
private function init()
@@ -202,7 +202,7 @@ class Curl
// protected methods
/**
* Execute the curl request based on the respectiv settings.
* Execute the curl request based on the respective settings.
*
* @return int Returns the error code for the current curl request
*/
@@ -212,14 +212,14 @@ class Curl
$this->response = curl_exec($this->curl);
$this->curl_error_code = curl_errno($this->curl);
$this->curl_error_message = curl_error($this->curl);
$this->curl_error = !($this->curl_error_code === 0);
$this->http_status_code = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
$this->http_error = in_array(floor($this->http_status_code / 100), array(4, 5));
$this->curl_error = !($this->getErrorCode() === 0);
$this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE));
$this->http_error = $this->isError();
$this->error = $this->curl_error || $this->http_error;
$this->error_code = $this->error ? ($this->curl_error ? $this->curl_error_code : $this->http_status_code) : 0;
$this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0;
$this->request_headers = preg_split('/\r\n/', curl_getinfo($this->curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY);
$this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : '';
$this->error_message = $this->curl_error ? $this->curl_error_message : $this->http_error_message;
$this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message;
return $this->error_code;
}
@@ -250,6 +250,18 @@ class Curl
$this->setOpt(CURLOPT_POSTFIELDS, $data);
}
/**
* Set the json payload informations to the postfield curl option.
*
* @param array $data The data to be sent.
* @return void
*/
protected function prepareJsonPayload(array $data)
{
$this->setOpt(CURLOPT_POST, true);
$this->setOpt(CURLOPT_POSTFIELDS, json_encode($data));
}
/**
* Set auth options for the current request.
*
@@ -307,12 +319,17 @@ class Curl
*
* @param string $url The url to make the post request
* @param array $data Post data to pass to the url
* @param boolean $asJson Whether the data should be passed as json or not. {@insce 2.2.1}
* @return self
*/
public function post($url, $data = array())
public function post($url, $data = array(), $asJson = false)
{
$this->setOpt(CURLOPT_URL, $url);
$this->preparePayload($data);
if ($asJson) {
$this->prepareJsonPayload($data);
} else {
$this->preparePayload($data);
}
$this->exec();
return $this;
}
@@ -320,7 +337,7 @@ class Curl
/**
* Make a put request with optional data.
*
* The put request data can be either sent via payload or as get paramters of the string.
* The put request data can be either sent via payload or as get parameters of the string.
*
* @param string $url The url to make the put request
* @param array $data Optional data to pass to the $url
@@ -346,7 +363,7 @@ class Curl
/**
* Make a patch request with optional data.
*
* The patch request data can be either sent via payload or as get paramters of the string.
* The patch request data can be either sent via payload or as get parameters of the string.
*
* @param string $url The url to make the patch request
* @param array $data Optional data to pass to the $url
@@ -398,7 +415,7 @@ class Curl
/**
* Pass basic auth data.
*
* If the the rquested url is secured by an httaccess basic auth mechanism you can use this method to provided the auth data.
* If the the requested url is secured by an htaccess basic auth mechanism you can use this method to provided the auth data.
*
* ```php
* $curl = new Curl();
@@ -406,8 +423,8 @@ class Curl
* $curl->get('http://example.com/secure.php');
* ```
*
* @param string $username The username for the authentification
* @param string $password The password for the given username for the authentification
* @param string $username The username for the authentication
* @param string $password The password for the given username for the authentication
* @return self
*/
public function setBasicAuthentication($username, $password)
@@ -418,7 +435,7 @@ class Curl
}
/**
* Provide optional header informations.
* Provide optional header information.
*
* In order to pass optional headers by key value pairing:
*
@@ -442,7 +459,7 @@ class Curl
/**
* Provide a User Agent.
*
* In order to provide you cusomtized user agent name you can use this method.
* In order to provide you customized user agent name you can use this method.
*
* ```php
* $curl = new Curl();
@@ -461,6 +478,9 @@ class Curl
/**
* @deprecated Call setReferer() instead
*
* @param $referrer
* @return self
*/
public function setReferrer($referrer)
{
@@ -471,7 +491,7 @@ class Curl
/**
* Set the HTTP referer header.
*
* The $referer informations can help identify the requested client where the requested was made.
* The $referer Information can help identify the requested client where the requested was made.
*
* @param string $referer An url to pass and will be set as referer header
* @return self
@@ -503,24 +523,26 @@ class Curl
*
* @see http://php.net/curl_setopt
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to pass for the given $option
* @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to pass for the given $option
* @return bool
*/
public function setOpt($option, $value)
{
return curl_setopt($this->curl, $option, $value);
}
/**
* Get customized curl options.
*
* To see a full list of options: http://php.net/curl_getinfo
*
* @see http://php.net/curl_getinfo
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to check for the given $option
*/
* Get customized curl options.
*
* To see a full list of options: http://php.net/curl_getinfo
*
* @see http://php.net/curl_getinfo
*
* @param int $option The curl option constant e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed The value to check for the given $option
* @return mixed
*/
public function getOpt($option)
{
return curl_getinfo($this->curl, $option);
@@ -539,17 +561,26 @@ class Curl
}
/**
* Enable verbositiy.
* Enable verbosity.
*
* @todo As to keep naming convention it should be renamed to `setVerbose()`
* @param bool $on
* @return self
*/
public function setVerbose($on = true)
{
$this->setOpt(CURLOPT_VERBOSE, $on);
return $this;
}
/**
* @deprecated Call setVerbose() instead
*
* @param string $on
* @param bool $on
* @return self
*/
public function verbose($on = true)
{
$this->setOpt(CURLOPT_VERBOSE, $on);
return $this;
return $this->setVerbose($on);
}
/**
@@ -574,7 +605,7 @@ class Curl
$this->http_error_message = null;
$this->request_headers = null;
$this->response_headers = array();
$this->response = null;
$this->response = false;
$this->init();
return $this;
}
@@ -605,7 +636,7 @@ class Curl
*/
public function isInfo()
{
return $this->http_status_code >= 100 && $this->http_status_code < 200;
return $this->getHttpStatus() >= 100 && $this->getHttpStatus() < 200;
}
/**
@@ -614,7 +645,7 @@ class Curl
*/
public function isSuccess()
{
return $this->http_status_code >= 200 && $this->http_status_code < 300;
return $this->getHttpStatus() >= 200 && $this->getHttpStatus() < 300;
}
/**
@@ -623,7 +654,7 @@ class Curl
*/
public function isRedirect()
{
return $this->http_status_code >= 300 && $this->http_status_code < 400;
return $this->getHttpStatus() >= 300 && $this->getHttpStatus() < 400;
}
/**
@@ -632,7 +663,7 @@ class Curl
*/
public function isError()
{
return $this->http_status_code >= 400 && $this->http_status_code < 600;
return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 600;
}
/**
@@ -641,7 +672,7 @@ class Curl
*/
public function isClientError()
{
return $this->http_status_code >= 400 && $this->http_status_code < 500;
return $this->getHttpStatus() >= 400 && $this->getHttpStatus() < 500;
}
/**
@@ -650,7 +681,7 @@ class Curl
*/
public function isServerError()
{
return $this->http_status_code >= 500 && $this->http_status_code < 600;
return $this->getHttpStatus() >= 500 && $this->getHttpStatus() < 600;
}
/**
@@ -673,7 +704,7 @@ class Curl
* ```
*
* @param string $headerKey Optional key to get from the array.
* @return bool|string
* @return bool|string|array
* @since 1.9
*/
public function getResponseHeaders($headerKey = null)
@@ -697,21 +728,37 @@ class Curl
return $headers;
}
/**
* Get response from the curl request
* @return string|false
*/
public function getResponse()
{
return $this->response;
}
/**
* Get curl error code
* @return string
*/
public function getErrorCode()
{
return $this->curl_error_code;
}
/**
* Get curl error message
* @return string
*/
public function getErrorMessage()
{
return $this->curl_error_message;
}
/**
* Get http status code from the curl request
* @return int
*/
public function getHttpStatus()
{
return $this->http_status_code;

View File

@@ -0,0 +1,6 @@
/.git
composer.lock
vendor
vendor/
.idea
.idea/

View File

@@ -0,0 +1,26 @@
{
"name": "ledccn/bittorrentclient",
"description": "实现对下载服务器管理的代码库",
"type": "library",
"keywords": ["transmission", "qBittorrent"],
"homepage": "https://github.com/ledccn/BittorrentClient",
"license": "GPL-3.0-or-later",
"authors": [
{
"name": "David",
"email": "367013672@qq.com"
}
],
"require": {
"php": "^5.6 | ^7.0",
"curl/curl": "^2.3",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*"
},
"autoload": {
"psr-4": {
"IYUU\\Client\\": "src"
}
}
}

View File

@@ -0,0 +1,23 @@
## 项目简介
下载服务器的支持库,目前支持
- transmission
- qBittorrent
## 使用方法
https://packagist.org/packages/ledccn/bittorrentclient
```php
composer require ledccn/bittorrentclient:dev-master
```
## 其他项目
| 名称 | 简介 |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| [IYUUAutoReseed](https://github.com/ledccn/IYUUAutoReseed) | IYUU自动辅种工具功能分为两大块自动辅种、自动转移。目前能对支持的PT站点自动辅种支持下载器集群支持多盘位支持多下载目录支持远程连接等可以实现各下载器之间自动转移做种客户端让下载器各司其职专职的保种、专职的下载。 |

View File

@@ -0,0 +1,145 @@
<?php
/**
* 下载服务器抽象类
* Created by PhpStorm
* User: David <367013672@qq.com>
* Date: 2020-1-11
*/
namespace IYUU\Client;
abstract class AbstractClient
{
/**
* 完整的下载服务器地址
* @var string
*/
protected $url = '';
/**
* 下载服务器用户名
* @var string
*/
protected $username = '';
/**
* 密码
* @var string
*/
protected $password = '';
/**
* 调试开关
* @var bool
*/
public $debug = false;
/**
* 公共方法:创建客户端实例
* @param array $config
* array(
* 'type' => '',
* 'host' => '',
* 'endpoint' => '',
* 'username' => '',
* 'password' => '',
* )
* @return mixed 客户端实例
* @throws \IYUU\Client\ClientException
*/
public static function create($config = [])
{
// 下载服务器类型
$type = isset($config['type']) ? $config['type'] : '';
$file = __DIR__ . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $type .'.php';
if (!is_file($file)) {
throw new ClientException($file.' 文件不存在');
}
$className = "IYUU\\Client\\" . $type . "\\" . $type;
if (class_exists($className)) {
echo $type." 客户端正在实例化!".PHP_EOL;
return new $className($config);
} else {
throw new ClientException($className.' 客户端class不存在');
}
}
/**
* 初始化必须的参数
* @descr 子类调用
* @param array $config
*/
protected function initialize($config = [])
{
$host = isset($config['host']) ? $config['host'] : ''; // 地址端口
$endpoint = isset($config['endpoint']) ? $config['endpoint'] : ''; // 接入点
$username = isset($config['username']) ? $config['username'] : ''; // 用户名
$password = isset($config['password']) ? $config['password'] : ''; // 密码
$debug = isset($config['debug']) ? $this->booleanParse($config['debug']) : false; // 调试开关
$this->url = rtrim($host, '/') . $endpoint;
$this->username = $username;
$this->password = $password;
$this->debug = $debug;
}
/**
* 对布尔型进行格式化
* @param mixed $value 变量值
* @return boolean/string 格式化后的变量
*/
public function booleanParse($value)
{
$rs = $value;
if (!is_bool($value)) {
if (is_numeric($value)) {
$rs = $value > 0 ? true : false;
} elseif (is_string($value)) {
$rs = in_array(strtolower($value), ['ok', 'true', 'success', 'on', 'yes', '(ok)', '(true)', '(success)', '(on)', '(yes)']) ? true : false;
} else {
$rs = $value ? true : false;
}
}
return $rs;
}
/**
* 查询Bittorrent客户端状态
* @return string
*/
abstract public function status();
/**
* 获取所有种子的列表
* @param array $move
* @return array(
* 'hash' => string json,
* 'sha1' => string,
* 'hashString '=> array
* )
*/
abstract public function all(&$move = array());
/**
* 添加种子连接
* @param string $torrent_url
* @param string $save_path
* @param array $extra_options
*/
abstract public function add($torrent_url, $save_path = '', $extra_options = array());
/**
* 添加种子原数据
* @param string $torrent_metainfo
* @param string $save_path
* @param array $extra_options
*/
abstract public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array());
/**
* 删除种子
* @param $torrent
* @param bool $deleteFiles
*/
abstract public function delete($torrent, $deleteFiles = false);
}

View File

@@ -0,0 +1,12 @@
<?php
namespace IYUU\Client;
use Exception;
/**
* Class ClientException
*/
class ClientException extends Exception
{
}

View File

@@ -0,0 +1,11 @@
{
"name": "qBittorrent",
"author": "David",
"homepage": "https://github.com/qbittorrent/qBittorrent",
"version": "1.0",
"icon": "https://www.iyuu.cn/usr/uploads/client/qBittorrent.ico",
"allowCustomPath": true,
"pathDescription": "当前目录列表配置是指定硬盘上的绝对路径,如 /volume1/music/ 或 D:\\download\\music\\",
"description": "当前支持 qBittorrent v4.1+,由于浏览器限制,需要禁用 qBittorrent 的『启用跨站请求伪造(CSRF)保护』功能才能正常使用",
"warning": "注意:由于 qBittorrent 验证机制限制,第一次测试连接成功后,后续测试无论密码正确与否都会提示成功。"
}

View File

@@ -0,0 +1,674 @@
<?php
namespace IYUU\Client\qBittorrent;
use Curl\Curl;
use IYUU\Client\AbstractClient;
use IYUU\Client\ClientException;
/**
* qBittorrent下载服务器的API操作类
* 开源项目地址https://github.com/qbittorrent/qBittorrent
* API文档https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation
*/
class qBittorrent extends AbstractClient
{
/**
* API主版本号
* @var int|mixed|string
*/
private $api_version = '';
/**
* CSRF使用的Session或者Cookie
* @var string
*/
private $session_id = '';
/**
* curl实例
* @var Curl
*/
private $curl;
/**
* 分隔符
* @var string
*/
protected $delimiter = '';
/**
* 各版的API接入点
* @var array
*/
private $endpoints = [
'login' => [
'1' => '/login',
'2' => '/api/v2/auth/login'
],
'logout'=> [
'1' => null,
'2' => '/api/v2/auth/logout'
],
'app_version' => [
'1' => '/version/qbittorrent',
'2' => '/api/v2/app/version'
],
'api_version' => [
'1' => '/version/api',
'2' => '/api/v2/app/webapiVersion'
],
'build_info' => [
'1' => null,
'2' => '/api/v2/app/buildInfo'
],
'preferences' => [
'1' => null,
'2' => '/api/v2/app/preferences'
],
'setPreferences' => [
'1' => null,
'2' => '/api/v2/app/setPreferences'
],
'defaultSavePath' => [
'1' => null,
'2' => '/api/v2/app/defaultSavePath'
],
'downloadLimit' => [
'1' => null,
'2' => '/api/v2/transfer/downloadLimit'
],
'setDownloadLimit' => [
'1' => null,
'2' => '/api/v2/transfer/setDownloadLimit'
],
'uploadLimit' => [
'1' => null,
'2' => '/api/v2/transfer/uploadLimit'
],
'setUploadLimit' => [
'1' => null,
'2' => '/api/v2/transfer/setUploadLimit'
],
'torrent_list' => [
'1' => null,
'2' => '/api/v2/torrents/info'
],
'torrent_properties' => [
'1' => null,
'2' => '/api/v2/torrents/properties'
],
'torrent_trackers' => [
'1' => null,
'2' => '/api/v2/torrents/trackers'
],
'torrent_files' => [
'1' => null,
'2' => '/api/v2/torrents/files'
],
'torrent_pieceStates' => [
'1' => null,
'2' => '/api/v2/torrents/pieceStates'
],
'torrent_pieceHashes' => [
'1' => null,
'2' => '/api/v2/torrents/pieceHashes'
],
'torrent_pause' => [
'1' => null,
'2' => '/api/v2/torrents/pause'
],
'torrent_resume' => [
'1' => null,
'2' => '/api/v2/torrents/resume'
],
'torrent_delete' => [
'1' => null,
'2' => '/api/v2/torrents/delete'
],
'torrent_recheck' => [
'1' => null,
'2' => '/api/v2/torrents/recheck' // 重新校验种子
],
'torrent_reannounce' => [
'1' => null,
'2' => '/api/v2/torrents/reannounce' // 重新宣告种子
],
'torrent_add' => [
'1' => null,
'2' => '/api/v2/torrents/add'
],
'torrent_addTrackers' => [
'1' => null,
'2' => '/api/v2/torrents/addTrackers'
],
'torrent_editTracker' => [
'1' => null,
'2' => '/api/v2/torrents/editTracker'
],
'torrent_removeTrackers' => [
'1' => null,
'2' => '/api/v2/torrents/removeTrackers'
],
'torrent_addPeers' => [
'1' => null,
'2' => '/api/v2/torrents/addPeers'
],
'torrent_increasePrio' => [
'1' => null,
'2' => '/api/v2/torrents/increasePrio'
],
'torrent_decreasePrio' => [
'1' => null,
'2' => '/api/v2/torrents/decreasePrio'
],
'torrent_downloadLimit' => [
'1' => null,
'2' => '/api/v2/torrents/downloadLimit'
],
'torrent_setDownloadLimit' => [
'1' => null,
'2' => '/api/v2/torrents/setDownloadLimit'
],
'torrent_setShareLimits' => [
'1' => null,
'2' => '/api/v2/torrents/setShareLimits'
],
'torrent_uploadLimit' => [
'1' => null,
'2' => '/api/v2/torrents/uploadLimit'
],
'torrent_setUploadLimit' => [
'1' => null,
'2' => '/api/v2/torrents/setUploadLimit'
],
'torrent_setLocation' => [
'1' => null,
'2' => '/api/v2/torrents/setLocation'
],
'torrent_rename' => [
'1' => null,
'2' => '/api/v2/torrents/rename'
],
'torrent_setCategory' => [
'1' => null,
'2' => '/api/v2/torrents/setCategory'
],
'torrent_categories' => [
'1' => null,
'2' => '/api/v2/torrents/categories'
],
'torrent_createCategory' => [
'1' => null,
'2' => '/api/v2/torrents/createCategory'
],
'torrent_editCategory' => [
'1' => null,
'2' => '/api/v2/torrents/editCategory'
],
'torrent_removeCategories' => [
'1' => null,
'2' => '/api/v2/torrents/removeCategories'
],
'torrent_addTags' => [
'1' => null,
'2' => '/api/v2/torrents/addTags'
],
'torrent_removeTags' => [
'1' => null,
'2' => '/api/v2/torrents/removeTags'
],
'torrent_tags' => [
'1' => null,
'2' => '/api/v2/torrents/tags'
],
'torrent_createTags' => [
'1' => null,
'2' => '/api/v2/torrents/createTags'
],
'torrent_deleteTags' => [
'1' => null,
'2' => '/api/v2/torrents/deleteTags'
],
'torrent_setAutoManagement' => [
'1' => null,
'2' => '/api/v2/torrents/setAutoManagement'
],
'torrent_toggleSequentialDownload' => [
'1' => null,
'2' => '/api/v2/torrents/toggleSequentialDownload'
],
'torrent_toggleFirstLastPiecePrio' => [
'1' => null,
'2' => '/api/v2/torrents/toggleFirstLastPiecePrio'
],
'torrent_setForceStart' => [
'1' => null,
'2' => '/api/v2/torrents/setForceStart'
],
'torrent_setSuperSeeding' => [
'1' => null,
'2' => '/api/v2/torrents/setSuperSeeding'
],
'torrent_renameFile' => [
'1' => null,
'2' => '/api/v2/torrents/renameFile'
],
'maindata' => [
'1' => null,
'2' => '/api/v2/sync/maindata'
],
];
/**
* 构造函数
* @param array $config
* @throws ClientException
*/
public function __construct($config = [])
{
$this->initialize($config);
$this->api_version = isset($config['api_version']) && $config['api_version'] ? $config['api_version'] : 2;
$this->curl = new Curl();
$this->curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); // 禁止验证证书
$this->curl->setOpt(CURLOPT_SSL_VERIFYHOST, 2); // 不检查证书
$this->curl->setOpt(CURLOPT_CONNECTTIMEOUT, 60); // 超时
$this->curl->setOpt(CURLOPT_TIMEOUT, 600); // 超时
if (!$this->login()) {
throw new ClientException("qBittorrent Unable to authenticate with Web Api.");
}
}
/**
* app编译版本
* @return string
*/
public function appVersion()
{
return $this->getData('app_version');
}
/**
* api版本
* @return string
*/
public function apiVersion()
{
return $this->getData('api_version');
}
/**
* 编译信息
* @return array
*/
public function buildInfo()
{
return $this->getData('build_info');
}
/**
* 下载器验证
* @return bool
*/
public function login()
{
$this->curl->post($this->url . $this->endpoints['login'][$this->api_version], [
'username' => $this->username,
'password' => $this->password
]);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
}
// Find authentication cookie and set in curl connection
foreach ($this->curl->response_headers as $header) {
if (preg_match('/SID=(\S[^;]+)/', $header, $matches)) {
$this->session_id = $matches[0];
$qb415 = '; QB_'.$matches[0]; // 兼容qBittorrent v4.1.5[小钢炮等]
$this->curl->setHeader('Cookie', $matches[0].$qb415);
return true;
}
};
return false;
}
/**
* 退出登录
* @return mixed
*/
public function logout()
{
$this->session_id = '';
$this->getData('logout');
$this->curl->reset();
return $this;
}
/**
* 获取下载器首选项
* @return mixed
*/
public function preferences()
{
return $this->getData('preferences');
}
/**
* 设置下载器首选项
* @param array $data
* @return array|mixed
*/
public function setPreferences($data = [])
{
if (!empty($data)) {
return $this->postData('setPreferences', ['json' => json_encode($data)]);
}
return [];
}
/**
* 获取种子列表
* @return mixed
*/
public function torrentList()
{
return $this->getData('torrent_list');
}
/**
* 添加种子链接
* @param $torrent_url
* @param string $save_path
* @param array $extra_options
* array(
* 'urls' => '',
* 'savepath' => '',
* 'cookie' => '',
* 'category' => '',
* 'skip_checking' => true,
* 'paused' => true,
* 'root_folder' => true,
* )
* @return array
*/
public function add($torrent_url, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['urls'] = $torrent_url;
#$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】
$post_data = $this->buildUrls($extra_options);
#p($post_data);
// 设置请求头
$this->curl->setHeader('Content-Type', 'multipart/form-data; boundary='.$this->delimiter);
$this->curl->setHeader('Content-Length', strlen($post_data));
return $this->postData('torrent_add', $post_data);
}
/**
* 添加种子元数据
* @param string $torrent_metainfo
* @param string $save_path
* @param array $extra_options
* @return false|string|null
*/
public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['savepath'] = $save_path;
}
$extra_options['torrents'] = $torrent_metainfo;
#$extra_options['skip_checking'] = 'true'; //跳校验
// 关键 上传文件流 multipart/form-data【严格按照api文档编写】
$post_data = $this->buildData($extra_options);
// 设置请求头
$this->curl->setHeader('Content-Type', 'multipart/form-data; boundary='.$this->delimiter);
$this->curl->setHeader('Content-Length', strlen($post_data));
return $this->postData('torrent_add', $post_data);
}
/**
* 删除所有种子
* @param bool $deleteFiles
* @return string
*/
public function deleteAll($deleteFiles = false)
{
$torrents = json_decode($this->torrentList());
$response = '';
foreach ($torrents as $torrent) {
$response .= $this->delete($torrent->hash, $deleteFiles);
}
return $response;
}
/**
* 暂停种子
* @param string $hash info_hash可以|分隔删除多个种子也可以传入all删除所有种子
* @return false|string|null
*/
public function pause($hash)
{
return $this->postData('torrent_pause', ['hashes' => $hash]);
}
/**
* 恢复做种
* @param string $hash info_hash可以|分隔删除多个种子也可以传入all删除所有种子
* @return false|string|null
*/
public function resume($hash)
{
return $this->postData('torrent_resume', ['hashes' => $hash]);
}
/**
* 抽象方法,子类实现
* 删除种子
* @param string $hash info_hash可以|分隔删除多个种子也可以传入all删除所有种子
* @param bool $deleteFiles 是否同时删除数据
* @return false|string|null
*/
public function delete($hash = '', $deleteFiles = false)
{
return $this->postData('torrent_delete', ['hashes' => $hash, 'deleteFiles' => $deleteFiles ? 'true':'false']);
}
/**
* 重新校验种子
* @param string $hash info_hash可以|分隔删除多个种子也可以传入all删除所有种子
* @return false|string|null
*/
public function recheck($hash)
{
return $this->postData('torrent_recheck', ['hashes' => $hash]);
}
/**
* 重新宣告种子
* @param string $hash info_hash可以|分隔删除多个种子也可以传入all删除所有种子
* @return false|string|null
*/
public function reannounce($hash)
{
return $this->postData('torrent_reannounce', ['hashes' => $hash]);
}
/**
* @param $hash
* @param $location
* @return false|string|null
*/
public function setTorrentLocation($hash, $location)
{
return $this->postData('torrent_setLocation', ['hashes' => $hash, 'location' => $location]);
}
/**
* 获取当前Curl对象
* @return Curl
*/
public function curl()
{
return $this->curl;
}
/**
* 基本get方法
* @param $endpoint
* @return mixed
*/
private function getData($endpoint)
{
$this->curl->get($this->url . $this->endpoints[$endpoint][$this->api_version]);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
var_dump($this->curl->response);
}
if ($this->curl->error) {
return $this->errorMessage();
}
return $this->curl->response;
}
/**
* 基本post方法
* @param $endpoint
* @param $data
* @return mixed
*/
private function postData($endpoint, $data)
{
$this->curl->post($this->url . $this->endpoints[$endpoint][$this->api_version], $data);
if ($this->debug) {
var_dump($this->curl->request_headers);
var_dump($this->curl->response_headers);
var_dump($this->curl->response);
}
if ($this->curl->error) {
return $this->errorMessage();
}
return $this->curl->response;
}
/**
* 返回错误信息
* @return string
*/
private function errorMessage()
{
return 'Curl Error Code: ' . $this->curl->error_code . ' (' . $this->curl->response . ')';
}
/**
* 拼接种子urls multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
* @param array $param
* @return string
*/
public function buildUrls($param)
{
$this->delimiter = uniqid();
$eol = "\r\n";
$data = '';
// 拼接文件流
foreach ($param as $name => $content) {
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' .$name. '"' . $eol . $eol;
$data .= $content . $eol;
}
$data .= "--" . $this->delimiter . "--" . $eol;
return $data;
}
/**
* 拼接种子上传文件流 multipart/form-data
* https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation#add-new-torrent
* @param array $param
* @return string
*/
public function buildData($param)
{
$this->delimiter = uniqid();
$eol = "\r\n";
$data = '';
// 拼接文件流
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' .$param['name']. '"; filename="'.$param['filename'].'"' . $eol;
$data .= 'Content-Type: application/x-bittorrent' . $eol . $eol;
$data .= $param['torrents'] . $eol;
unset($param['name']);
unset($param['filename']);
unset($param['torrents']);
if (!empty($param)) {
foreach ($param as $name => $content) {
$data .= "--" . $this->delimiter . $eol;
$data .= 'Content-Disposition: form-data; name="' . $name . '"' . $eol . $eol;
$data .= $content . $eol;
}
}
$data .= "--" . $this->delimiter . "--" . $eol;
return $data;
}
/**
* 抽象方法,子类实现
*/
public function status()
{
return $this->appVersion();
}
/**
* 抽象方法,子类实现
* @param array $torrentList
* @return array
*/
public function all(&$torrentList = array())
{
$result = $this->getData('torrent_list');
$res = json_decode($result, true);
if (empty($res)) {
echo "获取种子列表失败可能qBittorrent暂时无响应请稍后重试".PHP_EOL;
return array();
}
// 过滤,只保留正常做种
$res = array_filter($res, function ($v) {
if (isset($v['state']) && in_array($v['state'], array('uploading','stalledUP','pausedUP','queuedUP','checkingUP','forcedUP'))) {
return true;
}
return false;
}, ARRAY_FILTER_USE_BOTH);
if (empty($res)) {
echo "未获取到正常做种数据,请多保种,然后重试!".PHP_EOL;
return array();
}
// 提取数组hashString
$info_hash = array_column($res, 'hash');
// 升序排序
sort($info_hash);
$json = json_encode($info_hash, JSON_UNESCAPED_UNICODE);
// 去重 应该从文件读入,防止重复提交
$sha1 = sha1($json);
// 组装返回数据
$hashArray['hash'] = $json;
$hashArray['sha1'] = $sha1;
// 变换数组hashString键名、目录为键值
$hashArray['hashString'] = array_column($res, "save_path", 'hash');
$torrentList = array_column($res, null, 'hash');
return $hashArray;
}
}

View File

@@ -0,0 +1,10 @@
{
"name": "Transmission",
"author": "David",
"homepage": "https://github.com/transmission/transmission",
"version": "1.0",
"icon": "https://www.iyuu.cn/usr/uploads/client/transmission.ico",
"allowCustomPath": true,
"pathDescription": "当前目录列表配置是指定硬盘上的绝对路径,如 /volume1/music/",
"description": "默认情况下,系统会请求 http://ip:port/transmission/rpc 这个路径,如果无法连接,请确认 `settings.json` 文件的 `rpc-url` 值;"
}

View File

@@ -0,0 +1,990 @@
<?php
namespace IYUU\Client\transmission;
use Curl\Curl;
use IYUU\Client\AbstractClient;
use IYUU\Client\ClientException;
/**
* Transmission下载服务器的RPC操作类
* 开源项目地址https://github.com/transmission/transmission
* API文档https://github.com/transmission/transmission/blob/master/extras/rpc-spec.txt
*/
class transmission extends AbstractClient
{
/**
* UserAgent
*/
const UA = 'TransmissionRPC for PHP/7.0.0';
/**
* Transmission RPC version
* @var int
*/
protected $rpc_version = 0;
/**
* CSRF使用的Session或者Cookie
* @var string
*/
protected $session_id = '';
/**
* 种子状态码 torrent status
*/
const TR_STATUS_STOPPED = 0; // Torrent is stopped
const TR_STATUS_CHECK_WAIT = 1; // Queued to check files
const TR_STATUS_CHECK = 2; // Checking files
const TR_STATUS_DOWNLOAD_WAIT = 3; // Queued to download
const TR_STATUS_DOWNLOAD = 4; // Downloading
const TR_STATUS_SEED_WAIT = 5; // Queued to seed
const TR_STATUS_SEED = 6; // Seeding
const RPC_LT_14_TR_STATUS_CHECK_WAIT = 1;
const RPC_LT_14_TR_STATUS_CHECK = 2;
const RPC_LT_14_TR_STATUS_DOWNLOAD = 4;
const RPC_LT_14_TR_STATUS_SEED = 8;
const RPC_LT_14_TR_STATUS_STOPPED = 16;
/**
* Exception: Invalid arguments
*/
const E_INVALIDARG = -1;
/**
* Exception: Invalid Session-Id
*/
const E_SESSIONID = -2;
/**
* Exception: Error while connecting
*/
const E_CONNECTION = -3;
/**
* Exception: Error 401 returned, unauthorized
*/
const E_AUTHENTICATION = -4;
/**
* Curl实例
* @var
*/
private $curl;
/**
* 构造函数
* @param array $config
*/
public function __construct($config = [])
{
$this->initialize($config);
$this->curl = new Curl();
$this->curl->setOpt(CURLOPT_CONNECTTIMEOUT, 60); // 超时
$this->curl->setOpt(CURLOPT_TIMEOUT, 600); // 超时
}
/**
* 开始一个或多个种子
* Start one or more torrents
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws ClientException
*/
public function start($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-start", $request);
}
/**
* 停止一个或多个种子
* Stop one or more torrents
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws ClientException
*/
public function stop($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-stop", $request);
}
/**
* 校验一个或多个种子
* Verify one or more torrents
*
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws ClientException
*/
public function verify($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-verify", $request);
}
/**
* 删除一个或多个种子
* Remove torrent from transmission
* @param int|array ids A list of transmission torrent ids
* @param bool $delete_local_data 是否删除数据
* @return mixed
* @throws ClientException
*/
public function delete($ids, $delete_local_data = false)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array(
"ids" => $ids,
"delete-local-data" => $delete_local_data
);
return $this->request("torrent-remove", $request);
}
/**
* 从announce获取一个或多个种子的更多Peer
* Reannounce one or more torrents
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws ClientException
*/
public function reannounce($ids)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array("ids" => $ids);
return $this->request("torrent-reannounce", $request);
}
/**
* 获取一个种子或所有种子的参数
* Get information on torrents in transmission, if the ids parameter is
* empty all torrents will be returned. The fields array can be used to return certain
* fields. Default fields are: "id", "name", "status", "doneDate", "haveValid", "totalSize".
* key | type | source
----------------------------+-----------------------------+---------
activityDate | number | tr_stat
addedDate | number | tr_stat
bandwidthPriority | number | tr_priority_t
comment | string | tr_info
corruptEver | number | tr_stat
creator | string | tr_info
dateCreated | number | tr_info
desiredAvailable | number | tr_stat
doneDate | number | tr_stat
downloadDir | string | tr_torrent
downloadedEver | number | tr_stat
downloadLimit | number | tr_torrent
downloadLimited | boolean | tr_torrent
error | number | tr_stat
errorString | string | tr_stat
eta | number | tr_stat
etaIdle | number | tr_stat
files | array (see below) | n/a
fileStats | array (see below) | n/a
hashString | string | tr_info
haveUnchecked | number | tr_stat
haveValid | number | tr_stat
honorsSessionLimits | boolean | tr_torrent
id | number | tr_torrent
isFinished | boolean | tr_stat
isPrivate | boolean | tr_torrent
isStalled | boolean | tr_stat
leftUntilDone | number | tr_stat
magnetLink | string | n/a
manualAnnounceTime | number | tr_stat
maxConnectedPeers | number | tr_torrent
metadataPercentComplete | double | tr_stat
name | string | tr_info
peer-limit | number | tr_torrent
peers | array (see below) | n/a
peersConnected | number | tr_stat
peersFrom | object (see below) | n/a
peersGettingFromUs | number | tr_stat
peersSendingToUs | number | tr_stat
percentDone | double | tr_stat
pieces | string (see below) | tr_torrent
pieceCount | number | tr_info
pieceSize | number | tr_info
priorities | array (see below) | n/a
queuePosition | number | tr_stat
rateDownload (B/s) | number | tr_stat
rateUpload (B/s) | number | tr_stat
recheckProgress | double | tr_stat
secondsDownloading | number | tr_stat
secondsSeeding | number | tr_stat
seedIdleLimit | number | tr_torrent
seedIdleMode | number | tr_inactvelimit
seedRatioLimit | double | tr_torrent
seedRatioMode | number | tr_ratiolimit
sizeWhenDone | number | tr_stat
startDate | number | tr_stat
status | number | tr_stat
trackers | array (see below) | n/a
trackerStats | array (see below) | n/a
totalSize | number | tr_info
torrentFile | string | tr_info
uploadedEver | number | tr_stat
uploadLimit | number | tr_torrent
uploadLimited | boolean | tr_torrent
uploadRatio | double | tr_stat
wanted | array (see below) | n/a
webseeds | array (see below) | n/a
webseedsSendingToUs | number | tr_stat
| |
-------------------+--------+-----------------------------+
files | array of objects, each containing: |
+-------------------------+------------+
| bytesCompleted | number | tr_torrent
| length | number | tr_info
| name | string | tr_info
-------------------+--------------------------------------+
fileStats | a file's non-constant properties. |
| array of tr_info.filecount objects, |
| each containing: |
+-------------------------+------------+
| bytesCompleted | number | tr_torrent
| wanted | boolean | tr_info
| priority | number | tr_info
-------------------+--------------------------------------+
peers | array of objects, each containing: |
+-------------------------+------------+
| address | string | tr_peer_stat
| clientName | string | tr_peer_stat
| clientIsChoked | boolean | tr_peer_stat
| clientIsInterested | boolean | tr_peer_stat
| flagStr | string | tr_peer_stat
| isDownloadingFrom | boolean | tr_peer_stat
| isEncrypted | boolean | tr_peer_stat
| isIncoming | boolean | tr_peer_stat
| isUploadingTo | boolean | tr_peer_stat
| isUTP | boolean | tr_peer_stat
| peerIsChoked | boolean | tr_peer_stat
| peerIsInterested | boolean | tr_peer_stat
| port | number | tr_peer_stat
| progress | double | tr_peer_stat
| rateToClient (B/s) | number | tr_peer_stat
| rateToPeer (B/s) | number | tr_peer_stat
-------------------+--------------------------------------+
peersFrom | an object containing: |
+-------------------------+------------+
| fromCache | number | tr_stat
| fromDht | number | tr_stat
| fromIncoming | number | tr_stat
| fromLpd | number | tr_stat
| fromLtep | number | tr_stat
| fromPex | number | tr_stat
| fromTracker | number | tr_stat
-------------------+--------------------------------------+
pieces | A bitfield holding pieceCount flags | tr_torrent
| which are set to 'true' if we have |
| the piece matching that position. |
| JSON doesn't allow raw binary data, |
| so this is a base64-encoded string. |
-------------------+--------------------------------------+
priorities | an array of tr_info.filecount | tr_info
| numbers. each is the tr_priority_t |
| mode for the corresponding file. |
-------------------+--------------------------------------+
trackers | array of objects, each containing: |
+-------------------------+------------+
| announce | string | tr_tracker_info
| id | number | tr_tracker_info
| scrape | string | tr_tracker_info
| tier | number | tr_tracker_info
-------------------+--------------------------------------+
trackerStats | array of objects, each containing: |
+-------------------------+------------+
| announce | string | tr_tracker_stat
| announceState | number | tr_tracker_stat
| downloadCount | number | tr_tracker_stat
| hasAnnounced | boolean | tr_tracker_stat
| hasScraped | boolean | tr_tracker_stat
| host | string | tr_tracker_stat
| id | number | tr_tracker_stat
| isBackup | boolean | tr_tracker_stat
| lastAnnouncePeerCount | number | tr_tracker_stat
| lastAnnounceResult | string | tr_tracker_stat
| lastAnnounceStartTime | number | tr_tracker_stat
| lastAnnounceSucceeded | boolean | tr_tracker_stat
| lastAnnounceTime | number | tr_tracker_stat
| lastAnnounceTimedOut | boolean | tr_tracker_stat
| lastScrapeResult | string | tr_tracker_stat
| lastScrapeStartTime | number | tr_tracker_stat
| lastScrapeSucceeded | boolean | tr_tracker_stat
| lastScrapeTime | number | tr_tracker_stat
| lastScrapeTimedOut | boolean | tr_tracker_stat
| leecherCount | number | tr_tracker_stat
| nextAnnounceTime | number | tr_tracker_stat
| nextScrapeTime | number | tr_tracker_stat
| scrape | string | tr_tracker_stat
| scrapeState | number | tr_tracker_stat
| seederCount | number | tr_tracker_stat
| tier | number | tr_tracker_stat
-------------------+-------------------------+------------+
wanted | an array of tr_info.fileCount | tr_info
| 'booleans' true if the corresponding |
| file is to be downloaded. |
-------------------+--------------------------------------+
webseeds | an array of strings: |
+-------------------------+------------+
| webseed | string | tr_info
+-------------------------+------------+
*
* @param array fields An array of return fields
* @param int|array ids A list of transmission torrent ids
* 示例 Example:
Say we want to get the name and total size of torrents #7 and #10.
请求 Request:
{
"arguments": {
"fields": [ "id", "name", "totalSize" ],
"ids": [ 7, 10 ]
},
"method": "torrent-get",
"tag": 39693
}
响应 Response:
{
"arguments": {
"torrents": [
{
"id": 10,
"name": "Fedora x86_64 DVD",
"totalSize": 34983493932,
},
{
"id": 7,
"name": "Ubuntu x86_64 DVD",
"totalSize", 9923890123,
}
]
},
"result": "success",
"tag": 39693
}
*
* @return mixed
* @throws ClientException
*/
public function get($ids = [], $fields = [])
{
$default = ["id", "name", "status", "doneDate", "haveValid", "totalSize"];
if (!is_array($ids)) {
$ids = array($ids);
}
if (empty($fields)) {
$fields = $default;
} else {
$fields = is_array($fields) ? array_merge($default, $fields) : $default;
}
$request = array(
"fields" => $fields,
"ids" => $ids
);
return $this->request("torrent-get", $request);
}
/**
* 设置一个或多个种子的参数
* Set properties on one or more torrents, available fields are:
* string | value type & description
----------------------+-------------------------------------------------
"bandwidthPriority" | number this torrent's bandwidth tr_priority_t
"downloadLimit" | number maximum download speed (KBps)
"downloadLimited" | boolean true if "downloadLimit" is honored
"files-wanted" | array indices of file(s) to download
"files-unwanted" | array indices of file(s) to not download
"honorsSessionLimits" | boolean true if session upload limits are honored
"ids" | array torrent list, as described in 3.1
"location" | string new location of the torrent's content
"peer-limit" | number maximum number of peers
"priority-high" | array indices of high-priority file(s)
"priority-low" | array indices of low-priority file(s)
"priority-normal" | array indices of normal-priority file(s)
"queuePosition" | number position of this torrent in its queue [0...n)
"seedIdleLimit" | number torrent-level number of minutes of seeding inactivity
"seedIdleMode" | number which seeding inactivity to use. See tr_idlelimit
"seedRatioLimit" | double torrent-level seeding ratio
"seedRatioMode" | number which ratio to use. See tr_ratiolimit
"trackerAdd" | array strings of announce URLs to add
"trackerRemove" | array ids of trackers to remove
"trackerReplace" | array pairs of <trackerId/new announce URLs>
"uploadLimit" | number maximum upload speed (KBps)
"uploadLimited" | boolean true if "uploadLimit" is honored
*
* @param array arguments An associative array of arguments to set
* @param int|array ids A list of transmission torrent ids
* @return mixed
* @throws ClientException
*/
public function set($ids = array(), $arguments = array())
{
if (!is_array($ids)) {
$ids = array($ids);
}
if (!isset($arguments['ids'])) {
$arguments['ids'] = $ids;
}
return $this->request("torrent-set", $arguments);
}
/**
* 添加新种子 (URL)
* Add a new torrent
*
* Request arguments:
* key | value type & description
---------------------+-------------------------------------------------
"cookies" | string pointer to a string of one or more cookies.
"download-dir" | string path to download the torrent to
"filename" | string filename or URL of the .torrent file
"metainfo" | string base64-encoded .torrent content
"paused" | boolean if true, don't start the torrent
"peer-limit" | number maximum number of peers
"bandwidthPriority" | number torrent's bandwidth tr_priority_t
"files-wanted" | array indices of file(s) to download
"files-unwanted" | array indices of file(s) to not download
"priority-high" | array indices of high-priority file(s)
"priority-low" | array indices of low-priority file(s)
"priority-normal" | array indices of normal-priority file(s)
*
* 参数内必须包含"filename"或"metainfo"字段,其他字段都可选。
* Either "filename" OR "metainfo" MUST be included.
All other arguments are optional.
*
* @param string $filename 字符串文件名或种子urlThe URL or path to the torrent file
* @param string $save_path Folder to save torrent in
* @param array $extra_options Optional extra torrent options
* @return mixed
* @throws ClientException
*/
public function add($filename, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['download-dir'] = $save_path;
}
$extra_options['filename'] = $filename;
return $this->request("torrent-add", $extra_options);
}
/**
* 添加新种子 (元数据)
* Add a torrent using the raw torrent data
* @param string $torrent_metainfo The raw, unencoded contents (metainfo) of a torrent
* @param string $save_path Folder to save torrent in
* @param array $extra_options Optional extra torrent options
* @return mixed
* @throws ClientException
*/
public function add_metainfo($torrent_metainfo, $save_path = '', $extra_options = array())
{
if (!empty($save_path)) {
$extra_options['download-dir'] = $save_path;
}
$extra_options['metainfo'] = base64_encode($torrent_metainfo);
return $this->request("torrent-add", $extra_options);
}
/**
* 变更数据保存目录
* Move local storage location
*
* Request arguments:
string | value type & description
---------------------------------+-------------------------------------------------
"ids" | array torrent list, as described in 3.1
"location" | string the new torrent location
"move" | boolean if true, move from previous location.
| otherwise, search "location" for files
| (default: false)
*
* @param int|array $ids A list of transmission torrent ids
* @param string $target_location The new storage location
* @param boolean $move_existing_data Move existing data or scan new location for available data
* @return mixed
* @throws ClientException
*/
public function move($ids, $target_location, $move_existing_data = true)
{
if (!is_array($ids)) {
$ids = array($ids);
}
$request = array(
"ids" => $ids,
"location" => $target_location,
"move" => $move_existing_data
);
return $this->request("torrent-set-location", $request);
}
/**
* 修改种子文件或目录名称
* Renaming a Torrent's Path
*
* For more information on the use of this function, see the transmission.h
documentation of tr_torrentRenamePath(). In particular, note that if this
call succeeds you'll want to update the torrent's "files" and "name" field
with torrent-get.
Request arguments:
string | value type & description
---------------------------------+-------------------------------------------------
"ids" | array the torrent torrent list, as described in 3.1
| (must only be 1 torrent)
"path" | string the path to the file or folder that will be renamed
"name" | string the file or folder's new name
Response arguments: "path", "name", and "id", holding the torrent ID integer
*
* @param int|array ids A 1-element list of transmission torrent ids
* @param string path The path to the file or folder that will be renamed
* @param string name The file or folder's new name
* @return mixed
* @throws ClientException
*/
public function rename($ids, $path, $name)
{
if (!is_array($ids)) {
$ids = array($ids);
}
if (count($ids) !== 1) {
throw new ClientException('A single id is accepted', self::E_INVALIDARG);
}
$request = array(
"ids" => $ids,
"path" => $path,
"name" => $name
);
return $this->request("torrent-rename-path", $request);
}
/**
* Session 请求
* (4.1) Session 参数
* string | value type | description
* ---------------------------------+------------+-------------------------------------
* "alt-speed-down" | number | max global download speed (KBps)
* "alt-speed-enabled" | boolean | true means use the alt speeds
* "alt-speed-time-begin" | number | when to turn on alt speeds (units: minutes after midnight)
* "alt-speed-time-enabled" | boolean | true means the scheduled on/off times are used
* "alt-speed-time-end" | number | when to turn off alt speeds (units: same)
* "alt-speed-time-day" | number | what day(s) to turn on alt speeds (look at tr_sched_day)
* "alt-speed-up" | number | max global upload speed (KBps)
* "blocklist-url" | string | location of the blocklist to use for "blocklist-update"
* "blocklist-enabled" | boolean | true means enabled
* "blocklist-size" | number | number of rules in the blocklist
* "cache-size-mb" | number | maximum size of the disk cache (MB)
* "config-dir" | string | location of transmission's configuration directory
* "download-dir" | string | default path to download torrents
* "download-queue-size" | number | max number of torrents to download at once (see download-queue-enabled)
* "download-queue-enabled" | boolean | if true, limit how many torrents can be downloaded at once
* "dht-enabled" | boolean | true means allow dht in public torrents
* "encryption" | string | "required", "preferred", "tolerated"
* "idle-seeding-limit" | number | torrents we're seeding will be stopped if they're idle for this long
* "idle-seeding-limit-enabled" | boolean | true if the seeding inactivity limit is honored by default
* "incomplete-dir" | string | path for incomplete torrents, when enabled
* "incomplete-dir-enabled" | boolean | true means keep torrents in incomplete-dir until done
* "lpd-enabled" | boolean | true means allow Local Peer Discovery in public torrents
* "peer-limit-global" | number | maximum global number of peers
* "peer-limit-per-torrent" | number | maximum global number of peers
* "pex-enabled" | boolean | true means allow pex in public torrents
* "peer-port" | number | port number
* "peer-port-random-on-start" | boolean | true means pick a random peer port on launch
* "port-forwarding-enabled" | boolean | true means enabled
* "queue-stalled-enabled" | boolean | whether or not to consider idle torrents as stalled
* "queue-stalled-minutes" | number | torrents that are idle for N minuets aren't counted toward seed-queue-size or download-queue-size
* "rename-partial-files" | boolean | true means append ".part" to incomplete files
* "rpc-version" | number | the current RPC API version 当前RPC版本号
* "rpc-version-minimum" | number | the minimum RPC API version supported 支持RPC的最小版本号
* "script-torrent-done-filename" | string | filename of the script to run
* "script-torrent-done-enabled" | boolean | whether or not to call the "done" script
* "seedRatioLimit" | double | the default seed ratio for torrents to use
* "seedRatioLimited" | boolean | true if seedRatioLimit is honored by default
* "seed-queue-size" | number | max number of torrents to uploaded at once (see seed-queue-enabled)
* "seed-queue-enabled" | boolean | if true, limit how many torrents can be uploaded at once
* "speed-limit-down" | number | max global download speed (KBps)
* "speed-limit-down-enabled" | boolean | true means enabled
* "speed-limit-up" | number | max global upload speed (KBps)
* "speed-limit-up-enabled" | boolean | true means enabled
* "start-added-torrents" | boolean | true means added torrents will be started right away
* "trash-original-torrent-files" | boolean | true means the .torrent file of added torrents will be deleted
* "units" | object | see below
* "utp-enabled" | boolean | true means allow utp
* "version" | string | long version string "$version ($revision)"
* ---------------------------------+------------+-----------------------------+
* units | object containing: |
+--------------+--------+------------------+
| speed-units | array | 4 strings: KB/s, MB/s, GB/s, TB/s
| speed-bytes | number | number of bytes in a KB (1000 for kB; 1024 for KiB)
| size-units | array | 4 strings: KB/s, MB/s, GB/s, TB/s
| size-bytes | number | number of bytes in a KB (1000 for kB; 1024 for KiB)
| memory-units | array | 4 strings: KB/s, MB/s, GB/s, TB/s
| memory-bytes | number | number of bytes in a KB (1000 for kB; 1024 for KiB)
+--------------+--------+------------------+
*
* 当前RPC版本号"rpc-version" indicates the RPC interface version supported by the RPC server.
* It is incremented when a new version of Transmission changes the RPC interface.
*
* 支持RPC的最小版本号"rpc-version-minimum" indicates the oldest API supported by the RPC server.
* It is changes when a new version of Transmission changes the RPC interface
* in a way that is not backwards compatible. There are no plans for this
* to be common behavior.
*/
/**
* 获取会话
* Retrieve all session variables
* Method name: "session-get"
Request arguments: an optional "fields" array of keys (see 4.1)
Response arguments: key/value pairs matching the request's "fields"
argument if present, or all supported fields (see 4.1) otherwise.
*
* @returns array of session information
* @throws ClientException
*/
public function sessionGet()
{
return $this->request("session-get", array());
}
/**
* 设置会话
* Set session variable(s)
* Method name: "session-set"
Request arguments: one or more of 4.1's arguments, except: "blocklist-size",
"config-dir", "rpc-version", "rpc-version-minimum",
"version", and "session-id"
Response arguments: none
*
* @param array of session variables to set
* @return mixed
* @throws ClientException
*/
public function sessionSet($arguments)
{
return $this->request("session-set", $arguments);
}
/**
* 会话状态统计
* Retrieve session statistics
*
* Method name: "session-stats"
Request arguments: none
Response arguments:
string | value type
---------------------------+-------------------------------------------------
"activeTorrentCount" | number
"downloadSpeed" | number
"pausedTorrentCount" | number
"torrentCount" | number
"uploadSpeed" | number
---------------------------+-------------------------------+
"cumulative-stats" | object, containing: |
+------------------+------------+
| uploadedBytes | number | tr_session_stats
| downloadedBytes | number | tr_session_stats
| filesAdded | number | tr_session_stats
| sessionCount | number | tr_session_stats
| secondsActive | number | tr_session_stats
---------------------------+-------------------------------+
"current-stats" | object, containing: |
+------------------+------------+
| uploadedBytes | number | tr_session_stats
| downloadedBytes | number | tr_session_stats
| filesAdded | number | tr_session_stats
| sessionCount | number | tr_session_stats
| secondsActive | number | tr_session_stats
*
* @returns array of statistics
* @throws ClientException
*/
public function sessionStats()
{
return $this->request("session-stats", array());
}
/**
* Return the interpretation of the torrent status
*
* @param int The integer "torrent status"
* @returns string The translated meaning
* @return string
*/
public function getStatusString($intstatus)
{
if ($this->rpc_version < 14) {
if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_CHECK) {
return "Verifying local files";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_DOWNLOAD) {
return "Downloading";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_SEED) {
return "Seeding";
}
if ($intstatus == self::RPC_LT_14_TR_STATUS_STOPPED) {
return "Stopped";
}
} else {
if ($intstatus == self::TR_STATUS_CHECK_WAIT) {
return "Waiting to verify local files";
}
if ($intstatus == self::TR_STATUS_CHECK) {
return "Verifying local files";
}
if ($intstatus == self::TR_STATUS_DOWNLOAD) {
return "Downloading";
}
if ($intstatus == self::TR_STATUS_SEED) {
return "Seeding";
}
if ($intstatus == self::TR_STATUS_STOPPED) {
return "Stopped";
}
if ($intstatus == self::TR_STATUS_SEED_WAIT) {
return "Queued for seeding";
}
if ($intstatus == self::TR_STATUS_DOWNLOAD_WAIT) {
return "Queued for download";
}
}
return "Unknown";
}
/**
* 对请求数据预处理
* Clean up the request array. Removes any empty fields from the request
*
* @param array array The request associative array to clean
* @returns array The cleaned array
* @return array|null
*/
protected function cleanRequestData($array)
{
if (!is_array($array) || count($array) == 0) {
return null;
}
setlocale(LC_NUMERIC, 'en_US.utf8'); // Override the locale - if the system locale is wrong, then 12.34 will encode as 12,34 which is invalid JSON
foreach ($array as $index => $value) {
if (is_object($value)) {
$array[$index] = $value->toArray();
} // Convert objects to arrays so they can be JSON encoded
if (is_array($value)) {
$array[$index] = $this->cleanRequestData($value);
} // Recursion
if (empty($value) && ($value !== 0 || $value !== false)) { // Remove empty members
unset($array[$index]);
continue; // Skip the rest of the tests - they may re-add the element.
}
if (is_numeric($value)) {
$array[$index] = $value + 0;
} // Force type-casting for proper JSON encoding (+0 is a cheap way to maintain int/float/etc)
if (is_bool($value)) {
$array[$index] = ($value ? 1 : 0);
} // Store boolean values as 0 or 1
if (is_string($value)) {
$type = mb_detect_encoding($value, 'auto');
if ($type !== 'UTF-8') {
$array[$index] = mb_convert_encoding($value, 'UTF-8');
}
}
}
return $array;
}
/**
* 获取当前Curl对象
* @return Curl
*/
public function curl()
{
return $this->curl;
}
/**
* 执行 rpc 请求
* @param string $method 请求类型/方法, 详见 $this->allowMethods
* @param array $arguments 附加参数, 可选
* @return array
* @throws ClientException
*/
protected function request($method, $arguments = array())
{
if (!is_scalar($method)) {
throw new ClientException('Method name has no scalar value', self::E_INVALIDARG);
}
if (!is_array($arguments)) {
throw new ClientException('Arguments must be given as array', self::E_INVALIDARG);
}
$arguments = $this->cleanRequestData($arguments); // Sanitize input
// Grab the X-Transmission-Session-Id if we don't have it already
if (!$this->session_id) {
if (!$this->GetSessionID()) {
throw new ClientException('Unable to acquire X-Transmission-Session-Id', self::E_SESSIONID);
}
}
$data = array(
'method' => $method,
'arguments' => $arguments
);
$header = array(
'Content-Type' => 'application/json',
'Authorization' => 'Basic ' . base64_encode(sprintf("%s:%s", $this->username, $this->password)),
'X-Transmission-Session-Id' => $this->session_id
);
$curl = $this->curl;
if (stripos($this->url, 'https://') === 0) {
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); // 禁止验证证书
$curl->setOpt(CURLOPT_SSL_VERIFYHOST, 2); // 不检查证书
}
foreach ($header as $key => $value) {
$curl->setHeader($key, $value);
}
$curl->setUserAgent(self::UA);
$curl->setBasicAuthentication($this->username, $this->password);
$curl->post($this->url, $data, true);
$content = $curl->response;
if ($this->debug) {
var_dump($curl->request_headers);
var_dump($curl->response_headers);
var_dump($curl->response);
}
if (!$content) {
$content = array('result' => 'failed');
}
return json_decode($content, true);
}
/**
* Performs an empty GET on the Transmission RPC to get the X-Transmission-Session-Id
* and store it in $this->session_id
* @return string
*/
public function GetSessionID()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->username.':'.$this->password);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$content = curl_exec($ch);
$error_code = curl_errno($ch);
$error_message = curl_error($ch);
$http_status_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
if ($this->debug) {
var_dump($http_status_code);
var_dump($error_message);
var_dump($error_code);
var_dump($content);
}
// 401 Invalid username/password
// 409 成功
// 其他 Unexpected response from Transmission RPC
curl_close($ch);
if($content && preg_match("/<code>X-Transmission-Session-Id: (.*?)<\/code>/", $content, $match)) {
$this->session_id = isset($match[1]) ? $match[1] : null;
}
return $this->session_id;
}
/**
* 抽象方法,子类实现
* 获取下载器链接状态
* @throws ClientException
*/
public function status()
{
$rs = $this->sessionStats();
return isset($rs['result']) ? $rs['result'] : 'error';
}
/**
* 抽象方法,子类实现
* 获取所有种子的列表
* @param array $torrentList
* @return array
* array(
* 'hash' => string json,
* 'sha1' => string,
* 'hashString '=> array
* )
* @throws ClientException
*/
public function all(&$torrentList = array())
{
$ids = array();
$fields = array( "id", "status", "name", "hashString", "downloadDir", "torrentFile" );
$res = $this->get($ids, $fields);
if (isset($res['result']) && $res['result'] === 'success') {
// 成功
} else {
// 失败
echo "从客户端获取种子列表失败可能transmission暂时无响应请稍后重试".PHP_EOL;
return array();
}
if (empty($res['arguments']['torrents'])) {
echo "从客户端未获取到数据,请稍后重试!".PHP_EOL;
return array();
}
$res = $res['arguments']['torrents'];
// 过滤,只保留正常做种
$res = array_filter($res, function ($v) {
return isset($v['status']) && $v['status'] === 6;
}, ARRAY_FILTER_USE_BOTH);
if (empty($res)) {
echo "从客户端未获取到正常做种数据,请多保种,然后重试!".PHP_EOL;
return array();
}
// 提取数组hashString
$info_hash = array_column($res, 'hashString');
// 升序排序
sort($info_hash);
$json = json_encode($info_hash, JSON_UNESCAPED_UNICODE);
// 去重 应该从文件读入,防止重复提交
$sha1 = sha1($json);
// 组装返回数据
$hashArray['hash'] = $json;
$hashArray['sha1'] = $sha1;
// 变换数组hashString为键名、目录为键值
$hashArray['hashString'] = array_column($res, "downloadDir", 'hashString');
$torrentList = array_column($res, null, 'hashString');
return $hashArray;
}
}