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

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