One of the big issues with TT is scraping external torrents, the main thing to bare in mind is if the host allows all ports to be used. On most vps all ports are open and its worth checking the check.php to see if allow_url_fopen is enabled.
I wanted this to be part of my MVC/PDO version so ive been playing with this for a while not just scraping on torrents-details,php but also on importing torrents and uploading torrent.
This post will show my edits using the old TT scraper, the second post will show a new scraper which is a bit more modern which is much better. This post and the second are not related in any way - its one or the other.
While my code is different you should be able to patch it together using this post kindly shared by micromonkey https://torrenttrader.uk/topic?topicid=9795#post67051
The main difference for v3 is the directory location and the query - but as always if people want to try i will help with any conversion if you run into issues.
I post full code so i have a copy for future reference and sharing is caring
All three classes need to be required/included in backend/functions.php for v3
create Tscraper.php in backend folder
create Udptscraper.php in backend folder
create Httpscraper.php in backend folder
in torrents-import.php find if ($external=='yes' && $site_config['UPLOADSCRAPE']) {
that scraper block should look like this
in torrents-upload.php find
replace with
in torrents-details.php find
replace with
I wanted this to be part of my MVC/PDO version so ive been playing with this for a while not just scraping on torrents-details,php but also on importing torrents and uploading torrent.
This post will show my edits using the old TT scraper, the second post will show a new scraper which is a bit more modern which is much better. This post and the second are not related in any way - its one or the other.
While my code is different you should be able to patch it together using this post kindly shared by micromonkey https://torrenttrader.uk/topic?topicid=9795#post67051
The main difference for v3 is the directory location and the query - but as always if people want to try i will help with any conversion if you run into issues.
I post full code so i have a copy for future reference and sharing is caring
All three classes need to be required/included in backend/functions.php for v3
create Tscraper.php in backend folder
<?php
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;
}
}
create Udptscraper.php in backend folder
<?php
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";
//Connection request
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp, $packet);
//Connection response
$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);
//Scrape request
$hashes = '';
foreach ($infohash as $hash) {
$hashes .= pack('H*', $hash);
}
$packet = $current_connid . pack("N", 2) . pack("N", $transaction_id) . $hashes;
fwrite($fp, $packet);
//Scrape response
$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);
// Todo check for error string if response = 3
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);
}
}
create Httpscraper.php in backend folder
<?php
/*
Torrent HTTP Scraper
v1.0
2010 by Johannes Zinnau
johannes@johnimedia.de
Licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License
http://creativecommons.org/licenses/by-sa/3.0/
It would be very nice if you send me your changes on this class, so that i can include them if they are improve it.
Thanks!
Usage:
```
try{
$timeout = 2;
//Read only 4MiB of the scrape response
$maxread = 1024 * 4;
$scraper = new httptscraper($timeout,$maxread);
$ret = $scraper->scrape('http://tracker.tld:port/announce',array('0000000000000000000000000000000000000000'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
```
*/
/**
* Class HttpScraper
* @package Scrapers\Trackers
*/
class Httpscraper extends Tscraper
{
/**
* @var int
*/
protected $maxreadsize;
/**
* HttpScraper constructor.
* @param int $timeout
* @param int $maxreadsize
*/
public function __construct($timeout = 2, $maxreadsize = 4096)
{
$this->maxreadsize = $maxreadsize;
parent::__construct($timeout);
}
/* $url: Tracker url like: http://tracker.tld:port/announce or http://tracker.tld:port/scrape
$infohash: Infohash string or array. 40 char long infohash.
*/
/**
* @param string $url
* @param string $info_hash
* @return array
* @throws Exception\ScraperException
*/
public function scrape($url, $info_hash)
{
if (!is_array($info_hash)) {
$info_hash = array($info_hash);
}
foreach ($info_hash as $hash) {
if (!preg_match('#^[a-f0-9]{40}$#i', $hash)) {
throw new ScraperException('Invalid infohash: ' . $hash . '.');
}
}
$url = trim($url);
if (preg_match('%(http://.*?/)announce([^/]*)$%i', $url, $m)) {
$url = $m[1] . 'scrape' . $m[2];
} elseif (preg_match('%(http://.*?/)scrape([^/]*)$%i', $url, $m)) {
} else {
throw new ScraperException('Invalid tracker url: ' . $url);
}
$sep = preg_match('/\?.{1,}?/i', $url) ? '&' : '?';
$request_url = $url;
foreach ($info_hash as $hash) {
$request_url .= $sep . 'info_hash=' . rawurlencode(pack('H*', $hash));
$sep = '&';
}
ini_set('default_socket_timeout', $this->timeout);
$rh = @fopen($request_url, 'r');
if (!$rh) {
throw new ScraperException('Could not open HTTP connection.', 0, true);
}
stream_set_timeout($rh, $this->timeout);
$return = '';
$pos = 0;
while (!feof($rh) && $pos < $this->maxreadsize) {
$return .= fread($rh, 1024);
}
fclose($rh);
if (!substr($return, 0, 1) == 'd') {
throw new ScraperException('Invalid scrape response.');
}
$arr_scrape_data = Bencode::decode($return);
$torrents = array();
foreach ($info_hash as $hash) {
$ehash = pack('H*', $hash);
if (isset($arr_scrape_data['files'][$ehash])) {
$torrents[$hash] = array(
'infohash' => $hash,
'seeders' => (int) $arr_scrape_data['files'][$ehash]['complete'],
'completed' => (int) $arr_scrape_data['files'][$ehash]['downloaded'],
'leechers' => (int) $arr_scrape_data['files'][$ehash]['incomplete'],
);
} else {
$torrents[$hash] = false;
}
}
return $torrents;
}
}
in torrents-import.php find if ($external=='yes' && $site_config['UPLOADSCRAPE']) {
that scraper block should look like this
//EXTERNAL SCRAPE
if ($external == 'yes' && UPLOADSCRAPE) {
$ann = $TorrentInfo[0];
$annlist = array();
if ($TorrentInfo[6]) {
foreach ($TorrentInfo[6] as $ann) {
$annlist[] = $ann[0];
}
} else {
$annlist = array($ann);
}
$seeders = $leechers = $downloaded = null;
foreach ($annlist as $ann) {
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = str_replace("announce", "scrape", $path);
$tracker = implode("/", $tracker) . "/" . $path;
if ($oldpath == $path) {
continue;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $id]);
} }
//END SCRAPE
in torrents-upload.php find
if (!is_array($annlist)) {
$annlist = array(array($announce));
}
foreach ($annlist as $ann) {
foreach ($ann as $val) {
if (strtolower(substr($val, 0, 4)) != "udp:") {
SQL_Query_exec("INSERT INTO `announce` (`torrent`, `url`) VALUES($id, ".sqlesc($val).")");
}
}
}
replace with
$ann = $TorrentInfo[0];
$annlist = array();
if ($TorrentInfo[6]) {
foreach ($TorrentInfo[6] as $ann) {
$annlist[] = $ann[0];
}
} else {
$annlist = array($ann);
}
$seeders = $leechers = $downloaded = null;
foreach ($annlist as $ann) {
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = str_replace("announce", "scrape", $path);
$tracker = implode("/", $tracker) . "/" . $path;
if ($oldpath == $path) {
continue;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $infohash);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $id]);
}
in torrents-details.php find
while ($trow = mysqli_fetch_assoc($tres)) {
$ann = $trow["url"];
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = preg_replace("/^announce/", "scrape", $path);
$tracker = implode("/", $tracker)."/".$path;
if ($oldpath == $path) {
continue; // Scrape not supported, ignored
}
// TPB's tracker is dead. Use openbittorrent instead
if (preg_match("/thepiratebay.org/i", $tracker) || preg_match("/prq.to/", $tracker)) {
$tracker = "http://tracker.openbittorrent.com/scrape";
}
$stats = torrent_scrape_url($tracker, $row["info_hash"]);
if ($stats['seeds'] != -1) {
$seeders1 += $stats['seeds'];
$leechers1 += $stats['peers'];
$downloaded1 += $stats['downloaded'];
SQL_Query_exec("UPDATE `announce` SET `online` = 'yes', `seeders` = $stats[seeds], `leechers` = $stats[peers], `times_completed` = $stats[downloaded] WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
} else {
SQL_Query_exec("UPDATE `announce` SET `online` = 'no' WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
}
}
replace with
while ($trow = mysqli_fetch_assoc($tres)) {
$ann = $TorrentInfo[0];
$annlist = array();
if ($TorrentInfo[6]) {
foreach ($TorrentInfo[6] as $ann) {
$annlist[] = $ann[0];
}
} else {
$annlist = array($ann);
}
$seeders = $leechers = $downloaded = null;
foreach ($annlist as $ann) {
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = str_replace("announce", "scrape", $path);
$tracker = implode("/", $tracker) . "/" . $path;
if ($oldpath == $path) {
continue;
}
// Is It udp OR http
if (preg_match('/udp:\/\//', $tracker)) {
$udp = true;
try
{
$timeout = 5;
$udp = new Udptscraper($timeout);
$stats = $udp->scrape($tracker, $tres["info_hash"]);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $e) {
$e->isConnectionError();
}
} else {
$http = true;
try {
$timeout = 5;
$http = new Httpscraper($timeout);
$stats = $http->scrape($tracker, $tres["info_hash"]);
//print_r($stats); exit();
foreach ($stats as $idu => $scrape) {
$seeders += $scrape['seeders'];
$leechers += $scrape['leechers'];
$downloaded += $scrape['completed'];
}
} catch (ScraperException $exc) {
$exc->isConnectionError();
}
}
}
// Update the Torrent
if ($seeders !== null) {
DB::run("
UPDATE torrents
SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
WHERE id = ?",
[$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $tres['id']]);
} else {
DB::run("
UPDATE torrents
SET last_action = ?
WHERE id=?", [TimeDate::get_date_time(), $tres['id']]);
}
