TraderScrape (beta). As sites out there evolve, so so their need for accurate and stable stats. I never had this working before, while relying on the old mega-scrape.php, which was awful most of the time, so I scrapped it and utilized a fairly new class updated just 7 months ago via Github. Toss out mega-scrape.
It checks the torrent ID against the torrent's announce URL in torrent table, scrapes that URL & upon success => stores to database.
Supports UDP, HTTP, HTTPS, IP trackers.
What it's doing:
[color=rgb(226, 80, 65)]yoursite.com/[/color][color=rgb(0, 168, 133)]trader-scrape.php?id=[/color][color=rgb(41, 105, 176)]ID_OF_CURRENT_TORRENT_PAGE[/color]
Create trader-scrape.php and upload to root /
POST - AJAX call - Scrape class, DB update : id
Create get-torrent-stats.php and upload to root /
GET (JSON) - AJAX call [seeders], [leechers] : id
add to header.php after jQuery
Now place this anywhere you want on torrents-details.php - seed & peer data automatically scrapes and updates while browsing torrent-details.php and shows the dynamic count in the HTML below.
Leaves all the guess work out, and keep stats up to date on public trackers, it updates itself every 15 seconds or as any user views a torrent and their duration for that ID. If you don't have a good server, enough of these taxing calls on the CPU will get the best of you, just a notice.
It checks the torrent ID against the torrent's announce URL in torrent table, scrapes that URL & upon success => stores to database.
Supports UDP, HTTP, HTTPS, IP trackers.
What it's doing:
[color=rgb(226, 80, 65)]yoursite.com/[/color][color=rgb(0, 168, 133)]trader-scrape.php?id=[/color][color=rgb(41, 105, 176)]ID_OF_CURRENT_TORRENT_PAGE[/color]
Create trader-scrape.php and upload to root /
POST - AJAX call - Scrape class, DB update : id
<?
// AJAX Torrent Scrape - Update Stats - BETA - May 19, 2020
// Public torrents only / UDP, HTTPS, HTTP
// Takes POST by torrent ID via AJAX call, scrapes announce in torrent table
// with much better class and logic, and updates seeders/leechers in database by ID
require_once 'backend/functions.php';
$torrentid = isset($_GET['id'])?intval($_GET['id']):0; // Get torrent ID ?id=
$limit = 1;
$dsn = 'mysql:dbname=database;host=localhost;charset=utf8';
$user = 'username';
$password = 'password';
$torrentid = $_GET['id'];
try {
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$stmt = $conn->prepare("SELECT id, announce, info_hash FROM torrents WHERE external = 'yes' AND id = :torrentid LIMIT 1");
$stmt->bindValue(':torrentid', $torrentid, PDO::PARAM_INT);
$stmt->execute();
class ScraperException extends Exception
{
private $connectionerror;
public function __construct($message, $code = 0, $connectionerror = false)
{
$this->connectionerror = $connectionerror;
parent::__construct($message, $code);
}
public function isConnectionError()
{
return ($this->connectionerror);
}
}
abstract class tscraper
{
protected $timeout;
public function __construct($timeout = 2)
{
$this->timeout = $timeout;
}
}
class udptscraper extends tscraper
{
public function scrape($url, $infohash)
{
if (!is_array($infohash)) {
$infohash = array(
$infohash
);
}
foreach ($infohash as $hash) {
if (!preg_match('#^[a-f0-9]{40}$#i', $hash)) {
throw new ScraperException('Invalid infohash: ' . $hash . '.');
}
}
if (count($infohash) > 74) {
throw new ScraperException('Too many infohashes provided.');
}
if (!preg_match('%udp://([^:/]*)(?::([0-9]*))?(?:/)?%si', $url, $m)) {
throw new ScraperException('Invalid tracker url.');
}
$tracker = 'udp://' . $m[1];
$port = isset($m[2]) ? $m[2] : 80;
$transaction_id = mt_rand(0, 65535);
$fp = fsockopen($tracker, $port, $errno, $errstr);
if (!$fp) {
throw new ScraperException('Could not open UDP connection: ' . $errno . ' - ' . $errstr, 0, true);
}
stream_set_timeout($fp, $this->timeout);
$current_connid = "\x00\x00\x04\x17\x27\x10\x19\x80";
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp, $packet);
$ret = fread($fp, 16);
if (strlen($ret) < 1) {
throw new ScraperException('No connection response.', 0, true);
}
if (strlen($ret) < 16) {
throw new ScraperException('Too short connection response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 0 || $retd['transid'] != $transaction_id) {
throw new ScraperException('Invalid connection response.');
}
$current_connid = substr($ret, 8, 8);
$hashes = '';
foreach ($infohash as $hash) {
$hashes .= pack('H*', $hash);
}
$packet = $current_connid . pack("N", 2) . pack("N", $transaction_id) . $hashes;
fwrite($fp, $packet);
$readlength = 8 + (12 * count($infohash));
$ret = fread($fp, $readlength);
if (strlen($ret) < 1) {
throw new ScraperException('No scrape response.', 0, true);
}
if (strlen($ret) < 8) {
throw new ScraperException('Too short scrape response.');
}
$retd = unpack("Naction/Ntransid", $ret);
if ($retd['action'] != 2 || $retd['transid'] != $transaction_id) {
throw new ScraperException('Invalid scrape response.');
}
if (strlen($ret) < $readlength) {
throw new ScraperException('Too short scrape response.');
}
$torrents = array();
$index = 8;
foreach ($infohash as $hash) {
$retd = unpack("Nseeders/Ncompleted/Nleechers", substr($ret, $index, 12));
$retd['infohash'] = $hash;
$torrents[$hash] = $retd;
$index = $index + 12;
}
return ($torrents);
}
}
try {
$timeout = 2;
$scraper = new udptscraper($timeout);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ret = $scraper->scrape($row['announce'], $row['info_hash']);
}
foreach ($ret as $key => $value) {
$stmt = $conn->prepare("UPDATE torrents SET leechers='" . $value['leechers'] . "', seeders='" . $value['seeders'] . "', times_completed='" . $value['completed'] . "', last_action='" . get_date_time() . "', visible='yes' WHERE id = :torrentid");
$stmt->bindValue(':torrentid', $torrentid, PDO::PARAM_INT);
$stmt->execute();
}
}
catch (ScraperException $e) {
echo ('Error: ' . $e->getMessage() . "<br />\n");
echo ('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
?>
Create get-torrent-stats.php and upload to root /
GET (JSON) - AJAX call [seeders], [leechers] : id
<?
// AJAX Torrent Scrape - Get Stats - BETA - May 19, 2020
// Include database
$dsn = 'mysql:dbname=database;host=localhost;charset=utf8';
$user = 'username';
$password = 'password';
$torrentid = isset($_GET['id'])?intval($_GET['id']):0; // Get torrent ID ?id=
try {
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
die('Unable to connect to database');
}
$limit = 1;
$stmt = $conn->prepare("SELECT id, seeders, leechers FROM torrents WHERE id = :torrentid LIMIT :datalimit");
$stmt->bindParam(":datalimit", $limit, PDO::PARAM_INT);
$stmt->bindParam(":torrentid", $torrentid, PDO::PARAM_INT);
$stmt->execute();
$userData = array();
if ($stmt->rowCount() > 0) {
$usersactive = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($usersactive as $row => $data) {
$data['seeders'] = $row['seeders'];
$data['leechers'] = $row['leechers'];
array_push($userData, $usersactive);
}
}
echo json_encode($usersactive, JSON_UNESCAPED_SLASHES);
?>
add to header.php after jQuery
<? if (stripos($_SERVER['PHP_SELF'],'torrents-details.php') && $CURUSER) { ?>
<script>
// Get peer data
function fetchPeerData() {
$(document).ready(function () {
$.ajax({
url: "get-torrent-stats.php?id=<?=$id; ?>",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
html_to_append +=
'<div style="float:right"><span id="peers-updated"></span><span style="text-align:right;font-size:25px;color:#2E8B57">' +
item.seeders +
'</span><span style="text-align:right;font-size:25px;color:#C0C0C0;padding-left:10px;padding-right:5px">/</span><span style="text-align:right;font-size:18.75pt;color:#DC143C">' +
item.leechers +
'</span></div>';
});
$("#updated-stats").html(html_to_append);
$("#animate").toggleClass('flip');
$("#peers-updated").html("Peers updated").delay(1000).fadeIn().delay(2000).fadeOut();
}
});
});
// Update peer data
$(document).ready(function() {
$.ajax({
url: "trader-scrape.php?id=<?=$id; ?>",
method: "POST",
success: function (data) {
$("#peers-updated").html("Peers updated").delay(1000).fadeIn().delay(2000).fadeOut();
}
});
});
}
fetchPeerData();
setInterval(function () {
fetchPeerData()
}, 15000); // Update peer data every 15 sec on viewing torrent
<?
}
?>
</script>
Now place this anywhere you want on torrents-details.php - seed & peer data automatically scrapes and updates while browsing torrent-details.php and shows the dynamic count in the HTML below.
Leaves all the guess work out, and keep stats up to date on public trackers, it updates itself every 15 seconds or as any user views a torrent and their duration for that ID. If you don't have a good server, enough of these taxing calls on the CPU will get the best of you, just a notice.
<div id="updated-stats"></div>