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.6KB

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