MediaServerScripts/qBitTorrentSearchDeadTrackers.php

89 lines
2.9 KiB
PHP

<?php
require_once __DIR__ . '/common.php';
require_once __DIR__ . '/lib/qBitTorrent.php';
use Decicus\qBitTorrent\Client as QBitClient;
$qBitClient = new QBitClient();
$torrents = $qBitClient->getBasicTorrentsInfo();
// Sort by name
usort($torrents, function ($a, $b) {
return strcmp($a['name'], $b['name']);
});
// Filter any torrents with active trackers
$checkedCount = 0;
$totalCount = count($torrents);
$start = time();
$dateFormat = 'Y-m-d H:i:s';
printf('%s: %d torrents to check.%s', date($dateFormat), $totalCount, PHP_EOL);
$torrents = array_filter(
$torrents,
function ($torrent) use ($qBitClient, &$checkedCount, $totalCount, $dateFormat, $start)
{
$hash = $torrent['hash'];
$validTrackers = [];
try {
$trackers = $qBitClient->getTorrentTrackers($hash);
// printf('%s - %s - %s%s%s%s', $torrent['name'], $torrent['hash'], $torrent['tracker'], PHP_EOL, json_encode($trackers, JSON_PRETTY_PRINT), PHP_EOL);
$validTrackers = array_filter($trackers, function ($tracker) {
$status = $tracker['status'];
// https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)#get-torrent-trackers
return $status !== 4 && $status !== 0;
});
}
catch (Exception $e) {
printf('%s: %s%s', date($dateFormat), $e->getMessage(), PHP_EOL);
}
$checkedCount++;
if ($checkedCount % 100 === 0) {
$now = time();
printf('%s: Checked %s torrents out of %s - %s seconds since start%s', date($dateFormat), $checkedCount, $totalCount, ($now - $start), PHP_EOL);
}
// If this is empty, then all trackers returned errors.
return empty($validTrackers);
}
);
$deadTrackersTag = 'dead-trackers';
$torrents = array_filter(
$torrents,
function ($torrent) use ($deadTrackersTag)
{
return !str_contains($torrent['tags'], $deadTrackersTag);
}
);
// Reset all array keys for torrents
$torrents = array_values($torrents);
$hashes = array_map(function ($torrent) {
return $torrent['hash'];
}, $torrents);
$qBitClient->addTag($hashes, 'dead-trackers');
$torrentOutput = array_map(
function ($torrent) {
return [
'name' => $torrent['name'],
'category' => $torrent['category'],
'save_path' => $torrent['save_path'],
];
}, $torrents
);
$json = json_encode($torrentOutput, JSON_PRETTY_PRINT);
$filename = sprintf('%s/output/%s_dead_trackers.json', __DIR__, time());
fileWrite($filename, $json);
echo sprintf("Torrent output written to: %s\n", $filename);