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 10KB

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