BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

torrentsdl.class.php 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. /**
  3. * Class for functions related to the features involving torrent downloads
  4. */
  5. class TorrentsDL
  6. {
  7. const ChunkSize = 100;
  8. const MaxPathLength = 200;
  9. private $QueryResult;
  10. private $QueryRowNum = 0;
  11. private $Zip;
  12. private $IDBoundaries;
  13. private $FailedFiles = [];
  14. private $NumAdded = 0;
  15. private $NumFound = 0;
  16. private $Size = 0;
  17. private $Title;
  18. private $User;
  19. private $AnnounceURL;
  20. private $AnnounceList;
  21. /**
  22. * Create a Zip object and store the query results
  23. *
  24. * @param mysqli_result $QueryResult results from a query on the collector pages
  25. * @param string $Title name of the collection that will be created
  26. * @param string $AnnounceURL URL to add to the created torrents
  27. */
  28. public function __construct(&$QueryResult, $Title)
  29. {
  30. G::$Cache->InternalCache = false; // The internal cache is almost completely useless for this
  31. Zip::unlimit(); // Need more memory and longer timeout
  32. $this->QueryResult = $QueryResult;
  33. $this->Title = $Title;
  34. $this->User = G::$LoggedUser;
  35. $this->AnnounceURL = ANNOUNCE_URLS[0][0]."/".G::$LoggedUser['torrent_pass']."/announce";
  36. function add_passkey($Ann)
  37. {
  38. return (is_array($Ann)) ? array_map('add_passkey', $Ann) : $Ann."/".G::$LoggedUser['torrent_pass']."/announce";
  39. }
  40. # todo: Probably not working, but no need yet
  41. $this->AnnounceList = (sizeof(ANNOUNCE_URLS[0]) === 1 && sizeof(ANNOUNCE_URLS[0][0]) === 1) ? [] : array_map('add_passkey', ANNOUNCE_URLS[0]);
  42. # Tracker tiers (pending)
  43. #$this->AnnounceList = (sizeof(ANNOUNCE_URLS) === 1 && sizeof(ANNOUNCE_URLS[0]) === 1) ? [] : array(array_map('add_passkey', ANNOUNCE_URLS[0]), ANNOUNCE_URLS[1]);
  44. # Original Oppaitime
  45. #$this->AnnounceList = (sizeof(ANNOUNCE_URLS) == 1 && sizeof(ANNOUNCE_URLS[0]) == 1) ? [] : array_map('add_passkey', ANNOUNCE_URLS);
  46. $this->Zip = new Zip(Misc::file_string($Title));
  47. }
  48. /**
  49. * Store the results from a DB query in smaller chunks to save memory
  50. *
  51. * @param string $Key the key to use in the result hash map
  52. * @return array with results and torrent group IDs or false if there are no results left
  53. */
  54. public function get_downloads($Key)
  55. {
  56. $GroupIDs = $Downloads = [];
  57. $OldQuery = G::$DB->get_query_id();
  58. G::$DB->set_query_id($this->QueryResult);
  59. if (!isset($this->IDBoundaries)) {
  60. if ($Key === 'TorrentID') {
  61. $this->IDBoundaries = false;
  62. } else {
  63. $this->IDBoundaries = G::$DB->to_pair($Key, 'TorrentID', false);
  64. }
  65. }
  66. $Found = 0;
  67. while ($Download = G::$DB->next_record(MYSQLI_ASSOC, false)) {
  68. if (!$this->IDBoundaries || $Download['TorrentID'] === $this->IDBoundaries[$Download[$Key]]) {
  69. $Found++;
  70. $Downloads[$Download[$Key]] = $Download;
  71. $GroupIDs[$Download['TorrentID']] = $Download['GroupID'];
  72. if ($Found >= self::ChunkSize) {
  73. break;
  74. }
  75. }
  76. }
  77. $this->NumFound += $Found;
  78. G::$DB->set_query_id($OldQuery);
  79. if (empty($Downloads)) {
  80. return false;
  81. }
  82. return array($Downloads, $GroupIDs);
  83. }
  84. /**
  85. * Add a file to the zip archive
  86. *
  87. * @param string $TorrentData bencoded torrent without announce url (new format) or TORRENT object (old format)
  88. * @param array $Info file info stored as an array with at least the keys
  89. * Artist, Name, Year, Media, Format, Encoding and TorrentID
  90. * @param string $FolderName folder name
  91. */
  92. public function add_file(&$TorrentData, $Info, $FolderName = '')
  93. {
  94. $FolderName = Misc::file_string($FolderName);
  95. $MaxPathLength = $FolderName ? (self::MaxPathLength - strlen($FolderName) - 1) : self::MaxPathLength;
  96. $FileName = self::construct_file_name($Info['TorrentID'], $MaxPathLength);
  97. $this->Size += $Info['Size'];
  98. $this->NumAdded++;
  99. $this->Zip->add_file(self::get_file($TorrentData, $this->AnnounceURL, $this->AnnounceList), ($FolderName ? "$FolderName/" : "") . $FileName);
  100. usleep(25000); // We don't want to send much faster than the client can receive
  101. return null;
  102. }
  103. /**
  104. * Add a file to the list of files that could not be downloaded
  105. *
  106. * @param array $Info file info stored as an array with at least the keys Artist, Name and Year
  107. */
  108. public function fail_file($Info)
  109. {
  110. $this->FailedFiles[] = $Info['Artist'] . ' - ' . $Info['Name'] . ' - ' . $Info['Year'];
  111. }
  112. /**
  113. * Add a file to the list of files that did not match the user's format or quality requirements
  114. *
  115. * @param array $Info file info stored as an array with at least the keys Artist, Name and Year
  116. */
  117. public function skip_file($Info)
  118. {
  119. $this->SkippedFiles[] = $Info['Artist'] . ' - ' . $Info['Name'] . ' - ' . $Info['Year'];
  120. }
  121. /**
  122. * Add a summary to the archive and include a list of files that could not be added. Close the zip archive
  123. *
  124. * @param bool $FilterStats whether to include filter stats in the report
  125. */
  126. public function finalize($FilterStats = true)
  127. {
  128. $this->Zip->add_file($this->summary($FilterStats), "Summary.txt");
  129. if (!empty($this->FailedFiles)) {
  130. $this->Zip->add_file($this->errors(), "Errors.txt");
  131. }
  132. $this->Zip->close_stream();
  133. }
  134. /**
  135. * Produce a summary text over the collector results
  136. *
  137. * @param bool $FilterStats whether to include filter stats in the report
  138. * @return summary text
  139. */
  140. public function summary($FilterStats)
  141. {
  142. $ENV = ENV::go;
  143. global $ScriptStartTime;
  144. $Time = number_format(1000 * (microtime(true) - $ScriptStartTime), 2)." ms";
  145. $Used = Format::get_size(memory_get_usage(true));
  146. $Date = date("M d Y, H:i");
  147. $NumSkipped = count($this->SkippedFiles);
  148. # wtf
  149. return "Collector Download Summary for $this->Title - $ENV->SITE_NAME\r\n"
  150. . "\r\n"
  151. . "User: {$this->User[Username]}\r\n"
  152. . "Passkey: {$this->User[torrent_pass]}\r\n"
  153. . "\r\n"
  154. . "Time: $Time\r\n"
  155. . "Used: $Used\r\n"
  156. . "Date: $Date\r\n"
  157. . "\r\n"
  158. . ($FilterStats !== false
  159. ? "Torrent groups analyzed: $this->NumFound\r\n"
  160. . "Torrent groups filtered: $NumSkipped\r\n"
  161. : "")
  162. . "Torrents downloaded: $this->NumAdded\r\n"
  163. . "\r\n"
  164. . "Total size of torrents (ratio hit): ".Format::get_size($this->Size)."\r\n"
  165. . ($NumSkipped
  166. ? "\r\n"
  167. . "Albums unavailable within your criteria (consider making a request for your desired format):\r\n"
  168. . implode("\r\n", $this->SkippedFiles) . "\r\n"
  169. : "");
  170. }
  171. /**
  172. * Compile a list of files that could not be added to the archive
  173. *
  174. * @return list of files
  175. */
  176. public function errors()
  177. {
  178. return "A server error occurred. Please try again at a later time.\r\n"
  179. . "\r\n"
  180. . "The following torrents could not be downloaded:\r\n"
  181. . implode("\r\n", $this->FailedFiles) . "\r\n";
  182. }
  183. /**
  184. * Combine a bunch of torrent info into a standardized file name
  185. *
  186. * @params most input variables are self-explanatory
  187. * @param int $TorrentID if given, append "-TorrentID" to torrent name
  188. * @param int $MaxLength maximum file name length
  189. * @return file name with at most $MaxLength characters
  190. */
  191. public static function construct_file_name($TorrentID = false, $MaxLength = self::MaxPathLength)
  192. {
  193. $MaxLength -= 8; // ".torrent"
  194. if ($TorrentID !== false) {
  195. $MaxLength -= (strlen($TorrentID) + 1);
  196. }
  197. return "$TorrentID.torrent";
  198. /*
  199. $TorrentArtist = Misc::file_string($Artist);
  200. $TorrentName = Misc::file_string($Album);
  201. */
  202. }
  203. /**
  204. * Convert a stored torrent into a binary file that can be loaded in a torrent client
  205. *
  206. * @param mixed $TorrentData bencoded torrent without announce URL (new format) or TORRENT object (old format)
  207. * @return bencoded string
  208. */
  209. public static function get_file(&$TorrentData, $AnnounceURL, $AnnounceList = [])
  210. {
  211. if (Misc::is_new_torrent($TorrentData)) {
  212. $Bencode = BencodeTorrent::add_announce_url($TorrentData, $AnnounceURL);
  213. if (!empty($AnnounceList)) {
  214. $Bencode = BencodeTorrent::add_announce_list($Bencode, $AnnounceList);
  215. }
  216. return $Bencode;
  217. }
  218. $Tor = new TORRENT(unserialize(base64_decode($TorrentData)), true);
  219. $Tor->set_announce_url($AnnounceURL);
  220. unset($Tor->Val['announce-list']);
  221. if (!empty($AnnounceList)) {
  222. $Tor->set_announce_list($AnnounceList);
  223. }
  224. unset($Tor->Val['url-list']);
  225. unset($Tor->Val['libtorrent_resume']);
  226. return $Tor->enc();
  227. }
  228. }