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
TT Scraper
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / M-BiTsy / M-BiTsy Support

2021-06-15 19:46:28
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
<?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']]);
           }
2021-06-15 19:47:47
This is the new scraper which i now use and i will try post it for v3 although i can not test it
i think i have converted most for v3

first in backend/functions.php include two classes


require_once(BACKEND."/Scraper.php");
require_once(BACKEND."/Torrent.php");


create backend/Scraper.php

<?php

declare(strict_types=1);
/**
* Scrapeer, a tiny PHP library that lets you scrape
* HTTP(S) and UDP trackers for torrent information.
*
* This file is extensively based on Johannes Zinnau's
* work, which can be found at https://goo.gl/7hyjde
*
* Licensed under a Creative Commons
* Attribution-ShareAlike 3.0 Unported License
* http://creativecommons.org/licenses/by-sa/3.0
*/

/**
* The one and only class you'll ever need.
*/
class Scraper
{
   /**
    * Current version of Scrapeer.
    *
    * @var string
    */
   const VERSION = '0.6.0';

   /**
    * Array of errors.
    *
    * @var array
    */
   private $errors = [];

   /**
    * Array of infohashes to scrape.
    *
    * @var array
    */
   private $infohashes = [];

   /**
    * Timeout for a single tracker.
    *
    * @var int
    */
   private $timeout;

   /**
    * Initiates the scraper.
    *
    * @param array|string $hashes       list (>1) or string of infohash(es)
    * @param array|string $trackers     list (>1) or string of tracker(s)
    * @param null|int     $max_trackers Optional. Maximum number of trackers to be scraped, Default all.
    * @param int          $timeout      Optional. Maximum time for each tracker scrape in seconds, Default 2.
    * @param bool         $announce     Optional. Use announce instead of scrape, Default false.
    *
    * @throws Exception|RangeException in case of invalid amount of info-hashes
    *
    * @return array list of results
    */
   public function scrape($hashes, $trackers, $max_trackers = null, $timeout = 2, $announce = false)
   {
       $final_result = [];

       if (empty($trackers)) {
           $this->errors[] = 'No tracker specified, aborting.';

           return $final_result;
       }
       if (!is_array($trackers)) {
           $trackers = [$trackers];
       }

       if (is_int($timeout)) {
           $this->timeout = $timeout;
       } else {
           $this->timeout  = 2;
           $this->errors[] = 'Timeout must be an integer. Using default value.';
       }

       try {
           $this->infohashes = $this->normalize_infohashes($hashes);
       } catch (RangeException $e) {
           $this->errors[] = $e->getMessage();

           return $final_result;
       }

       $max_iterations = is_int($max_trackers) ? $max_trackers : count($trackers);
       foreach ($trackers as $index => $tracker) {
           if (!empty($this->infohashes) && $index < $max_iterations) {
               $tracker  = is_array($tracker) ? $tracker[0] : $tracker;
               $info     = parse_url($tracker);
               $protocol = $info['scheme'];
               $host     = $info['host'];
               if (empty($protocol) || empty($host)) {
                   $this->errors[] = 'Skipping invalid tracker (' . $tracker . ').';

                   continue;
               }

               $port         = $info['port'] ?? null;
               $path         = $info['path'] ?? null;
               $passkey      = $this->get_passkey($path);
               $result       = $this->try_scrape($protocol, $host, $port, $passkey, $announce);
               $final_result = array_merge($final_result, $result);

               continue;
           }

           break;
       }

       return $final_result;
   }

   /**
    * Checks if there are any errors.
    *
    * @return bool true or false, depending if errors are present or not
    */
   public function has_errors()
   {
       return !empty($this->errors);
   }

   /**
    * Returns all the errors that were logged.
    *
    * @return array all the logged errors
    */
   public function get_errors()
   {
       return $this->errors;
   }

   /**
    * Normalizes the given hashes.
    *
    * @param array $infohashes list of infohash(es)
    *
    * @throws RangeException if amount of valid infohashes > 64 or < 1
    *
    * @return array normalized infohash(es)
    */
   private function normalize_infohashes($infohashes)
   {
       if (!is_array($infohashes)) {
           $infohashes = [$infohashes];
       }

       foreach ($infohashes as $index => $infohash) {
           if (!preg_match('/^[a-f0-9]{40}$/i', $infohash)) {
               $this->errors[] = 'Invalid infohash skipped (' . $infohash . ').';
               unset($infohashes[$index]);
           }
       }

       $total_infohashes = count($infohashes);
       if ($total_infohashes > 64 || $total_infohashes < 1) {
           throw new RangeException('Invalid amount of valid infohashes (' . $total_infohashes . ').');
       }

       return array_values($infohashes);
   }

   /**
    * Returns the passkey found in the scrape request.
    *
    * @param string $path path from the scrape request
    *
    * @return string passkey or empty string
    */
   private function get_passkey($path)
   {
       if (!empty($path) && preg_match('/[a-z0-9]{32}/i', $path, $matches)) {
           return '/' . $matches[0];
       }

       return '';
   }

   /**
    * Tries to scrape with a single tracker.
    *
    * @param string $protocol protocol of the tracker
    * @param string $host     domain or address of the tracker
    * @param int    $port     Optional. Port number of the tracker.
    * @param string $passkey  Optional. Passkey provided in the scrape request.
    * @param bool   $announce Optional. Use announce instead of scrape, Default false.
    *
    * @throws Exception in case of unsupported protocol
    *
    * @return array list of results
    */
   private function try_scrape($protocol, $host, $port, $passkey, $announce)
   {
       $infohashes       = $this->infohashes;
       $this->infohashes = [];
       $results          = [];

       try {
           switch ($protocol) {
               case 'udp':
                   $port    = $port ?? 80;
                   $results = $this->scrape_udp($infohashes, $host, $port, $announce);

                   break;
               case 'http':
                   $port    = $port ?? 80;
                   $results = $this->scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce);

                   break;
               case 'https':
                   $port    = $port ?? 443;
                   $results = $this->scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce);

                   break;
               default:
                   throw new Exception('Unsupported protocol (' . $protocol . '://' . $host . ').');
           }
       } catch (Exception $e) {
           $this->infohashes = $infohashes;
           $this->errors[]   = $e->getMessage();
       }

       return $results;
   }

   /**
    * Initiates the HTTP(S) scraping.
    *
    * @param array|string $infohashes list (>1) or string of infohash(es)
    * @param string       $protocol   protocol to use for the scraping
    * @param string       $host       domain or IP address of the tracker
    * @param int          $port       Optional. Port number of the tracker, Default 80 (HTTP) or 443 (HTTPS).
    * @param string       $passkey    Optional. Passkey provided in the scrape request.
    * @param bool         $announce   Optional. Use announce instead of scrape, Default false.
    *
    * @throws Exception
    *
    * @return array list of results
    */
   private function scrape_http($infohashes, $protocol, $host, $port, $passkey, $announce)
   {
       if (true === $announce) {
           $response = $this->http_announce($infohashes, $protocol, $host, $port, $passkey);
       } else {
           $query    = $this->http_query($infohashes, $protocol, $host, $port, $passkey);
           $response = $this->http_request($query, $host, $port);
       }

       return $this->http_data($response, $infohashes, $host);
   }

   /**
    * Builds the HTTP(S) query.
    *
    * @param array|string $infohashes list (>1) or string of infohash(es)
    * @param string       $protocol   protocol to use for the scraping
    * @param string       $host       domain or IP address of the tracker
    * @param int          $port       port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
    * @param string       $passkey    Optional. Passkey provided in the scrape request.
    *
    * @return string request query
    */
   private function http_query($infohashes, $protocol, $host, $port, $passkey)
   {
       $tracker_url  = $protocol . '://' . $host . ':' . $port . $passkey;
       $scrape_query = '';

       foreach ($infohashes as $index => $infohash) {
           if ($index > 0) {
               $scrape_query .= '&info_hash=' . urlencode(pack('H*', $infohash));
           } else {
               $scrape_query .= '/scrape?info_hash=' . urlencode(pack('H*', $infohash));
           }
       }

       return $tracker_url . $scrape_query;
   }

   /**
    * Executes the query and returns the result.
    *
    * @param string $query the query that will be executed
    * @param string $host  domain or IP address of the tracker
    * @param int    $port  port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
    *
    * @throws Exception if the response isn't valid
    * @throws Exception if the connection can't be established
    *
    * @return string request response
    */
   private function http_request($query, $host, $port)
   {
       $context = stream_context_create([
           'http' => [
               'timeout' => $this->timeout,
           ],
       ]);

       if (false === ($response = @file_get_contents($query, false, $context))) {
           throw new Exception('Invalid scrape connection (' . $host . ':' . $port . ').');
       }

       if (substr($response, 0, 12) !== 'd5:filesd20:') {
           throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
       }

       return $response;
   }

   /**
    * Builds the query, sends the announce request and returns the data.
    *
    * @param array|string $infohashes list (>1) or string of infohash(es)
    * @param string       $protocol   protocol to use for the scraping
    * @param string       $host       domain or IP address of the tracker
    * @param int          $port       port number of the tracker, Default 80 (HTTP) or 443 (HTTPS)
    * @param string       $passkey    Optional. Passkey provided in the scrape request.
    *
    * @throws Exception if the connection can't be established
    *
    * @return string request response
    */
   private function http_announce($infohashes, $protocol, $host, $port, $passkey)
   {
       $tracker_url = $protocol . '://' . $host . ':' . $port . $passkey;
       $context     = stream_context_create([
           'http' => [
               'timeout' => $this->timeout,
           ],
       ]);

       $response_data = '';
       foreach ($infohashes as $infohash) {
           $query = $tracker_url . '/announce?info_hash=' . urlencode(pack('H*', $infohash));
           if (false === ($response = @file_get_contents($query, false, $context))) {
               throw new Exception('Invalid announce connection (' . $host . ':' . $port . ').');
           }

           if (substr($response, 0, 12) !== 'd8:completei'
               || substr($response, 0, 46) === 'd8:completei0e10:downloadedi0e10:incompletei1e') {
               continue;
           }

           $ben_hash = '20:' . pack('H*', $infohash) . 'd';
           $response_data .= $ben_hash . $response;
       }

       return $response_data;
   }

   /**
    * Parses the response and returns the data.
    *
    * @param string $response   the response that will be parsed
    * @param array  $infohashes list of infohash(es)
    * @param string $host       domain or IP address of the tracker
    *
    * @return array parsed data
    */
   private function http_data($response, $infohashes, $host)
   {
       $torrents_data = [];

       foreach ($infohashes as $infohash) {
           $ben_hash  = '20:' . pack('H*', $infohash) . 'd';
           $start_pos = strpos($response, $ben_hash);
           if (false !== $start_pos) {
               $start = $start_pos + 24;
               $head  = substr($response, $start);
               $end   = strpos($head, 'ee') + 1;
               $data  = substr($response, $start, $end);

               $seeders                 = '8:completei';
               $torrent_info['seeders'] = $this->get_information($data, $seeders, 'e');

               $completed                 = '10:downloadedi';
               $torrent_info['completed'] = $this->get_information($data, $completed, 'e');

               $leechers                 = '10:incompletei';
               $torrent_info['leechers'] = $this->get_information($data, $leechers, 'e');

               $torrents_data[$infohash] = $torrent_info;
           } else {
               $this->collect_infohash($infohash);
               $this->errors[] = 'Invalid infohash (' . $infohash . ') for tracker: ' . $host . '.';
           }
       }

       return $torrents_data;
   }

   /**
    * Parses a string and returns the data between $start and $end.
    *
    * @param string $data  the data that will be parsed
    * @param string $start beginning part of the data
    * @param string $end   ending part of the data
    *
    * @return int parsed information or 0
    */
   private function get_information($data, $start, $end)
   {
       $start_pos = strpos($data, $start);
       if (false !== $start_pos) {
           $start       = $start_pos + strlen($start);
           $head        = substr($data, $start);
           $end         = strpos($head, $end);
           $information = substr($data, $start, $end);

           return (int) $information;
       }

       return 0;
   }

   /**
    * Initiates the UDP scraping.
    *
    * @param array|string $infohashes list (>1) or string of infohash(es)
    * @param string       $host       domain or IP address of the tracker
    * @param int          $port       Optional. Port number of the tracker, Default 80.
    * @param bool         $announce   Optional. Use announce instead of scrape, Default false.
    *
    * @throws Exception
    *
    * @return array list of results
    */
   private function scrape_udp($infohashes, $host, $port, $announce)
   {
       list($socket, $transaction_id, $connection_id) = $this->prepare_udp($host, $port);

       if (true === $announce) {
           $response = $this->udp_announce($socket, $infohashes, $connection_id);
           $keys     = 'Nleechers/Nseeders';
           $start    = 12;
           $end      = 16;
           $offset   = 20;
       } else {
           $response = $this->udp_scrape($socket, $infohashes, $connection_id, $transaction_id, $host, $port);
           $keys     = 'Nseeders/Ncompleted/Nleechers';
           $start    = 8;
           $end      = $offset      = 12;
       }

       return $this->udp_scrape_data($response, $infohashes, $host, $keys, $start, $end, $offset);
   }

   /**
    * Prepares the UDP connection.
    *
    * @param string $host domain or IP address of the tracker
    * @param int    $port Optional. Port number of the tracker, Default 80.
    *
    * @throws Exception
    *
    * @return array created socket, transaction ID and connection ID
    */
   private function prepare_udp($host, $port)
   {
       $socket         = $this->udp_create_connection($host, $port);
       $transaction_id = $this->udp_connection_request($socket);
       $connection_id  = $this->udp_connection_response($socket, $transaction_id, $host, $port);

       return [$socket, $transaction_id, $connection_id];
   }

   /**
    * Creates the UDP socket and establishes the connection.
    *
    * @param string $host domain or IP address of the tracker
    * @param int    $port port number of the tracker, Default 80
    *
    * @throws Exception if the socket couldn't be created or connected to
    *
    * @return resource $socket created and connected socket
    */
   private function udp_create_connection($host, $port)
   {
       if (false === ($socket = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))) {
           throw new Exception("Couldn't create socket.");
       }

       $timeout = $this->timeout;
       socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $timeout, 'usec' => 0]);
       socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => $timeout, 'usec' => 0]);
       if (false === @socket_connect($socket, $host, $port)) {
           throw new Exception("Couldn't connect to socket.");
       }

       return $socket;
   }

   /**
    * Writes to the connected socket and returns the transaction ID.
    *
    * @param resource $socket the socket resource
    *
    * @throws Exception if the socket couldn't be written to
    *
    * @return int the transaction ID
    */
   private function udp_connection_request($socket)
   {
       $connection_id  = "\x00\x00\x04\x17\x27\x10\x19\x80";
       $action         = pack('N', 0);
       $transaction_id = mt_rand(0, 2147483647);
       $buffer         = $connection_id . $action . pack('N', $transaction_id);
       if (false === @socket_write($socket, $buffer, strlen($buffer))) {
           socket_close($socket);

           throw new Exception("Couldn't write to socket.");
       }

       return $transaction_id;
   }

   /**
    * Reads the connection response and returns the connection ID.
    *
    * @param resource $socket         the socket resource
    * @param int      $transaction_id the transaction ID
    * @param string   $host           domain or IP address of the tracker
    * @param int      $port           port number of the tracker, Default 80
    *
    * @throws Exception if anything fails with the scraping
    *
    * @return string the connection ID
    */
   private function udp_connection_response($socket, $transaction_id, $host, $port)
   {
       if (false === ($response = @socket_read($socket, 16))) {
           socket_close($socket);

           throw new Exception('Invalid scrape connection! (' . $host . ':' . $port . ').');
       }

       if (strlen($response) < 16) {
           socket_close($socket);

           throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
       }

       $result = unpack('Naction/Ntransaction_id', $response);
       if (0 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
           socket_close($socket);

           throw new Exception('Invalid scrape result (' . $host . ':' . $port . ').');
       }

       return substr($response, 8, 8);
   }

   /**
    * Reads the socket response and returns the torrent data.
    *
    * @param resource $socket         the socket resource
    * @param array    $hashes         list (>1) or string of infohash(es)
    * @param string   $connection_id  the connection ID
    * @param int      $transaction_id the transaction ID
    * @param string   $host           domain or IP address of the tracker
    * @param int      $port           port number of the tracker, Default 80
    *
    * @throws Exception if anything fails while reading the response
    *
    * @return string response data
    */
   private function udp_scrape($socket, $hashes, $connection_id, $transaction_id, $host, $port)
   {
       $this->udp_scrape_request($socket, $hashes, $connection_id, $transaction_id);

       $read_length = 8 + (12 * count($hashes));
       if (false === ($response = @socket_read($socket, $read_length))) {
           socket_close($socket);

           throw new Exception('Invalid scrape connection (' . $host . ':' . $port . ').');
       }
       socket_close($socket);

       if (strlen($response) < $read_length) {
           throw new Exception('Invalid scrape response (' . $host . ':' . $port . ').');
       }

       $result = unpack('Naction/Ntransaction_id', $response);
       if (2 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
           throw new Exception('Invalid scrape result (' . $host . ':' . $port . ').');
       }

       return $response;
   }

   /**
    * Writes to the connected socket.
    *
    * @param resource $socket         the socket resource
    * @param array    $hashes         list (>1) or string of infohash(es)
    * @param string   $connection_id  the connection ID
    * @param int      $transaction_id the transaction ID
    *
    * @throws Exception if the socket couldn't be written to
    */
   private function udp_scrape_request($socket, $hashes, $connection_id, $transaction_id)
   {
       $action = pack('N', 2);

       $infohashes = '';
       foreach ($hashes as $infohash) {
           $infohashes .= pack('H*', $infohash);
       }

       $buffer = $connection_id . $action . pack('N', $transaction_id) . $infohashes;
       if (false === @socket_write($socket, $buffer, strlen($buffer))) {
           socket_close($socket);

           throw new Exception("Couldn't write to socket.");
       }
   }

   /**
    * Writes the announce to the connected socket.
    *
    * @param resource $socket        the socket resource
    * @param array    $hashes        list (>1) or string of infohash(es)
    * @param string   $connection_id the connection ID
    *
    * @throws Exception if the socket couldn't be written to
    *
    * @return string torrent(s) data
    */
   private function udp_announce($socket, $hashes, $connection_id)
   {
       $action     = pack('N', 1);
       $downloaded = $left = $uploaded = "\x30\x30\x30\x30\x30\x30\x30\x30";
       $peer_id    = $this->random_peer_id();
       $event      = pack('N', 3);
       $ip_addr    = pack('N', 0);
       $key        = pack('N', mt_rand(0, 2147483647));
       $num_want   = -1;
       $ann_port   = pack('N', mt_rand(0, 255));

       $response_data = '';
       foreach ($hashes as $infohash) {
           $transaction_id = mt_rand(0, 2147483647);
           $buffer         = $connection_id . $action . pack('N', $transaction_id) . pack('H*', $infohash) .
               $peer_id . $downloaded . $left . $uploaded . $event . $ip_addr . $key . $num_want . $ann_port;

           if (false === @socket_write($socket, $buffer, strlen($buffer))) {
               socket_close($socket);

               throw new Exception("Couldn't write announce to socket.");
           }

           $response = $this->udp_verify_announce($socket, $transaction_id);
           if (false === $response) {
               continue;
           }

           $response_data .= $response;
       }
       socket_close($socket);

       return $response_data;
   }

   /**
    * Generates a random peer ID.
    *
    * @return string generated peer ID
    */
   private function random_peer_id()
   {
       $identifier = '-SP0054-';
       $chars      = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

       return $identifier . substr(str_shuffle($chars), 0, 12);
   }

   /**
    * Verifies the correctness of the announce response.
    *
    * @param resource $socket         the socket resource
    * @param int      $transaction_id the transaction ID
    *
    * @return string response data
    */
   private function udp_verify_announce($socket, $transaction_id)
   {
       if (false === ($response = @socket_read($socket, 20))) {
           return false;
       }

       if (strlen($response) < 20) {
           return false;
       }

       $result = unpack('Naction/Ntransaction_id', $response);
       if (1 !== $result['action'] || $result['transaction_id'] !== $transaction_id) {
           return false;
       }

       return $response;
   }

   /**
    * Reads the socket response and returns the torrent data.
    *
    * @param string $response data from the request response
    * @param array  $hashes   list (>1) or string of infohash(es)
    * @param string $host     domain or IP address of the tracker
    * @param string $keys     keys for the unpacked information
    * @param int    $start    start of the content we want to unpack
    * @param int    $end      end of the content we want to unpack
    * @param int    $offset   offset to the next content part
    *
    * @return array scraped torrent data
    */
   private function udp_scrape_data($response, $hashes, $host, $keys, $start, $end, $offset)
   {
       $torrents_data = [];

       foreach ($hashes as $infohash) {
           $byte_string = substr($response, $start, $end);
           $data        = unpack('N', $byte_string);
           $content     = $data[1];
           if (!empty($content)) {
               $results                  = unpack($keys, $byte_string);
               $torrents_data[$infohash] = $results;
           } else {
               $this->collect_infohash($infohash);
               $this->errors[] = 'Invalid infohash (' . $infohash . ') for tracker: ' . $host . '.';
           }
           $start += $offset;
       }

       return $torrents_data;
   }

   /**
    * Collects info-hashes that couldn't be scraped.
    *
    * @param string $infohash infohash that wasn't scraped
    */
   private function collect_infohash($infohash)
   {
       $this->infohashes[] = $infohash;
   }
}


create backend/Torrent.php
<?php

declare(strict_types=1);

/**
* Torrent.
*
* PHP version 7.2+ (with cURL extension enabled)
*
* Features:
* - Decode torrent file or data from local file and distant url
* - Build torrent from source folder/file(s) or distant url
* - Super easy usage & syntax
* - Silent Exception error system
*
* @author   Adrien Gibrat <adrien.gibrat@gmail.com>
* @tester   Jeong, Anton, dokcharlie, official testers ;) Thanks for your precious feedback
* @copyleft 2010 - Just use it!
*
* @license  http://www.gnu.org/licenses/gpl.html GNU General Public License version 3
*
* @version  0.1.0
*/


/**
* Class Torrent.
*/
class Torrent
{
   /**
    * @const float Default http timeout
    */
   public const TIMEOUT = 30;

   /**
    * @var array List of error occurred
    */
   protected static $errors = [];
   /**
    * @var string
    */
   protected $comment;
   /**
    * @var array
    */
   protected $info;
   /**
    * @var array
    */
   protected $httpseeds;
   /**
    * @var mixed
    */
   protected $announce;

   /** Read and decode torrent file/data OR build a torrent from source folder/file(s)
    * Supported signatures:
    * - Torrent(); // get an instance (useful to scrape and check errors)
    * - Torrent(string $torrent); // analyze a torrent file
    * - Torrent(string $torrent, string $announce);
    * - Torrent(string $torrent, array $meta);
    * - Torrent(string $file_or_folder); // create a torrent file
    * - Torrent(string $file_or_folder, string $announce_url, int $piece_length);
    * - Torrent(string $file_or_folder, array $meta, int $piece_length);
    * - Torrent(string $file_or_folder, array $meta, int $piece_length, bool $include_hidden);
    * - Torrent(array $files_list);
    * - Torrent(array $files_list, string $announce_url, int $piece_length);
    * - Torrent(array $files_list, array $meta, int $piece_length);
    * - Torrent(array $files_list, array $meta, int $piece_length , bool $include_hidden);.
    *
    * @param mixed $data           torrent to read or source folder/file(s) (optional, to get an instance)
    * @param mixed $meta           announce url or meta information (optional)
    * @param int   $piece_length   (optional)
    * @param bool  $include_hidden (optional)
    */
   public function __construct($data = null, $meta = [], int $piece_length = 256, bool $include_hidden = true)
   {
       if (is_null($data)) {
           self::setError(new Exception('data cannot be empty'));
       }
       if ($piece_length < 32 || $piece_length > 4096) {
           self::setError(new Exception('Invalid piece length, must be between 32 and 4096'));
       }
       if (is_string($meta)) {
           $meta = [
               'announce' => $meta,
           ];
       } else {
           $list = [];
           foreach ($meta as $item) {
               $list[] = [
                   'announce' => $item,
               ];
           }
           $meta = $list;
       }
       if ($this->build($data, $piece_length * 1024, $include_hidden)) {
           $this->touch();
       } else {
           $meta = array_merge($meta, self::decode($data));
       }
       foreach ($meta as $key => $value) {
           $this->{trim($key)} = $value;
       }
   }

   /** Convert the current Torrent instance in torrent format.
    *
    * @return string encoded torrent data
    */
   public function __toString(): string
   {
       return (string) self::encode($this);
   }

   /** Return last error message.
    *
    * @return bool|string last error message or false if none
    */
   public function error()
   {
       return empty(self::$errors) ?
           false :
           self::$errors[0]->getMessage();
   }

   /** Return Errors.
    *
    * @return array|bool error list or false if none
    */
   public function errors()
   {
       return empty(self::$errors) ?
           false :
           self::$errors;
   }

   // Getters and setters

   /** Getter and setter of torrent announce url / list
    * If the argument is a string, announce url is added to announce list (or set as announce if announce is not set)
    * If the argument is an array/object, set announce url (with first url) and list (if array has more than one url),
    * tiered list supported
    * If the argument is false announce url & list are unset.
    *
    * @param null|mixed $announce list, reset all if false (optional, if omitted it's a getter)
    *
    * @return null|array|string announce url / list or null if not set
    */
   public function announce($announce = null)
   {
       if (is_null($announce)) {
           return $this->{'announce-list'} ?? $this->announce ?? null;
       }
       $this->touch();
       if (is_string($announce) && isset($this->announce)) {
           return $this->{'announce-list'} = self::announceList(
               $this->{'announce-list'} ?? $this->announce,
               $announce
           );
       }
       unset($this->{'announce-list'});
       if (is_array($announce) || is_object($announce)) {
           if (($this->announce = self::firstAnnounce($announce)) && count($announce) > 1) {
               return $this->{'announce-list'} = self::announceList($announce);
           }

           return $this->announce;
       }
       if (!isset($this->announce) && $announce) {
           return $this->announce = (string) $announce;
       }
       unset($this->announce);

       return null;
   }

   /** Getter and setter of torrent creation date.
    *
    * @param null|mixed $timestamp (optional, if omitted it's a getter)
    *
    * @return null|int timestamp or null if not set
    */
   public function creation_date($timestamp = null)
   {
       return is_null($timestamp) ?
           $this->{'creation date'} ?? null :
           $this->touch($this->{'creation date'} = (int) $timestamp);
   }

   /** Getter and setter of torrent comment.
    *
    * @param null|mixed $comment (optional, if omitted it's a getter)
    *
    * @return null|string comment or null if not set
    */
   public function comment($comment = null)
   {
       return is_null($comment) ?
           $this->comment ?? null :
           $this->touch($this->comment = (string) $comment);
   }

   /** Getter and setter of torrent name.
    *
    * @param null|mixed $name (optional, if omitted it's a getter)
    *
    * @return null|string name or null if not set
    */
   public function name($name = null)
   {
       return is_null($name) ?
           $this->info['name'] ?? null :
           $this->touch($this->info['name'] = (string) $name);
   }

   /** Getter and setter of private flag.
    *
    * @param null|mixed $private or not (optional, if omitted it's a getter)
    *
    * @return bool private flag
    */
   public function is_private($private = null): bool
   {
       return is_null($private) ?
           !empty($this->info['private']) :
           $this->touch($this->info['private'] = $private ? 1 : 0);
   }

   /** Getter and setter of torrent source.
    *
    * @param null|mixed $source (optional, if omitted it's a getter)
    *
    * @return null|string source or null if not set
    */
   public function source($source = null)
   {
       return is_null($source) ?
           $this->info['source'] ?? null :
           $this->touch($this->info['source'] = (string) $source);
   }

   /** Getter and setter of webseed(s) url list ( GetRight implementation ).
    *
    * @param null|mixed $urls webseed or webseeds mirror list (optional, if omitted it's a getter)
    *
    * @return null|array|string webseed(s) or null if not set
    */
   public function url_list($urls = null)
   {
       return is_null($urls) ?
           $this->{'url-list'} ?? null :
           $this->touch($this->{'url-list'} = is_string($urls) ? $urls : (array) $urls);
   }

   /** Getter and setter of httpseed(s) url list ( BitTornado implementation ).
    *
    * @param null|mixed $urls httpseed or httpseeds mirror list (optional, if omitted it's a getter)
    *
    * @return null|array|bool httpseed(s) or null if not set
    */
   public function httpseeds($urls = null)
   {
       return is_null($urls) ?
           $this->httpseeds ?? null :
           $this->touch($this->httpseeds = (array) $urls);
   }

   // Analyze BitTorrent

   /** Get piece length.
    *
    * @return int piece length or null if not set
    */
   public function piece_length(): ?int
   {
       return $this->info['piece length'] ?? null;
   }

   /** Compute hash info.
    *
    * @return string hash info or null if info not set
    */
   public function hash_info(): ?string
   {
       return isset($this->info) ?
           sha1(self::encode($this->info)) :
           null;
   }

   /** List torrent content.
    *
    * @param null|mixed $precision size precision (optional, if omitted returns sizes in bytes)
    *
    * @return array file(s) and size(s) list, files as keys and sizes as values
    */
   public function content($precision = null): array
   {
       $files = [];
       if (isset($this->info['files']) && is_array($this->info['files'])) {
           foreach ($this->info['files'] as $file) {
               $files[self::path($file['path'], $this->info['name'])] = $precision ?
                   self::format($file['length'], $precision) :
                   $file['length'];
           }
       } elseif (isset($this->info['name'])) {
           $files[$this->info['name']] = $precision ?
               self::format($this->info['length'], $precision) :
               $this->info['length'];
       }

       return $files;
   }

   /** List torrent content pieces and offset(s).
    *
    * @return array file(s) and pieces/offset(s) list, file(s) as keys and pieces/offset(s) as values
    */
   public function offset(): array
   {
       $files = [];
       $size  = 0;
       if (isset($this->info['files']) && is_array($this->info['files'])) {
           foreach ($this->info['files'] as $file) {
               $files[self::path($file['path'], $this->info['name'])] = [
                   'startpiece' => floor($size / $this->info['piece length']),
                   'offset'     => fmod($size, $this->info['piece length']),
                   'size'       => $size += $file['length'],
                   'endpiece'   => floor($size / $this->info['piece length']),
               ];
           }
       } elseif (isset($this->info['name'])) {
           $files[$this->info['name']] = [
               'startpiece' => 0,
               'offset'     => 0,
               'size'       => $this->info['length'],
               'endpiece'   => floor($this->info['length'] / $this->info['piece length']),
           ];
       }

       return $files;
   }

   /** Sum torrent content size.
    *
    * @param null|mixed $precision size precision (optional, if omitted returns size in bytes)
    *
    * @return int|string file(s) size
    */
   public function size($precision = null)
   {
       $size = 0;
       if (isset($this->info['files']) && is_array($this->info['files'])) {
           foreach ($this->info['files'] as $file) {
               $size += $file['length'];
           }
       } elseif (isset($this->info['name'])) {
           $size = $this->info['length'];
       }

       return is_null($precision) ?
           $size :
           self::format($size, $precision);
   }

   /**
    * @param null|mixed $announce  url (optional, to request an alternative tracker BUT required for static call)
    * @param null|mixed $hash_info (optional, required ONLY for static call)
    * @param mixed      $timeout   in seconds (optional, default to self::timeout 30s)
    *
    * @throws Exception
    *
    * @return array|bool tracker torrent statistics
    */
   public function scrape($announce = null, $hash_info = null, $timeout = self::TIMEOUT)
   {
       $scraper = new Scraper();

       try {
           return $scraper->scrape($hash_info ?? $this->hash_info(), $announce ?? $this->announce(), null, $timeout);
       } catch (Exception $e) {
           return $scraper->get_errors();
       }
   }

   // Save and Send

   /** Save torrent file to disk.
    *
    * @param null|mixed $filename name of the file (optional)
    *
    * @return bool|int file has been saved or not
    */
   public function save($filename = null)
   {
       return file_put_contents(is_null($filename) ?
           $this->info['name'] . '.torrent' : $filename, self::encode($this));
   }

   /** Send torrent file to client.
    *
    * @param null|mixed $filename name of the file (optional)
    */
   public function send($filename = null): void
   {
       $data = self::encode($this);
       header('Content-type: application/x-bittorrent');
       header('Content-Length: ' . strlen($data));
       header('Content-Disposition: attachment; filename="' . (is_null($filename) ?
               $this->info['name'] . '.torrent' : $filename) . '"');
       exit($data);
   }

   /** Get magnet link.
    *
    * @param mixed $html encode ampersand, default true (optional)
    *
    * @return string magnet link
    */
   public function magnet($html = true): string
   {
       $ampersand = $html ? '&' : '&';

       return sprintf(
           'magnet:?xt=urn:btih:%2$s%1$sdn=%3$s%1$sxl=%4$d%1$str=%5$s',
           $ampersand,
           $this->hash_info(),
           urlencode($this->name()),
           $this->size(),
           implode($ampersand . 'tr=', self::untier($this->announce()))
       );
   }

   // Encode BitTorrent

   /** Encode torrent data.
    *
    * @param mixed $mixed data to encode
    *
    * @return string torrent encoded data
    */
   public static function encode($mixed): ?string
   {
       switch (gettype($mixed)) {
           case 'integer':
           case 'double':
               return self::encodeInteger($mixed);
           case 'object':
               $mixed = get_object_vars($mixed);
           // no break
           case 'array':
               return self::encodeArray($mixed);
           default:
               return self::encodeString((string) $mixed);
       }
   }

   // Public Helpers

   /** Helper to format size in bytes to human readable.
    *
    * @param mixed $size      in bytes
    * @param mixed $precision precision after comma
    *
    * @return string formatted size in appropriate unit
    */
   public static function format($size, $precision = 2): string
   {
       $units = [
           'octets',
           'KiB',
           'MiB',
           'GiB',
           'TiB',
           'PiB',
       ];
       while (($next = next($units)) && $size > 1024) {
           $size /= 1024;
       }

       return round($size, $precision) . ' ' . ($next ? prev($units) : end($units));
   }

   /** Helper to return filesize (even bigger than 2Gb -linux only- and distant files size).
    *
    * @param mixed $file path
    *
    * @return bool|float filesize or false if error
    */
   public static function filesize($file)
   {
       if (is_file($file)) {
           return (float) sprintf('%u', @filesize($file));
       }
       if ($content_length = preg_grep($pattern = '#^Content-Length:\s+(\d+)$#i', (array) @get_headers($file))) {
           return (int) preg_replace($pattern, '$1', reset($content_length));
       }

       return 0;
   }

   /** Helper to open file to read (even bigger than 2Gb, linux only).
    *
    * @param mixed      $file path
    * @param null|mixed $size (optional)
    *
    * @return bool|resource file handle or false if error
    */
   public static function fopen($file, $size = null)
   {
       if ((is_null($size) ? self::filesize($file) : $size) <= 2 * (1024 ** 3)) {
           return fopen($file, 'rb');
       }
       if (PHP_OS !== 'Linux') {
           return self::setError(new Exception('File size is greater than 2GB. This is only supported under Linux'));
       }
       if (!is_readable($file)) {
           return false;
       }

       return popen('cat ' . escapeshellarg(realpath($file)), 'r');
   }

   /** Helper to scan directories files and sub directories recursively.
    *
    * @param string $dir            directory path
    * @param bool   $include_hidden
    *
    * @return array directory content list
    */
   public static function scandir($dir, $include_hidden): array
   {
       $paths     = $ignored     = [];
       $ignored[] = '/torrent-rw/vendor';
       $iterator  = new RecursiveIteratorIterator(
           new RecursiveDirectoryIterator(
               $dir,
               RecursiveDirectoryIterator::SKIP_DOTS
           ),
           RecursiveIteratorIterator::SELF_FIRST
       );
       if (!$include_hidden) {
           foreach ($iterator as $name => $object) {
               if (is_dir($name) && basename($name)[0] === '.') {
                   $ignored[] = $name;
               }
           }
       }

       $iterator = new RecursiveIteratorIterator(
           new RecursiveDirectoryIterator(
               $dir,
               RecursiveDirectoryIterator::SKIP_DOTS
           ),
           RecursiveIteratorIterator::SELF_FIRST
       );
       foreach ($iterator as $name => $object) {
           if (!$include_hidden) {
               foreach ($ignored as $ignore) {
                   if (preg_match('#' . $ignore . '#', $name)) {
                       continue 2;
                   }
               }
               if (basename($name)[0] === '.') {
                   continue;
               }
           }
           if (is_dir($name)) {
               continue;
           }
           $paths[] = $name;
       }

       return $paths;
   }

   /** Helper to check if string is an url (http).
    *
    * @param mixed $url to check
    *
    * @return bool is string an url
    */
   public static function is_url($url): bool
   {
       return (bool) filter_var($url, FILTER_VALIDATE_URL);
   }

   /** Helper to check if url exists.
    *
    * @param mixed $url to check
    *
    * @return bool does the url exist or not
    */
   public static function url_exists($url): bool
   {
       return self::is_url($url) ?
           (bool) self::filesize($url) :
           false;
   }

   /** Helper to check if a file is a torrent.
    *
    * @param mixed $file    path
    * @param mixed $timeout http timeout (optional, default to self::timeout 30s)
    *
    * @return bool is the file a torrent or not
    */
   public static function is_torrent($file, $timeout = self::TIMEOUT): bool
   {
       return (($start = self::file_get_contents($file, $timeout, 0, 11))
               && 'd8:announce' === $start)
           || 'd10:created' === $start
           || 'd13:creatio' === $start
           || 'd13:announc' === $start
           || 'd12:_info_l' === $start
           || strpos($start, 'd7:comment') === 0 // @see https://github.com/adriengibrat/torrent-rw/issues/32
           || strpos($start, 'd4:info') === 0
           || strpos($start, 'd9:') === 0; // @see https://github.com/adriengibrat/torrent-rw/pull/17
   }

   /** Helper to get (distant) file content.
    *
    * @param mixed      $file    path
    * @param mixed      $timeout http timeout (optional, default to self::timeout 30s)
    * @param null|mixed $offset  starting offset (optional, default to null)
    * @param null|mixed $length  content length (optional, default to null)
    *
    * @return bool|string file content or false if error
    */
   public static function file_get_contents($file, $timeout = self::TIMEOUT, $offset = null, $length = null)
   {
       if (is_file($file) || ini_get('allow_url_fopen')) {
           $context = !is_file($file) && $timeout ?
               stream_context_create(['http' => ['timeout' => $timeout]]) :
               null;

           return !is_null($offset) ? $length ?
               @file_get_contents($file, false, $context, $offset, $length) :
               @file_get_contents($file, false, $context, $offset) :
               @file_get_contents($file, false, $context);
       }
       if (!function_exists('curl_init')) {
           return self::setError(new Exception('Install CURL or enable "allow_url_fopen"'));
       }
       $handle = curl_init($file);
       if ($timeout) {
           curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);
       }
       if ($offset || $length) {
           curl_setopt($handle, CURLOPT_RANGE, $offset . '-' . ($length ? $offset + $length - 1 : null));
       }
       curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
       $content = curl_exec($handle);
       $size    = curl_getinfo($handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
       curl_close($handle);

       return ($offset && $size === -1) || ($length && $length !== $size) ? $length ?
           substr($content, $offset, $length) :
           substr($content, $offset) :
           $content;
   }

   /** Flatten announces list.
    *
    * @param mixed $announces list
    *
    * @return array flattened announces list
    */
   public static function untier($announces): array
   {
       $list = [];
       foreach ((array) $announces as $tier) {
           is_array($tier) ?
               $list = array_merge($list, self::untier($tier)) :
               array_push($list, $tier);
       }

       return $list;
   }

   // Decode BitTorrent

   /** Decode torrent data or file.
    *
    * @param mixed $string data or file path to decode
    *
    * @return array decoded torrent data
    */
   protected static function decode($string): array
   {
       $data = is_file($string) || self::url_exists($string) ?
           self::file_get_contents($string) :
           $string;

       return (array) self::decodeData($data);
   }

   // Internal Helpers

   /** Build torrent info.
    *
    * @param mixed $data           source folder/file(s) path
    * @param mixed $piece_length
    * @param mixed $include_hidden include hidden files
    *
    * @return array|bool torrent info or false if data isn't folder/file(s)
    */
   protected function build($data, $piece_length, $include_hidden)
   {
       if (is_null($data)) {
           return false;
       }
       if (is_array($data) && self::isList($data)) {
           return $this->info = $this->files($data, $piece_length);
       }
       if (is_dir((string) $data)) {
           return $this->info = $this->folder($data, $piece_length, $include_hidden);
       }
       if ((is_file((string) $data) || self::url_exists($data)) && !self::is_torrent($data)) {
           return $this->info = $this->file($data, $piece_length);
       }

       return false;
   }

   /** Set torrent creator and creation date.
    *
    * @param null $void
    *
    * @return bool
    */
   protected function touch($void = null): bool
   {
       $this->{'created by'}    = 'Torrent RW PHP Class - http://github.com/adriengibrat/torrent-rw';
       $this->{'creation date'} = time();

       return true;
   }

   /** Add an error to errors stack.
    *
    * @param mixed $exception error to add
    * @param mixed $message   return error message or not (optional, default to false)
    *
    * @return bool|string return false or error message if requested
    */
   protected static function setError($exception, $message = false)
   {
       return (array_unshift(self::$errors, $exception) && $message) ? $exception->getMessage() : false;
   }

   /** Build announce list.
    *
    * @param mixed $announce announce url / list
    * @param mixed $merge    announce url / list to add (optional)
    *
    * @return array announce list (array of arrays)
    */
   protected static function announceList($announce, $merge = []): array
   {
       return array_map(static function ($a) {
           return (array) $a;
       }, array_merge((array) $announce, (array) $merge));
   }

   /** Get the first announce url in a list.
    *
    * @param mixed $announce list (array of arrays if tiered trackers)
    *
    * @return string first announce url
    */
   protected static function firstAnnounce($announce): string
   {
       while (is_array($announce)) {
           $announce = reset($announce);
       }

       return $announce;
   }

   /** Helper to pack data hash.
    *
    * @param mixed $data
    *
    * @return string packed data hash
    */
   protected static function pack(&$data): string
   {
       return pack('H*', sha1($data)) . ($data = null);
   }

   /** Helper to build file path.
    *
    * @param mixed $path
    * @param mixed $folder base path
    *
    * @return string real file path
    */
   protected static function path($path, $folder): string
   {
       array_unshift($path, $folder);

       return implode(DIRECTORY_SEPARATOR, $path);
   }

   /** Helper to explode file path.
    *
    * @param mixed $path
    *
    * @return array file path
    */
   protected static function pathExplode($path): array
   {
       return explode(DIRECTORY_SEPARATOR, $path);
   }

   /** Helper to test if an array is a list.
    *
    * @param mixed $array to test
    *
    * @return bool is the array a list or not
    */
   protected static function isList($array): bool
   {
       foreach (array_keys($array) as $key) {
           if (!is_int($key)) {
               return false;
           }
       }

       return true;
   }

   /** Encode torrent string.
    *
    * @param mixed $string to encode
    *
    * @return string encoded string
    */
   private static function encodeString($string): string
   {
       return strlen($string) . ':' . $string;
   }

   /** Encode torrent integer.
    *
    * @param mixed $integer to encode
    *
    * @return string encoded integer
    */
   private static function encodeInteger($integer): string
   {
       return 'i' . $integer . 'e';
   }

   /** Encode torrent dictionary or list.
    *
    * @param mixed $array to encode
    *
    * @return string encoded dictionary or list
    */
   private static function encodeArray($array): string
   {
       if (self::isList($array)) {
           $return = 'l';
           foreach ($array as $value) {
               $return .= self::encode($value);
           }
       } else {
           ksort($array, SORT_STRING);
           $return = 'd';
           foreach ($array as $key => $value) {
               $return .= self::encode((string) $key) . self::encode($value);
           }
       }

       return $return . 'e';
   }

   /**
    * @param mixed $data
    *
    * @return array|int|string
    */
   private static function decodeData(&$data)
   {
       switch (self::char($data)) {
           case 'i':
               $data = substr($data, 1);

               return self::decodeInteger($data);
           case 'l':
               $data = substr($data, 1);

               return self::decodeList($data);
           case 'd':
               $data = substr($data, 1);

               return self::decodeDictionary($data);
           default:
               return self::decodeString($data);
       }
   }

   /** Decode torrent dictionary.
    *
    * @param mixed $data to decode
    *
    * @return array|string decoded dictionary
    */
   private static function decodeDictionary(&$data)
   {
       $dictionary = [];
       $previous   = null;
       while ('e' !== ($char = self::char($data))) {
           if (false === $char) {
               return self::setError(new Exception('Unterminated dictionary'));
           }
           if (!ctype_digit($char)) {
               return self::setError(new Exception('Invalid dictionary key'));
           }
           $key = self::decodeString($data);
           if (isset($dictionary[$key])) {
               return self::setError(new Exception('Duplicate dictionary key'));
           }
           if ($key < $previous) {
               self::setError(new Exception('Missorted dictionary key'));
           }
           $dictionary[$key] = self::decodeData($data);
           $previous         = $key;
       }
       $data = substr($data, 1);

       return $dictionary;
   }

   /** Decode torrent list.
    *
    * @param mixed $data to decode
    *
    * @return array|string decoded list
    */
   private static function decodeList(&$data)
   {
       $list = [];
       while ('e' !== ($char = self::char($data))) {
           if (false === $char) {
               return self::setError(new Exception('Unterminated list'));
           }
           $list[] = self::decodeData($data);
       }
       $data = substr($data, 1);

       return $list;
   }

   /** Decode torrent string.
    *
    * @param mixed $data to decode
    *
    * @return string decoded string
    */
   private static function decodeString(&$data): string
   {
       if ('0' === self::char($data) && ':' !== substr($data, 1, 1)) {
           self::setError(new Exception('Invalid string length, leading zero'));
       }
       if (!$colon = @strpos($data, ':')) {
           return self::setError(new Exception('Invalid string length, colon not found'));
       }
       $length = (int) substr($data, 0, $colon);
       if ($length + $colon + 1 > strlen($data)) {
           return self::setError(new Exception('Invalid string, input too short for string length'));
       }
       $string = substr($data, $colon + 1, $length);
       $data   = substr($data, $colon + $length + 1);

       return $string;
   }

   /** Decode torrent integer.
    *
    * @param mixed $data to decode
    *
    * @return int decoded integer
    */
   private static function decodeInteger(&$data): int
   {
       $start = 0;
       $end   = strpos($data, 'e');
       if (0 === $end) {
           self::setError(new Exception('Empty integer'));
       }
       if ('-' === self::char($data)) {
           ++$start;
       }
       if ($end > $start + 1 && '0' === substr($data, $start, 1)) {
           self::setError(new Exception('Leading zero in integer'));
       }
       if (!ctype_digit(substr($data, $start, $start ? $end - 1 : $end))) {
           self::setError(new Exception('Non-digit characters in integer'));
       }
       $integer = substr($data, 0, $end);
       $data    = substr($data, $end + 1);

       return (int) $integer;
   }

   /** Build pieces depending on piece length from a file handler.
    *
    * @param mixed $handle       file handle
    * @param mixed $piece_length
    * @param mixed $last         piece
    *
    * @return string pieces
    */
   private function pieces($handle, $piece_length, $last = true)
   {
       static $piece, $length;
       if (empty($length)) {
           $length = $piece_length;
       }
       $pieces = null;
       while (!feof($handle)) {
           if (($length = strlen($piece .= fread($handle, $length))) === $piece_length) {
               $pieces .= self::pack($piece);
           } elseif (($length = $piece_length - $length) < 0) {
               return self::setError(new Exception('Invalid piece length!'));
           }
       }
       fclose($handle);

       return $pieces . ($last && $piece ? self::pack($piece) : null);
   }

   /** Build torrent info from single file.
    *
    * @param mixed $file         path
    * @param mixed $piece_length
    *
    * @return array|string torrent info
    */
   private function file($file, $piece_length)
   {
       if (!$handle = self::fopen($file, $size = self::filesize($file))) {
           return self::setError(new Exception('Failed to open file: "' . $file . '"'));
       }
       if (self::is_url($file)) {
           $this->url_list($file);
       }
       $path = self::pathExplode($file);

       return [
           'length'       => $size,
           'name'         => end($path),
           'piece length' => $piece_length,
           'pieces'       => $this->pieces($handle, $piece_length),
       ];
   }

   /** Build torrent info from files.
    *
    * @param mixed $files
    * @param mixed $piece_length
    *
    * @return array torrent info
    */
   private function files($files, $piece_length): array
   {
       sort($files);
       usort($files, static function ($a, $b) {
           return strrpos($a, DIRECTORY_SEPARATOR) - strrpos($b, DIRECTORY_SEPARATOR);
       });
       $first = current($files);
       if (!self::is_url($first)) {
           $files = array_map('realpath', $files);
       } else {
           $this->url_list(dirname($first) . DIRECTORY_SEPARATOR);
       }
       $files_path = array_map('self::pathExplode', $files);
       $root       = array_intersect_assoc(...$files_path);
       $pieces     = null;
       $info_files = [];
       $count      = count($files) - 1;
       foreach ($files as $i => $file) {
           if (!$handle = self::fopen($file, $filesize = self::filesize($file))) {
               self::setError(new Exception('Failed to open file: "' . $file . '" discarded'));

               continue;
           }
           $pieces .= $this->pieces($handle, $piece_length, $count === $i);
           $info_files[] = [
               'length' => $filesize,
               'path'   => array_diff_assoc($files_path[$i], $root),
           ];
       }

       return [
           'files'        => $info_files,
           'name'         => end($root),
           'piece length' => $piece_length,
           'pieces'       => $pieces,
       ];
   }

   /** Build torrent info from folder content.
    *
    * @param mixed $dir            path
    * @param mixed $piece_length
    * @param mixed $include_hidden
    *
    * @return array torrent info
    */
   private function folder($dir, $piece_length, $include_hidden): array
   {
       return $this->files(self::scandir($dir, $include_hidden), $piece_length);
   }

   /** Helper to return the first char of encoded data.
    *
    * @param mixed $data encoded data
    *
    * @return bool|string first char of encoded data or false if empty data
    */
   private static function char($data)
   {
       return empty($data) ?
           false :
           substr($data, 0, 1);
   }
}


in torrent-upload find and delete
            if (!is_array($annlist)) {
               $annlist = array(array($announce));
           }
           foreach ($annlist as $ann) {
               foreach ($ann as $val) {
                   if (strtolower(substr($val, 0, 4)) != "udp:") {
                       DB::run("INSERT INTO `announce` (`torrent`, `url`) VALUES (?, ?)", [$id, $val]);
                   }
               }
           }


find
$message = sprintf(Lang::T("TORRENT_UPLOAD_EXTERNAL"), $name, $id);

add below
                // scrape external
               $torrent = new Torrent "uploads/$id.torrent");
               try {
                   $scraped = $torrent->scrape();
               } catch (Exception $e) {
                   $scraped = $torrent->errors();
                   exit();
               }
               $myarray = array_shift($scraped);

               $seeders = $leechers = $completed = 0;
               if ($myarray['seeders'] > 0) {
                   $seeders = $myarray['seeders'];
               }
               if ($myarray['leechers'] > 0) {
                   $leechers = $myarray['leechers'];
               }
               if ($myarray['completed'] > 0) {
                   $completed = $myarray['completed'];
               }

               if ($seeders !== null) {
                   // Update the Torrent
                   SQL_Query_exec("
                   UPDATE torrents
                   SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible =  'yes'
                   WHERE id = $id");
               }


in torrents-import find
                   if ($external == 'yes' && $site_config['UPLOADSCRAPE']) {

that extenal block should look like this
                    if ($external == 'yes' && $site_config['UPLOADSCRAPE']) {
                       $torrent = new Torrent( "uploads/$id.torrent");
                       try {
                           $scraped = $torrent->scrape();
                       } catch (Exception $e) {
                           $scraped = $torrent->errors();
                           exit();
                       }
                       $myarray = array_shift($scraped);

                       $seeders = $leechers = $completed = 0;
                       if ($myarray['seeders'] > 0) {
                           $seeders = $myarray['seeders'];
                       }
                       if ($myarray['leechers'] > 0) {
                           $leechers = $myarray['leechers'];
                       }
                       if ($myarray['completed'] > 0) {
                           $completed = $myarray['completed'];
                       }
                       if ($seeders !== null) {
                           // Update the Torrent
                   SQL_Query_exec("
                   UPDATE torrents
                   SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible =  'yes'
                   WHERE id = $id");
                       }
                   }
                   //END SCRAPE


in torrents-details find
			$seeders1 = $leechers1 = $downloaded1 = null;

$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
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
        $resu = SQL_Query_exec("SELECT id, info_hash FROM torrents WHERE external = 'yes' AND id = $id");
       while ($rowu = mysqli_fetch_assoc($resu)) {
           $torrent = new Torrent("uploads/$rowu[id].torrent");
           try {
               $scraped = $torrent->scrape();
           } catch (Exception $e) {
               $scraped = $torrent->errors();
               exit();
           }
           $myarray = array_shift($scraped);

           $seeders = $leechers = $completed = 0;
           if ($myarray['seeders'] > 0) {
               $seeders = $myarray['seeders'];
           }
           if ($myarray['leechers'] > 0) {
               $leechers = $myarray['leechers'];
           }
           if ($myarray['completed'] > 0) {
               $completed = $myarray['completed'];
           }

           if ($seeders !== null) {
               // Update the Torrent
                   SQL_Query_exec("
                   UPDATE torrents
                   SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible =  'yes'
                   WHERE id = $id");

           } else {
               // Its Dead :(
               SQL_Query_exec("UPDATE torrents SET last_action = get_date_time( WHERE id=$rowu['id']");
           }
Last edited by M-jay warn on 2021-06-15 20:38:39
2021-06-15 19:54:29
Implement a interface, dump those variables into public functions and call them in the interface block. It will clean up a lot of that code.
Last edited by STorrents2020 on 2021-06-15 19:54:54
2021-06-15 19:55:38
OK, as I understand it, it will be an update of your current MVC / PDO version from the old code.

Will there be any "mega-scrape" as in the previous version and some form of "cronjob" so all this can be made easier for admins

Current situation is such that anyone can do "scrape" (it is default, but can be changed with some knowledge)

My old scraper is not like the one you just presented, it is very different

A good idea, I think


www.exyusubs.com
TorrentTrader V3.8.3 (SE)
OS: AlmaLinux 9.9 (BC)
Apache version: 2.4.71
PHP version: 8.5.13 (PHP-FPM)
MySQL version: 10.11.18-MariaDB
Last edited by Botanicar on 2021-06-15 19:58:18
2021-06-15 20:07:32
the main difference for v3 in the first post is this query
               DB::run("
              UPDATE torrents
              SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
              WHERE id = ?",
                  [$leechers, $seeders, $downloaded, TimeDate::get_date_time(), 'yes', $id]);


there is no mega scrape yet but in my pdo version the plan is everytime a user visits torrent details, torrent edit, torrent delete it will scrape 10 torrents per time i do this by using AND last_edit LIMIT 10

the first post is based on the v3 scraper posted by micromonkey i had a quick look through post and i hope its just the update torrent query that needs changing the second post is what is the new scraper used in my MVC/PDO version  :thumb
2021-06-15 20:46:08
Here is a test page for the new scraper from the second post for users to try on v3 - just edit the torrent id

create test.php

<?php
require_once("backend/Scraper.php");
require_once("backend/Torrent.php");

// change this id from 7
$file    = 'uploads/7.torrent';

$torrent = new Torrent($file);
       try {
           $scraped = $torrent->scrape();
       } catch (Exception $e) {
           $scraped = $torrent->errors();
           exit();
       }
       $myarray = array_shift($scraped);

echo $myarray['completed'].'<br>';
echo $myarray['leechers'].'<br>';
echo $myarray['seeders'].'<br>';
Last edited by M-jay warn on 2021-06-15 20:51:12
2021-06-18 04:28:56
Try domain.com/test.php?id=5

$file    = printf('uploads/%s.torrent', (isset($_GET[‘id’]) ? Intval($_GET[‘id’]) : 0));
2021-06-18 04:46:27
I’ll update this class too, implement cURL and options as constants, the interface and the object to scrape id or file.

I would go for checking null so instead of this

if (empty($trackers)) {

To


function ($trackers = null, …)
   if (is_null($trackers)) {

I’m just curious, too.. this to me appears incorrect in the way that it can be instructed to assign value and key (and if relying on 1st array position, add a pointer: &$key), not sure why this is a multi array when the iteration is already taking place with those variables - $ann, etc

foreach ($annlist as $ann) {
              foreach ($ann as $val) {
Last edited by STorrents2020 on 2021-06-18 06:44:59
2021-06-18 13:50:00
I'd personally stay away from the old TT one
While I got it working its a bit outdated. The second post is better option and can be simplified to a function
Also moving forward using the torrent-rw class it makes sense to use the scraper

Something like this in function passing id as var
[
                       $torrent = new Torrent( "uploads/$id.torrent");
                      try {
                          $scraped = $torrent->scrape();
                      } catch (Exception $e) {
                          $scraped = $torrent->errors();
                          exit();
                      }
                      $myarray = array_shift($scraped);

                      $seeders = $leechers = $completed = 0;
                      if ($myarray['seeders'] > 0) {
                          $seeders = $myarray['seeders'];
                      }
                      if ($myarray['leechers'] > 0) {
                          $leechers = $myarray['leechers'];
                      }
                      if ($myarray['completed'] > 0) {
                          $completed = $myarray['completed'];
                      }
                      if ($seeders !== null) {
                          // Update the Torrent
                  SQL_Query_exec("
                  UPDATE torrents
                  SET leechers = $leechers, seeders = $seeders, times_completed = $completed, last_action = get_date_time(), visible =  'yes'
                  WHERE id = $id");
                      }
                  }
                  //END SCRAPE


Just playing with it at minute thinking of adding scraperfunction($id, $all = 0)

So with $all = 1 it will scrape 100 torrents by updated date and age so it's all in one tidy small class function

Will probably  return scrape array then it's simple function call in any page, cleanup or wherever
2021-06-18 14:13:31
Great plan. I’m going to get into this myself this weekend. I’ll wait on your final, I didn’t know that was old TT code, saw a few flaws and I was like …!

Also

$seeders = $leechers = $completed = 0;

This is what list() takes care of. Variables are faster but logically, list is the solution there.
Last edited by STorrents2020 on 2021-06-18 23:53:31
2021-06-19 15:39:50
Updating my current progress to github so here is what i have so far

Include the 3 classes in backed/functions.php

require_once(BACKEND."/Scraper.php"); // Mail functions
require_once(BACKEND."/Torrent.php");
require_once(BACKEND."/Tscraper.php");


Thats
the rw-torrent class https://github.com/darkalchemy/Torrent-RW
the scrapeer class https://github.com/medariox/scrapeer

One i put to gether for TT to scrape by id or 10 at a time

<?php

class Tscraper
{
   public static function ScrapeId($id)
   {
       $torrent = new Torrent(TORRENTDIR . "/$id.torrent");
       try {
           $scraped = $torrent->scrape();
       } catch (\Exception $e) {
           //$scraped = $torrent->errors();
           //exit();
       }
       $myarray = array_shift($scraped);

       $seeders = $leechers = $completed = 0;
       if ($myarray['seeders'] > 0) {
           $seeders = $myarray['seeders'];
       }
       if ($myarray['leechers'] > 0) {
           $leechers = $myarray['leechers'];
       }
       if ($myarray['completed'] > 0) {
           $completed = $myarray['completed'];
       }

       if ($seeders !== null) {
           // Update the Torrent
           DB::run(" UPDATE torrents
                             SET leechers = ?, seeders = ?, times_completed = ?, last_action = ?, visible = ?
                             WHERE id = ?",
                             [$leechers, $seeders, $completed, TimeDate::get_date_time(), 'yes', $id]
           );
       } else {
           // Its Dead :(
           DB::run("UPDATE torrents SET last_action = ? WHERE id=?", [TimeDate::get_date_time(), $id]);
       }
   }

   public static function scrapeall()
   {
       // Set A time limit ? how fast is your server ?
       //set_time_limit(15);

       // Rescrape torrents every x seconds. (Default: 2 days)
       $stmt = DB::run("SELECT `id`, `info_hash`, `last_action`
                        FROM `torrents`
                        WHERE `external` = 'yes'
                        AND `last_action` <= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 DAY) LIMIT 10");

       foreach ($stmt as $tor) {
           self::ScrapeId($tor['id']);
       }
   }
}


then on torrent-import i have this

                   //EXTERNAL SCRAPE
                   if ($external == 'yes' && UPLOADSCRAPE) {
                       Tscraper::ScrapeId($id);
                   }


on torrent-upload

           //Uploaded ok message
           if ($external == 'no') {
               $message = sprintf(Lang::T("TORRENT_UPLOAD_LOCAL"), $name, $id, $id);
           } else {
               $message = sprintf(Lang::T("TORRENT_UPLOAD_EXTERNAL"), $name, $id);
               // scrape external
               Tscraper::ScrapeId($id);
           }


Scrapethis.php i use form at minute but this should be on template like onclick or if $_post this is where namesspace causes headache torrent class 1 in torrent class 2 lol ill have to rename one of them
       $id = $_GET['id'];
                if ($_SESSION["view_torrents"] != "yes") {
                     Session::flash('info', Lang::T("NO_TORRENT_VIEW"), URLROOT . "/home");
                }
                Tscraper::ScrapeId($id);
               Redirect::autolink(URLROOT . "/torrent?id=$id", Lang::T("The Tracker is Updated"));


And then the what to show based on time

       $now = TimeDate::gmtime();
       $ts = $row['last_action'];
       if ($ts + 172800 > $now) {
           $scraper = "
           <br><b>" . Lang::T("EXTERNAL_TORRENT") . "</b>
           <form action='".URLROOT."/Scrapethis?id=".$id."' method='post'>
           <button type='submit' class='btn btn-warning center-block' value=''>". Lang::T("Update Stats")."</button>
           </form>";
       } else {
           $scraper = "<br>
           <br><b>" . Lang::T("EXTERNAL_TORRENT") . "</b>
           <font  size='4' color=#ff9900><b>Stats Recently Updated</b></font>";
       }

// Scrape External Torrents
       if ($torr["external"] == 'yes') {
           echo $scraper;
       }


Then Any Where we can place scrape
Place anywhere in cleanup.php for example
Tscraper::scrapeall();


Just thought you could even put limit in config so you can alter number of torrents scraped
Tscraper::scrapeall($limit = $site_config['scrapelimit']);

Last edited by M-jay warn on 2021-06-19 18:17:03
2021-06-23 16:01:19
Type declare

public static function ScrapeId(int $id)

Or I usually do

public static function ScrapeId($id): ?int {}

The ?int just tells it to pass through even if not a INT (for those certain cases).
Last edited by STorrents2020 on 2021-06-23 16:02:07
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: 9
  • Members: 0
  • Guests online: 9
  • Comments: 3
  • Messages: 1,728