MediaServerScripts/qBitTorrentTagPublic.php

100 lines
2.7 KiB
PHP

<?php
require_once __DIR__ . '/common.php';
require_once __DIR__ . '/lib/qBitTorrent.php';
use Decicus\qBitTorrent\Client as QBitClient;
$cliOptions = getopt('l::o::');
$limit = isset($cliOptions['l']) && $cliOptions['l'] === false;
$old = isset($cliOptions['o']) && $cliOptions['o'] === false;
$tag = (string) env('QBITTORRENT_PUBLIC_TAG', 'public-trackers');
$qBitClient = new QBitClient();
$torrents = $qBitClient->getBasicTorrentsInfo();
$torrents = array_filter(
$torrents,
function ($torrent) use ($tag)
{
$tags = $torrent['tags'];
return !str_contains($tags, $tag) && $torrent['trackers_count'] >= 5;
}
);
/**
* Only tag torrents older than specified hours
*/
$olderThan = null;
if ($old) {
$olderThanHours = (int) env('QBITTORRENT_PUBLIC_OLDER_THAN_HOURS', 48);
$olderThan = time() - ($olderThanHours * 60 * 60);
}
if ($olderThan) {
$torrents = array_filter(
$torrents,
function ($torrent) use ($olderThan)
{
return $torrent['added_on'] <= $olderThan;
}
);
}
// Reset all array keys for torrents
$torrents = array_values($torrents);
if (!empty($torrents)) {
$torrentHashes = array_map(
function ($torrent)
{
return $torrent['hash'];
},
$torrents
);
$qBitClient->addTag($torrentHashes, $tag);
echo sprintf('Added tag "%s" to %d torrents.%s', $tag, count($torrents), PHP_EOL);
}
else {
echo 'No torrents to tag.' . PHP_EOL;
}
if (!$limit) {
exit;
}
$maxRate = (int) env('QBITTORRENT_PUBLIC_MAX_RATE', 153600);
echo sprintf('Limit specified, limiting public torrents speed to %s%s', formatBytes($maxRate, 2, true), PHP_EOL);
$torrents = $qBitClient->getBasicTorrentsInfo();
$torrents = array_filter(
$torrents,
function ($torrent) use ($tag)
{
$hasTag = str_contains($torrent['tags'], $tag);
/**
* We only set the upload limit if it's not already set.
* If it's set to something specific, we don't want to override it.
*/
$hasNoLimit = $torrent['up_limit'] <= 0;
return $hasTag && $hasNoLimit;
}
);
$hashes = array_map(
function ($torrent)
{
return $torrent['hash'];
},
$torrents
);
echo sprintf('Limiting %d torrents to %s%s', count($torrents), formatBytes($maxRate, 2, true), PHP_EOL);
$qBitClient->setTorrentsUploadLimit($hashes, $maxRate);