Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
Scraper Class + PECL Parallel Support
You don't have permission for this action!
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / Torrent Trader / v3 Support

2023-03-11 23:11:11
This enables you to scrape multiple UDP/HTTP(S) announce urls against info hashes. It accepts array or single strings. It enables custom cURL options, a optional Bencode object, and optional parameters to enable/disable cURL (defaults to streams) and enable/disable PECL parallel tasks.

I built this over the weekend mostly from scratch with the exception of the UDP connection logic, which was ported and updated. Since the original "Scrapeer", "tscraper" classes are falling behind and becoming non-functional.. I decided it was time for a PHP 8x rewrite.

Requires: PHP 8.1+, sockets, PECL Parallel extension (optional)

---

Parameters: Timeout | Enable Parelle | Enable cURL | Bencode | cURL Options
$scraper = new ScrapeTorrent(..., ..., ..., ..., ...);


Methods:

$results = $scraper->scrapeAll(array|string, array|string);
$results = $scraper->scrape(string, string);



<?
// Switch-Torrents Torrent Scraper w/ PECL Parallel support
// Supports protocols: UDP | HTTP | HTTPS - March/2023-v1.1
// cURL | Streams
class ScrapeTorrent
{
   private int $timeout;
   private bool $parallel = false;
   private bool $usecurl = false;
   private int $maxhashes;

   private string $useragent;
   private ?Bencode $bencode;

   private array $curlopt = [];

   private bool $verifypeer;
   private bool $verifyname;

   public function __construct(int $timeout = 2, bool $parallel = false, bool $usecurl = false, ?Bencode $bencode = null, array $curlopts = [])
   {
       $this->useragent = 'Switch-Torrents Scrape/1.0';
       $this->maxhashes = 74;
       $this->timeout = $timeout;
       $this->bencode = $bencode ?? null;

       // ssl
       $this->verifypeer = true;
       $this->verifyname = true;

       if (function_exists('curl_init') && $usecurl)
       {
           $this->usecurl = true;
           $this->curlopt = array(
               CURLOPT_RETURNTRANSFER => true,
               CURLOPT_TIMEOUT => $timeout,
               CURLOPT_FOLLOWLOCATION => true,
               CURLOPT_SSL_VERIFYPEER => $this->verifypeer,
               CURLOPT_SSL_VERIFYHOST => 2
           );
           $this->curlopt = !empty($curlopts) ? $curlopts : $this->curlopt;
       }

       if (extension_loaded('parallel') && $parallel)
       {
           $this->parallel = true;
       }
   }

   public function scrapeAll(array|string $urls, array|string $infohashes) : array
   {
       if (!is_array($urls))
       {
           $urls = [$urls];
       }
       if (!is_array($infohashes))
       {
           $infohashes = [$infohashes];
       }

       $torrents = array();
       $results = array();

       if ($this->parallel)
       {
           $pool = new \parallel\Runtime;

           foreach ($urls as $url)
           {
               foreach ($infohashes as $infohash)
               {
                   $task = $pool->run(function () use ($url, $infohash)
                   {
                       spl_autoload_register(function ($class)
                       {
                           include_once $class . '.php';
                       });
                       return (new \ScrapeTorrent)->scrape($url, $infohash, (new \Bencode));
                   });
                   $results[] = $task;
               }
           }

           foreach ($results as $result)
           {
               $result->value();
           }
       }
       else
       {
           foreach ($urls as $url)
           {
               foreach ($infohashes as $infohash)
               {
                   $results[] = $this->scrape($url, $infohash, $this->bencode);
               }
           }
       }

       if ($this->parallel)
       {
           foreach ($results as $result)
           {
               if (is_array($result->value()))
               {
                   foreach ($result->value() as $infohash => $stats)
                   {
                       $torrents[$infohash] = $stats;
                   }
               }
           }
       }
       else
       {
           foreach ($results as $result)
           {
               if (is_array($result))
               {
                   foreach ($result as $infohash => $stats)
                   {
                       $torrents[$infohash] = $stats;
                   }
               }
           }
       }

       return $torrents;
   }

   public function scrape(string $url, string $infohash, ?Bencode $bencode = null) : array
   {
       if (!is_array($infohash))
       {
           $infohash = array(
               $infohash
           );
       }

       for ($i = 0;$i < count($infohash);$i++)
       {
           if (!preg_match('#^[a-f0-9]{40}$#i', $infohash[$i]))
           {
               ScrapeException::Message('Invalid infohash: ' . $infohash[$i] . '.');
           }
       }

       if (count($infohash) > $this->maxhashes)
       {
           ScrapeException::Message('Too many infohashes provided.');
       }

       if (!preg_match('#^(udp|http|https)://([^:/]*)(?::([0-9]*))?(?:/)?#si', $url, $m))
       {
           ScrapeException::Message('Invalid tracker url.');
       }

       $torrents = array();
       $tracker = $m[1] . '://' . $m[2];
       $port = isset($m[3]) ? $m[3] : ($m[1] === 'https' ? 443 : 80);
       $transaction_id = mt_rand(0, 65535);

       if ($m[1] === 'http' || $m[1] === 'https')
       {

           if (!($this->bencode instanceof \Bencode) && !($bencode instanceof \Bencode))
           {
               ScrapeException::Message('Bencode is required for HTTP/HTTPS scraping.');
           }

           $port = $m[1] === 'http' ? 80 : 443;
           $torrents = $this->fetch_http($url, $m[2], $port, $this->timeout, $infohash, $m[1], $this->usecurl);

       }
       elseif ($m[1] === 'udp')
       {

           $fp = fsockopen('udp://' . $m[2], $port, $errno, $errstr, $this->timeout);
           if (!$fp)
           {
               ScrapeException::Message('Could not open ' . strtoupper($m[1]) . ' 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)
           {
               ScrapeException::Message('No connection response.');
           }

           if (strlen($ret) < 16)
           {
               ScrapeException::Message('Too short connection response.');
           }

           $retd = unpack("Naction/Ntransid", $ret);
           if ($retd['action'] != 0 || $retd['transid'] != $transaction_id)
           {
               ScrapeException::Message('Invalid connection response.');
           }

           $hashes = '';
           $packhash = 'H*';
           $current_connid = substr($ret, 8, 8);

           foreach ($infohash as $hash)
           {
               $hashes .= pack($packhash, $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)
           {
               ScrapeException::Message('No scrape response.');
           }

           if (strlen($ret) < 8)
           {
               ScrapeException::Message('Too short scrape response.');
           }

           $retd = unpack("Naction/Ntransid", $ret);

           if ($retd['action'] != 2 || $retd['transid'] != $transaction_id)
           {
               ScrapeException::Message('Invalid scrape response.');
           }

           if (strlen($ret) < $readlength)
           {
               ScrapeException::Message('Too short scrape response.');
           }

           $index = 8;
           $unpack = "Nseeders/Ncompleted/Nleechers";

           foreach ($infohash as $hash)
           {
               $retd = unpack($unpack, substr($ret, $index, 12));
               $retd['infohash'] = $hash;
               $torrents[$hash] = $retd;
               $index = $index + 12;
               $torrents[$hash]['type'] = $m[1];

           }
       }

       $empty = null;
       foreach ($torrents as $torrent)
       {
           if (!empty($torrent))
           {
               $empty = $torrent;
               break;
           }
       }

       $default = array(
           'complete' => 0,
           'downloaded' => 0,
           'incomplete' => 0,
           'infohash' => $hash,
           'type' => $m[1]
       );

       foreach ($torrents as $hash => &$torrent)
       {
           if (empty($torrent))
           {
               $torrent = ($empty ?: $default);
               $torrent['infohash'] = $hash;
           }
       }

       unset($torrent);
       return $torrents;
   }

   private function decodeData(string $data) : array
   {
       if (empty($data))
       {
           ScrapeException::Message('Input data cannot be empty.');
       }

       $stream = fopen('php://memory', 'r+');
       fwrite($stream, $data);
       rewind($stream);

       $decoder = new \Decoder(stream: $stream, bigInt: BigInt::INTERNAL);

       return $decoder->decode();
   }

   private function fetch_http(string $url, string $host, int $port, int $timeout, array $hashes, string $prefix, bool $usecurl = false):
       array
       {
           $storestats = array();
           $ann = (strpos($url, 'scrape') !== false) ? 'scrape' : ((strpos($url, 'announce') !== false) ? 'announce' : '');

           if (!$ann)
           {
               ScrapeException::Message('URL does not contain scrape or announce.');
           }

           $response = '';
           foreach ($hashes as $hash)
           {
               $url = "$prefix://$host/$ann?info_hash=$hash";
               try
               {
                   if ($usecurl)
                   {
                       $ch = curl_init();
                       curl_setopt_array($ch, $this->curlopt);
                       curl_setopt($ch, CURLOPT_URL, $url);

                       $multihandle = curl_multi_init();
                       curl_multi_add_handle($multihandle, $ch);

                       $active = null;
                       do
                       {
                           $status = curl_multi_exec($multihandle, $active);
                           if ($active)
                           {
                               curl_multi_select($multihandle);
                           }
                       }
                       while ($status === CURLM_CALL_MULTI_PERFORM || $active);

                       if ($status !== CURLM_OK)
                       {
                           ScrapeException::Message('HTTP request failed.');
                       }

                       $response = curl_multi_getcontent($ch);
                       curl_multi_remove_handle($multihandle, $ch);
                       curl_multi_close($multihandle);
                   }
                   else
                   {
                       $context = stream_context_create(array(
                           $prefix => array(
                               'timeout' => $timeout,
                               'user_agent' => $this->useragent,
                               'header' => 'Content-Type: text/plain',
                               'ssl' => array(
                                   'verify_peer' => $this->verifypeer,
                                   'verify_peer_name' => $this->verifyname
                               )
                           )
                       ));
                       $stream = @fopen($url, 'r', false, $context);
                       if ($stream)
                       {
                           $response = stream_get_contents($stream);
                           fclose($stream);
                       }
                       else
                       {
                           ScrapeException::Message('Could not open stream for URL.');
                       }
                   }

                   if (isset($response))
                   {
                       $decoded = $this->decodeData($response);
                   }

                   if (isset($decoded['files']))
                   {
                       unset($decoded['files'][0][$hash]['name']);
                   }

                   $storestats[$hash] = $decoded['files'][0][$hash] ? ? $this->decodeData($response);
                   $storestats[$hash]['infohash'] = $hash;
                   $storestats[$hash]['type'] = $prefix;

               }
               catch(Exception $e)
               {
                   //ScrapeException::Message("Error fetching $prefix");
                   $storestats[$hash] = array();
               }
           }

           return $storestats;
       }
   }


Exception class

<?
class ScrapeException extends Exception
{
   public static function Message(string $message)
   {
       throw new self($message);
   }
}


Usage:


$urls = array(
   'udp://tracker.opentrackr.org:1337/announce',
   'udp://tracker.opentrackr.org:1337/announce'

);
$infohashes = array(
   '9269f2bf2c48756ac1f98fb3abdee3920893388f',
   '5d33dede60ab4d24b1b720d0dee2df9505605397'
);

try
{
   // Optional: cURL Options
   $curlopts = array(
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_TIMEOUT => 2,
       CURLOPT_FOLLOWLOCATION => true,
   );
   // Optional: HTTP/HTTPS scraping
   $bencode = new Bencode;
   // Optional Parameters: Timeout | Enable Parelle | Enable cURL | Bencode | cURL Options
   $scraper = new ScrapeTorrent(2, true, true, $bencode, $curlopts);

   // Methods: scrapeAll(array|string, array|string) | scrape(string, string)
   $results = $scraper->scrapeAll($urls, $infohashes);

   // Test
   print_r($results);

}
catch(\ScrapeException $e)
{
   echo $e->getMessage();
}


Autoloading
If you are not autoloading your classes, you need to include the class.

include_once 'ScrapeTorrent.php';
Last edited by STorrents2020 on 2023-03-13 07:19:13
2023-03-13 05:19:01
Class complete. I encourage anyone to test or develop this. I took it as far as I could. Enjoy.
2023-03-13 05:31:25
just catching up on post and this and the cache class look interesting mate, nice work ill test this this week

2023-03-13 07:21:22
It was fun! It allowed me to learn a lot about classes and different things I can do with them. Thats valuable.

I got some time in for Torrent Signing class. Completed in an hour, it works great too!
I'll post this week.
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 3
  • Members: 0
  • Guests online: 3
  • Comments: 3
  • Messages: 1,728