findTorrent.pl 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Defaults
  5. my $DEBUG = 0;
  6. my $NO_QUALITY_CHECKS = 0;
  7. my $MORE_NUMBER_FORMATS = 0;
  8. my $MIN_DAYS_BACK = 0;
  9. my $MAX_DAYS_BACK = 3;
  10. my $NEXT_EPISODES = 3;
  11. # Local config
  12. my $TV_DIR = `~/bin/video/mediaPath` . '/TV';
  13. # Search parameters
  14. my $PROTOCOL = 'https';
  15. my %ENABLE_SOURCE = ('TPB' => 0, 'ISO' => 1, 'KICK' => 1, 'Z' => 1);
  16. # Selection parameters
  17. my $MIN_COUNT = 10;
  18. my $MIN_SIZE = 100;
  19. my $SIZE_BONUS = 7;
  20. my $SIZE_PENALTY = $SIZE_BONUS;
  21. my $TITLE_PENALTY = $SIZE_BONUS / 2;
  22. my $MAX_SEED_RATIO = .25;
  23. my $SEED_RATIO_COUNT = 10;
  24. my $TRACKER_LOOKUP = 1;
  25. # App config
  26. my $DELAY = 4;
  27. my $TIMEOUT = 15;
  28. my $UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A';
  29. # Static tracker list, appended to all magnet URIs
  30. my @TRACKERS = ('udp://open.demonii.com:1337/announce', 'udp://tracker.publicbt.com:80/announce', 'udp://tracker.openbittorrent.com:80/announce', 'udp://9.rarbg.com:2710/announce');
  31. # Includes
  32. use URI::Encode qw(uri_encode);
  33. use HTML::Strip;
  34. use JSON;
  35. use File::Temp;
  36. use File::Spec;
  37. use File::Basename;
  38. use FindBin qw($Bin);
  39. use lib $Bin;
  40. use Fetch;
  41. # Prototypes
  42. sub resolveSecondary($);
  43. sub resolveTrackers($);
  44. sub splitTags($$$);
  45. sub findSE($);
  46. sub initSources();
  47. # Command line
  48. my ($dir, $search) = @ARGV;
  49. if (!defined($dir)) {
  50. die('Usage: ' . basename($0) . " input_directory [search_string]\n");
  51. }
  52. if ($ENV{'DEBUG'}) {
  53. $DEBUG = 1;
  54. }
  55. if ($ENV{'NO_QUALITY_CHECKS'}) {
  56. $NO_QUALITY_CHECKS = 1;
  57. }
  58. if ($ENV{'MORE_NUMBER_FORMATS'}) {
  59. $MORE_NUMBER_FORMATS = 1;
  60. }
  61. if (defined($ENV{'MIN_DAYS_BACK'})) {
  62. $MIN_DAYS_BACK = $ENV{'MIN_DAYS_BACK'};
  63. }
  64. if (defined($ENV{'MAX_DAYS_BACK'})) {
  65. $MAX_DAYS_BACK = $ENV{'MAX_DAYS_BACK'};
  66. }
  67. if (defined($ENV{'NEXT_EPISODES'})) {
  68. $NEXT_EPISODES = $ENV{'NEXT_EPISODES'};
  69. }
  70. # Fetch object
  71. my $cookies = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  72. my $fetch = Fetch->new(
  73. 'cookiefile' => $cookies,
  74. 'timeout' => $TIMEOUT,
  75. 'uas' => $UA
  76. );
  77. # Environment
  78. #if ($DEBUG) {
  79. # print STDERR `printenv` . "\n";
  80. #}
  81. # Figure out what we're searching for
  82. my $show = '';
  83. my @urls = ();
  84. my $CUSTOM_SEARCH = 0;
  85. my $season = 0;
  86. my @need = ();
  87. my %need = ();
  88. # Clean up the input "directory" path
  89. {
  90. # Allow use of the raw series name
  91. if (!($dir =~ /\//)) {
  92. $show = $dir;
  93. $dir = $TV_DIR . '/' . $dir;
  94. }
  95. # Allow use of relative paths
  96. $dir = File::Spec->rel2abs($dir);
  97. # Sanity check
  98. if (!-d $dir) {
  99. die('Invalid input directory: ' . $dir . "\n");
  100. }
  101. # Isolate the season from the path, if provided
  102. $dir =~ /\/Season\s+(\d+)\/?$/i;
  103. if ($1) {
  104. $season = $1;
  105. $dir = dirname($dir);
  106. }
  107. # If no season is provided find the latest
  108. if (!$season) {
  109. opendir(SERIES, $dir)
  110. or die("Unable to open series directory: ${!}\n");
  111. while (my $file = readdir(SERIES)) {
  112. if ($file =~ /^Season\s+(\d+)$/i) {
  113. if (!$season || $season < $1) {
  114. $season = $1;
  115. }
  116. }
  117. }
  118. closedir(SERIES);
  119. }
  120. # Isolate and clean the series name
  121. if (!$show) {
  122. $show = basename($dir);
  123. }
  124. $show =~ s/[\'\"\.]//g;
  125. if ($DEBUG) {
  126. print STDERR 'Checking directory: ' . $dir . "\n";
  127. }
  128. }
  129. # Allow quality checks to be disabled
  130. if (-e $dir . '/no_quality_checks') {
  131. $NO_QUALITY_CHECKS = 1;
  132. }
  133. # Read the excludes file, if any
  134. my $exclude = '';
  135. if (-e $dir . '/excludes') {
  136. local $/ = undef;
  137. open(EX, $dir . '/excludes')
  138. or die("Unable to open excludes file: ${!}\n");
  139. my $ex = <EX>;
  140. close(EX);
  141. $ex =~ s/^\s+//;
  142. $ex =~ s/^\s+//;
  143. my @excludes = split(/\s*,\s*/, $ex);
  144. foreach my $ex (@excludes) {
  145. if (length($exclude)) {
  146. $exclude .= ' ';
  147. }
  148. $exclude .= '-"' . $ex . '"';
  149. }
  150. $exclude = uri_encode(' ' . $exclude);
  151. }
  152. # Setup our sources
  153. my $SOURCES = initSources();
  154. # Adjust the inter-page delay with respect to the number of unique sources
  155. $DELAY /= scalar(keys(%{$SOURCES}));
  156. # Handle custom searches
  157. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  158. # Note the custom search string
  159. $CUSTOM_SEARCH = 1;
  160. if ($DEBUG) {
  161. print STDERR "Custom search\n";
  162. }
  163. # Create the relevent search strings
  164. foreach my $key (keys(%{$SOURCES})) {
  165. my $source = $SOURCES->{$key};
  166. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  167. }
  168. }
  169. # Handle search-by-date series
  170. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  171. # Note the search-by-date status
  172. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  173. $CUSTOM_SEARCH = 1;
  174. if ($DEBUG) {
  175. print STDERR "Find by date\n";
  176. }
  177. # Read the find-by-date string
  178. my $search_by_date = '';
  179. local ($/, *FH);
  180. open(FH, $dir . '/search_by_date')
  181. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  182. my $text = <FH>;
  183. close(FH);
  184. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  185. $search_by_date = $1;
  186. } else {
  187. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  188. }
  189. # Create search strings for each date in the range, unless the related file already exists
  190. my (%years, %months, %days) = ();
  191. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  192. # Calculate the date
  193. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  194. # Format as strings
  195. $year = sprintf('%04d', $year + 1900);
  196. $month = sprintf('%02d', $month + 1);
  197. $day = sprintf('%02d', $day);
  198. # Check for an existing file
  199. my $exists = 0;
  200. {
  201. my $season_dir = $dir . '/Season ' . $year;
  202. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  203. opendir(SEASON, $season_dir)
  204. or die("Unable to open season directory: ${!}\n");
  205. while (my $file = readdir(SEASON)) {
  206. if ($file =~ $prefix) {
  207. $exists = 1;
  208. last;
  209. }
  210. }
  211. closedir(SEASON);
  212. }
  213. if ($exists) {
  214. next;
  215. }
  216. # Save all the date string components
  217. $years{$year} = 1;
  218. $months{$month} = 1;
  219. $days{$day} = 1;
  220. # Create the relevent search strings
  221. my $search_str = $search_by_date;
  222. $search_str =~ s/%Y/${year}/g;
  223. $search_str =~ s/%m/${month}/g;
  224. $search_str =~ s/%d/${day}/g;
  225. foreach my $key (keys(%{$SOURCES})) {
  226. my $source = $SOURCES->{$key};
  227. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  228. }
  229. }
  230. # Build a date string matching regex
  231. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  232. $str .= '.*';
  233. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  234. $str .= '.*';
  235. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  236. $CUSTOM_SEARCH = qr/${str}/;
  237. }
  238. # Handle standard series
  239. if (scalar(@urls) < 1) {
  240. # Allow use of more number formats
  241. if (-e $dir . '/more_number_formats') {
  242. $MORE_NUMBER_FORMATS = 1;
  243. }
  244. # Allow the show name to be overriden
  245. {
  246. my $search_name = $dir . '/search_name';
  247. if (-e $search_name) {
  248. local ($/, *FH);
  249. open(FH, $search_name)
  250. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  251. my $text = <FH>;
  252. close(FH);
  253. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  254. $show = $1;
  255. } else {
  256. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  257. }
  258. }
  259. }
  260. if ($DEBUG) {
  261. print STDERR 'Searching with series title: ' . $show . "\n";
  262. }
  263. # Validate the season number
  264. if (!defined($season) || $season < 1 || $season > 2000) {
  265. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  266. }
  267. # Get the last episode number
  268. my $no_next = 0;
  269. my %episodes = ();
  270. my $highest = 0;
  271. opendir(SEASON, $dir . '/Season ' . $season)
  272. or die("Unable to open season directory: ${!}\n");
  273. while (my $file = readdir(SEASON)) {
  274. # Skip support files
  275. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  276. next;
  277. }
  278. # Check for a season_done file
  279. if ($file eq 'season_done') {
  280. $no_next = 1;
  281. next;
  282. }
  283. # Extract the episode number
  284. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  285. if (defined($num)) {
  286. $num = int($num);
  287. if ($DEBUG) {
  288. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  289. }
  290. # Record it
  291. $episodes{$num} = 1;
  292. # Track the highest episode number
  293. if ($num > $highest) {
  294. $highest = $num;
  295. }
  296. }
  297. }
  298. close(SEASON);
  299. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  300. if (!$no_next) {
  301. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  302. push(@need, $highest + $i);
  303. }
  304. }
  305. # Find any missing episodes
  306. for (my $i = 1 ; $i <= $highest ; $i++) {
  307. if (!$episodes{$i}) {
  308. push(@need, $i);
  309. }
  310. }
  311. if ($DEBUG) {
  312. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  313. }
  314. # Reverse the array for later matching
  315. foreach my $episode (@need) {
  316. $need{$episode} = 1;
  317. }
  318. # Construct a URL-friendly show name
  319. my $safeShow = $show;
  320. $safeShow =~ s/\s+\&\s+/ and /i;
  321. $safeShow =~ s/^\s*The\b//i;
  322. $safeShow =~ s/\s+\-\s+/ /g;
  323. $safeShow =~ s/[\'\:]//g;
  324. $safeShow =~ s/[^\w\"\-]+/ /g;
  325. $safeShow =~ s/^\s+//;
  326. $safeShow =~ s/\s+$//;
  327. $safeShow =~ s/\s\s+/ /g;
  328. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  329. $safeShow =~ s/\%20/\+/g;
  330. # Calculate possible name variations
  331. my @urlShowVarients = ();
  332. {
  333. # Default name
  334. push(@urlShowVarients, $safeShow);
  335. # Search for both "and" and "&"
  336. if ($safeShow =~ /\+and\+/i) {
  337. my $tmp = $safeShow;
  338. $tmp =~ s/\+and\+/\+%26\+/;
  339. push(@urlShowVarients, $tmp);
  340. }
  341. }
  342. # Construct the URL for each title varient of each needed episode
  343. foreach my $urlShow (@urlShowVarients) {
  344. foreach my $episode (@need) {
  345. my $episode_long = sprintf('%02d', $episode);
  346. my $season_long = sprintf('%02d', $season);
  347. foreach my $source (values(%{$SOURCES})) {
  348. # Use quotes around the show name if the source needs them
  349. my $quote = '%22';
  350. if (!$source->{'quote'}) {
  351. $quote = '';
  352. }
  353. # Calculate the compete search prefix and suffix to simplify later concatenations
  354. my $prefix = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote;
  355. my $suffix = $exclude;
  356. if ($source->{'search_suffix'}) {
  357. $suffix .= $source->{'search_suffix'};
  358. }
  359. # SXXEYY
  360. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  361. push(@urls, $url);
  362. # Extra searches for shows that have lazy/non-standard number formats
  363. if ($MORE_NUMBER_FORMATS) {
  364. # SXEY
  365. if ($season_long ne $season || $episode_long ne $episode) {
  366. $url = $prefix . '+s' . $season . 'e' . $episode . $exclude . $suffix;
  367. push(@urls, $url);
  368. }
  369. # SXX EYY
  370. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $exclude . $suffix;
  371. push(@urls, $url);
  372. # Season XX Episode YY
  373. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $exclude . $suffix;
  374. push(@urls, $url);
  375. # Series X Episode Y
  376. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $exclude . $suffix;
  377. push(@urls, $url);
  378. # SxEE
  379. $url = $prefix . '+' . $season . 'x' . $episode_long . $exclude . $suffix;
  380. push(@urls, $url);
  381. # Season X
  382. if ($NO_QUALITY_CHECKS) {
  383. $url = $prefix . '+Season+' . $season . $exclude . $suffix;
  384. push(@urls, $url);
  385. }
  386. }
  387. }
  388. }
  389. }
  390. }
  391. my @html_content = ();
  392. my @json_content = ();
  393. foreach my $url (@urls) {
  394. # Fetch the page
  395. if ($DEBUG) {
  396. print STDERR 'Searching with URL: ' . $url . "\n";
  397. $fetch->file('/tmp/findTorrent-lastPage.html');
  398. }
  399. sleep($DELAY * (rand(2) + 0.5));
  400. $fetch->url($url);
  401. $fetch->fetch('nocheck' => 1);
  402. # Check for useful errors
  403. if ($fetch->status_code() == 404) {
  404. if ($DEBUG) {
  405. print STDERR "Skipping content from 404 response\n";
  406. }
  407. next;
  408. }
  409. # Check for errors
  410. if ($fetch->status_code() != 200) {
  411. print STDERR 'Error fetching URL (' . $fetch->status_code() . '): ' . $url . "\n";
  412. next;
  413. }
  414. # Save the content, discriminating by data type
  415. if ($DEBUG) {
  416. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  417. }
  418. if ($fetch->content() =~ /^\s*{/) {
  419. my $json = eval { decode_json($fetch->content()); };
  420. if (defined($json) && ref($json)) {
  421. push(@json_content, \@{ $json->{'items'}->{'list'} });
  422. } elsif ($DEBUG) {
  423. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  424. }
  425. } else {
  426. push(@html_content, scalar($fetch->content()));
  427. }
  428. }
  429. # We need someplace to store parsed torrent data from the various sources
  430. my @tors = ();
  431. # Handle HTML content
  432. foreach my $content (@html_content) {
  433. if ($content =~ /\<title\>The Pirate Bay/i) {
  434. # Find TR elements from TPB
  435. my @trs = splitTags($content, 'TR', 'TH');
  436. foreach my $tr (@trs) {
  437. # Find the show title
  438. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  439. if (!defined($title) || length($title) < 1) {
  440. if ($DEBUG) {
  441. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  442. }
  443. next;
  444. }
  445. $title =~ s/^\s+//;
  446. # Extract the season and episode numbers
  447. my ($fileSeason, $episode) = findSE($title);
  448. # Extract the URL
  449. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  450. if (!defined($url) || length($url) < 1) {
  451. if ($DEBUG) {
  452. print STDERR "Skipping TR with no magnet URL\n";
  453. }
  454. next;
  455. }
  456. # Count the sum of seeders and leachers
  457. my $seeds = 0;
  458. my $leaches = 0;
  459. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  460. $seeds = $1;
  461. $leaches = $2;
  462. }
  463. # Extract the size (from separate column or inline)
  464. my $size = 0;
  465. my $unit = 'M';
  466. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  467. $size = $1;
  468. $unit = $2;
  469. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  470. $size = $1;
  471. $unit = $2;
  472. }
  473. if ($unit eq 'G') {
  474. $size *= 1024;
  475. }
  476. $size = int($size);
  477. if ($DEBUG) {
  478. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  479. }
  480. # Save the extracted data
  481. my %tor = (
  482. 'title' => $title,
  483. 'season' => $fileSeason,
  484. 'episode' => $episode,
  485. 'seeds' => $seeds,
  486. 'leaches' => $leaches,
  487. 'size' => $size,
  488. 'url' => $url,
  489. 'source' => 'TPB'
  490. );
  491. push(@tors, \%tor);
  492. }
  493. } elsif ($content =~ /Isohunt Torrent Search Engine\<\/title\>/i) {
  494. # Find each TR element from ISOHunt
  495. my @trs = splitTags($content, 'TR', 'TH');
  496. foreach my $tr (@trs) {
  497. # Split each TD element from the row
  498. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  499. my $numCols = scalar(@tds) - 1;
  500. if ($numCols > 9 && $numCols < 8) {
  501. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  502. next;
  503. }
  504. # Skip sponsored results
  505. if ($tds[1] =~ /Sponsored\<\/td\>/i) {
  506. if ($DEBUG > 1) {
  507. print STDERR "Skipping sponsored result\n";
  508. }
  509. next;
  510. }
  511. # Find the torrent ID and show title
  512. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+)\/[^\"]*\"\>\<span\>([^\>]+)\<\/span\>/i;
  513. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  514. if ($DEBUG) {
  515. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  516. }
  517. next;
  518. }
  519. $title =~ s/^\s+//;
  520. # Extract the season and episode numbers
  521. my ($fileSeason, $episode) = findSE($title);
  522. # Extract the size
  523. my $size = 0;
  524. my $unit = 'M';
  525. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  526. $size = $1;
  527. $unit = $2;
  528. }
  529. if ($unit eq 'G') {
  530. $size *= 1024;
  531. }
  532. $size = int($size);
  533. # Count the sum of seeders and leachers
  534. my $seeds = 0;
  535. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  536. $seeds = $1;
  537. }
  538. my $leaches = 0;
  539. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  540. $leaches = $1;
  541. }
  542. # Fetch the detail page for the URL
  543. my $url = $PROTOCOL . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id . '/';
  544. if ($DEBUG) {
  545. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  546. }
  547. # Save the extracted data
  548. my %tor = (
  549. 'title' => $title,
  550. 'season' => $fileSeason,
  551. 'episode' => $episode,
  552. 'seeds' => $seeds,
  553. 'leaches' => $leaches,
  554. 'size' => $size,
  555. 'url' => $url,
  556. 'source' => 'ISO'
  557. );
  558. push(@tors, \%tor);
  559. }
  560. } elsif ($content =~ /KickassTorrents\<\/title\>/i) {
  561. # Find each TR element from Kickass
  562. my @trs = splitTags($content, 'TR', 'TH');
  563. foreach my $tr (@trs) {
  564. # Split each TD element from the row
  565. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  566. my $numCols = scalar(@tds) - 1;
  567. if ($numCols > 9 && $numCols < 8) {
  568. print STDERR 'Invalid KICK TR: ' . $tr . "\n";
  569. next;
  570. }
  571. # Find the torrent title
  572. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  573. if (!defined($title) || length($title) < 1) {
  574. if ($DEBUG) {
  575. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  576. }
  577. next;
  578. }
  579. $title =~ s/^\s+//;
  580. # Find the torrent URL
  581. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  582. if (!defined($url) || length($url) < 1) {
  583. if ($DEBUG) {
  584. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  585. }
  586. next;
  587. }
  588. # Extract the season and episode numbers
  589. my ($fileSeason, $episode) = findSE($title);
  590. # Extract the size
  591. my $size = 0;
  592. my $unit = 'M';
  593. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  594. $size = $1;
  595. $unit = $2;
  596. }
  597. if ($unit eq 'G') {
  598. $size *= 1024;
  599. }
  600. $size = int($size);
  601. # Count the sum of seeders and leachers
  602. my $seeds = 0;
  603. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  604. $seeds = $1;
  605. }
  606. my $leaches = 0;
  607. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  608. $leaches = $1;
  609. }
  610. if ($DEBUG) {
  611. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  612. }
  613. # Save the extracted data
  614. my %tor = (
  615. 'title' => $title,
  616. 'season' => $fileSeason,
  617. 'episode' => $episode,
  618. 'seeds' => $seeds,
  619. 'leaches' => $leaches,
  620. 'size' => $size,
  621. 'url' => $url,
  622. 'source' => 'KICK'
  623. );
  624. push(@tors, \%tor);
  625. }
  626. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  627. # We'll need to strip HTML
  628. my $hs = HTML::Strip->new();
  629. # Find each DL element from Torrentz
  630. my @dls = splitTags($content, 'DL', undef());
  631. foreach my $dl (@dls) {
  632. # Skip ads
  633. if ($dl =~ /\s+rel\=\"nofollow/i) {
  634. next;
  635. }
  636. # Find the torrent title
  637. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  638. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  639. if ($DEBUG) {
  640. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  641. }
  642. next;
  643. }
  644. $title = $hs->parse($title);
  645. $hs->eof;
  646. $title =~ s/^\s+//;
  647. # Extract the season and episode numbers
  648. my ($fileSeason, $episode) = findSE($title);
  649. # Extract the size
  650. my $size = 0;
  651. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  652. $size = $1;
  653. if ($2 eq 'G') {
  654. $size *= 1024;
  655. }
  656. $size = int($size);
  657. }
  658. # Count the sum of seeders and leachers
  659. my $seeds = 0;
  660. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  661. $seeds = $1;
  662. }
  663. my $leaches = 0;
  664. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  665. $leaches = $1;
  666. }
  667. # Construct a magnet URL from the hash
  668. # Assume the seconary lookup will append a list of trackers
  669. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  670. if ($DEBUG) {
  671. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  672. }
  673. # Save the extracted data
  674. my %tor = (
  675. 'title' => $title,
  676. 'season' => $fileSeason,
  677. 'episode' => $episode,
  678. 'seeds' => $seeds,
  679. 'leaches' => $leaches,
  680. 'size' => $size,
  681. 'url' => $url,
  682. 'source' => 'Z'
  683. );
  684. push(@tors, \%tor);
  685. }
  686. } else {
  687. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  688. }
  689. }
  690. # Handle JSON content
  691. foreach my $content (@json_content) {
  692. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  693. }
  694. # Filter for size/count/etc.
  695. my %tors = ();
  696. my $showRegex = undef();
  697. {
  698. my $showClean = $show;
  699. $showClean =~ s/[\"\']//g;
  700. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  701. $showRegex = qr/^${showClean}[\W_]/i;
  702. }
  703. foreach my $tor (@tors) {
  704. # Skip files that don't start with our show title
  705. if (!($tor->{'title'} =~ $showRegex)) {
  706. if ($DEBUG) {
  707. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  708. }
  709. next;
  710. # Skip pre-air files
  711. } elsif ($tor->{'title'} =~ /preair/i) {
  712. if ($DEBUG) {
  713. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  714. }
  715. next;
  716. # Skip SWESUB files
  717. } elsif ($tor->{'title'} =~ /swesub/i) {
  718. if ($DEBUG) {
  719. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  720. }
  721. next;
  722. # Skip .rus. files
  723. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  724. if ($DEBUG) {
  725. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  726. }
  727. next;
  728. # Skip German files
  729. } elsif ($tor->{'title'} =~ /german/i) {
  730. if ($DEBUG) {
  731. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  732. }
  733. next;
  734. # Skip French files
  735. } elsif ($tor->{'title'} =~ /french/i) {
  736. if ($DEBUG) {
  737. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  738. }
  739. next;
  740. # Skip unedited files
  741. } elsif ($tor->{'title'} =~ /unedited/i) {
  742. if ($DEBUG) {
  743. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  744. }
  745. next;
  746. }
  747. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  748. if (!$CUSTOM_SEARCH) {
  749. # Skip files that don't contain the right season number
  750. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  751. if ($DEBUG) {
  752. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  753. }
  754. next;
  755. # Skip files that don't contain the episode number, unless MORE_NUMBER_FORMATS is set and NO_SEAONS is not
  756. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })
  757. && !($MORE_NUMBER_FORMATS && $NO_QUALITY_CHECKS && defined($tor->{'episode'}) && $tor->{'episode'} == 0))
  758. {
  759. if ($DEBUG) {
  760. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  761. }
  762. next;
  763. }
  764. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  765. # Skip files that don't match the regex
  766. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  767. if ($DEBUG) {
  768. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  769. }
  770. next;
  771. }
  772. }
  773. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  774. if (!$NO_QUALITY_CHECKS) {
  775. # Skip torrents with too few seeders/leachers
  776. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  777. if ($DEBUG) {
  778. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  779. }
  780. next;
  781. # Skip torrents with unusual seed/leach ratios
  782. } elsif ($tor->{'seeds'} > 1
  783. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  784. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  785. {
  786. if ($DEBUG) {
  787. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  788. }
  789. next;
  790. # Skip torrents that are too small
  791. } elsif ($tor->{'size'} < $MIN_SIZE) {
  792. if ($DEBUG) {
  793. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  794. }
  795. next;
  796. }
  797. }
  798. # Save good torrents
  799. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  800. if ($DEBUG) {
  801. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  802. }
  803. }
  804. # Find the average torrent size for each episode
  805. my %avg = ();
  806. foreach my $episode (keys(%tors)) {
  807. my $count = 0;
  808. $avg{$episode} = 0.001;
  809. foreach my $tor (@{ $tors{$episode} }) {
  810. $avg{$episode} += $tor->{'size'};
  811. $count++;
  812. }
  813. if ($count > 0) {
  814. $avg{$episode} /= $count;
  815. }
  816. if ($DEBUG) {
  817. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  818. }
  819. }
  820. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  821. foreach my $episode (keys(%tors)) {
  822. foreach my $tor (@{ $tors{$episode} }) {
  823. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  824. # Start with the peer count
  825. $tor->{'adj_count'} = $count;
  826. # Adjust based on file size
  827. {
  828. my $size_ratio = $tor->{'size'} / $avg{$episode};
  829. if ($tor->{'size'} >= $avg{$episode}) {
  830. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  831. } else {
  832. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  833. }
  834. }
  835. # Adjust based on title contents
  836. if ($tor->{'title'} =~ /Subtitulado/i) {
  837. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  838. }
  839. # Truncate to an integer
  840. $tor->{'adj_count'} = int($tor->{'adj_count'});
  841. if ($DEBUG) {
  842. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  843. }
  844. }
  845. }
  846. # Pick the best-adjusted-count torrent for each episode
  847. my %urls = ();
  848. foreach my $episode (keys(%tors)) {
  849. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  850. my $max = undef();
  851. foreach my $tor (@sorted) {
  852. if (!defined($max) || $tor->{'adj_count'} > $max) {
  853. if ($urls{$episode} = resolveSecondary($tor)) {
  854. $max = $tor->{'adj_count'};
  855. }
  856. if ($DEBUG) {
  857. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  858. }
  859. } elsif ($DEBUG) {
  860. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  861. }
  862. }
  863. }
  864. # Output
  865. foreach my $episode (keys(%tors)) {
  866. if (defined($urls{$episode})) {
  867. $urls{$episode} = resolveTrackers($urls{$episode});
  868. print $urls{$episode} . "\n";
  869. if ($DEBUG) {
  870. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  871. }
  872. } elsif ($DEBUG) {
  873. print STDERR 'No URL for: ' . $episode . "\n";
  874. }
  875. }
  876. # Cleanup
  877. unlink($cookies);
  878. exit(0);
  879. # Resolve secondary URLs
  880. sub resolveSecondary($) {
  881. my ($tor) = @_;
  882. my $url = $tor->{'url'};
  883. if ($tor->{'source'} eq 'ISO') {
  884. if ($DEBUG) {
  885. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  886. $fetch->file('/tmp/findTorrent-secondary.html');
  887. }
  888. sleep($DELAY * (rand(2) + 0.5));
  889. $fetch->url($tor->{'url'});
  890. $fetch->fetch();
  891. if ($fetch->status_code() != 200) {
  892. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  893. return undef();
  894. }
  895. ($url) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  896. if (!defined($url) || length($url) < 1) {
  897. if ($DEBUG) {
  898. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  899. }
  900. return undef();
  901. }
  902. }
  903. return $url;
  904. }
  905. sub resolveTrackers($) {
  906. my ($url) = @_;
  907. # Always append a few static trackers to the URI
  908. if ($url =~ /^magnet\:/i) {
  909. foreach my $tracker (@TRACKERS) {
  910. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  911. my $match = quotemeta($arg);
  912. if (!($url =~ /${match}/)) {
  913. $url .= $arg;
  914. }
  915. }
  916. }
  917. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  918. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  919. my $hash = $1;
  920. my $baseURL = $PROTOCOL . '://' . $SOURCES->{'Z'}->{'host'};
  921. my $hashURL = $baseURL . '/' . $hash;
  922. if ($DEBUG) {
  923. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  924. $fetch->file('/tmp/findTorrent-hashinfo.html');
  925. }
  926. sleep($DELAY * (rand(2) + 0.5));
  927. $fetch->url($hashURL);
  928. $fetch->fetch();
  929. if ($fetch->status_code() != 200) {
  930. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  931. return $url;
  932. }
  933. # Parse out and fetch the tracker list URL
  934. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  935. if (!defined($list)) {
  936. print STDERR "Unable to find tracker list link\n";
  937. return $url;
  938. }
  939. my $listURL = $baseURL . $list;
  940. if ($DEBUG) {
  941. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  942. $fetch->file('/tmp/findTorrent-tracker.html');
  943. }
  944. sleep($DELAY * (rand(2) + 0.5));
  945. $fetch->url($listURL);
  946. $fetch->fetch();
  947. if ($fetch->status_code() != 200) {
  948. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  949. return $url;
  950. }
  951. # Parse the tracker list and append our URL
  952. foreach my $line ($fetch->content()) {
  953. if ($line =~ /^\s*$/) {
  954. next;
  955. }
  956. $line =~ s/^\s+//;
  957. $line =~ s/\s+$//;
  958. if ($line =~ /^(?:http|udp)\:/i) {
  959. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  960. my $match = quotemeta($arg);
  961. if (!($url =~ /${match}/)) {
  962. if ($DEBUG) {
  963. print STDERR 'Adding tracker: ' . $line . "\n";
  964. }
  965. $url .= $arg;
  966. }
  967. } else {
  968. print STDERR 'Unknown tracker type: ' . $line . "\n";
  969. }
  970. }
  971. }
  972. return $url;
  973. }
  974. sub splitTags($$$) {
  975. my ($content, $tag, $header) = @_;
  976. # Find each tag element
  977. my @out = ();
  978. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  979. foreach my $part (@parts) {
  980. # Trim trailing tags and skip things that aren't complete tags
  981. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  982. if ($DEBUG > 1) {
  983. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  984. }
  985. next;
  986. }
  987. # Skip headers
  988. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  989. if ($DEBUG > 2) {
  990. print STDERR 'Skipping header line: ' . $part . "\n\n";
  991. }
  992. next;
  993. }
  994. # Save good tags
  995. push(@out, $part);
  996. }
  997. return @out;
  998. }
  999. # Extract season
  1000. sub findSE($) {
  1001. my ($title) = @_;
  1002. my $season = 0;
  1003. my $episode = 0;
  1004. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  1005. $season = $1;
  1006. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  1007. $season = $1;
  1008. $episode = $2;
  1009. }
  1010. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  1011. $episode = $1;
  1012. }
  1013. $season = int($season);
  1014. $episode = int($episode);
  1015. return ($season, $episode);
  1016. }
  1017. sub initSources() {
  1018. my %sources = ();
  1019. # The Pirate Bay
  1020. if ($ENABLE_SOURCE{'TPB'}) {
  1021. # Available TPB proxies, in order of preference
  1022. my @TPBs = ('thepiratebay.se/search/', 'pirateproxy.se/search/', 'tpb.unblocked.co/search/');
  1023. # Automatically select a proxy that returns a search page
  1024. my $host = '';
  1025. my $search_url = '';
  1026. foreach my $url (@TPBs) {
  1027. ($host) = $url =~ /^([^\/]+)/;
  1028. $fetch->url($PROTOCOL . '://' . $host);
  1029. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /\bSearch\b/i) {
  1030. $search_url = $url;
  1031. last;
  1032. } elsif ($DEBUG) {
  1033. print STDERR 'TPB proxy not available: ' . $host . "\n";
  1034. }
  1035. }
  1036. # Only add TPB if one of the proxies is up
  1037. if ($search_url) {
  1038. my %tmp = (
  1039. 'host' => $host,
  1040. 'search_url' => $search_url,
  1041. 'search_suffix' => '/0/7/0',
  1042. 'weight' => 1.5,
  1043. 'quote' => 0
  1044. );
  1045. $sources{'TPB'} = \%tmp;
  1046. }
  1047. }
  1048. # ISOhunt
  1049. if ($ENABLE_SOURCE{'ISO'}) {
  1050. # Available ISOhunt proxies, in order of preference
  1051. my @proxies = ('isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1052. # Automatically select a proxy that returns the non-US page
  1053. my $host = '';
  1054. my $search_url = '';
  1055. foreach my $url (@proxies) {
  1056. ($host) = $url =~ /^([^\/]+)/;
  1057. $fetch->url($PROTOCOL . '://' . $host);
  1058. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /Last\s+\d+\s+files\s+indexed/i) {
  1059. $search_url = $url;
  1060. last;
  1061. } elsif ($DEBUG) {
  1062. print STDERR 'ISOhunt proxy not available: ' . $host . "\n";
  1063. }
  1064. }
  1065. # Only add ISOhunt if one of the proxies is up
  1066. if ($search_url) {
  1067. my %tmp = (
  1068. 'host' => $host,
  1069. 'search_url' => $search_url,
  1070. 'search_suffix' => '',
  1071. 'weight' => 0.30,
  1072. 'quote' => 1
  1073. );
  1074. $sources{'ISO'} = \%tmp;
  1075. }
  1076. }
  1077. # Kickass
  1078. if ($ENABLE_SOURCE{'KICK'}) {
  1079. # Available Kickass proxies, in order of preference
  1080. my @proxies = ('katproxy.com/usearch/', 'kickass.so/usearch/');
  1081. # Automatically select a proxy that returns the non-US page
  1082. my $host = '';
  1083. my $search_url = '';
  1084. foreach my $url (@proxies) {
  1085. ($host) = $url =~ /^([^\/]+)/;
  1086. $fetch->url($PROTOCOL . '://' . $host);
  1087. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /torrent name\<\/th\>/i) {
  1088. $search_url = $url;
  1089. last;
  1090. } elsif ($DEBUG) {
  1091. print STDERR 'Kickass proxy not available: ' . $host . "\n";
  1092. }
  1093. }
  1094. # Only add Kickass if one of the proxies is up
  1095. if ($search_url) {
  1096. my %tmp = (
  1097. 'host' => $host,
  1098. 'search_url' => $search_url,
  1099. 'search_suffix' => '/',
  1100. 'weight' => 0.30,
  1101. 'quote' => 1
  1102. );
  1103. $sources{'KICK'} = \%tmp;
  1104. }
  1105. }
  1106. # Torrentz
  1107. if ($ENABLE_SOURCE{'Z'}) {
  1108. # Available Torrentz proxies, in order of preference
  1109. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1110. # Automatically select a proxy that returns the non-US page
  1111. my $host = '';
  1112. my $search_url = '';
  1113. foreach my $url (@proxies) {
  1114. ($host) = $url =~ /^([^\/]+)/;
  1115. $fetch->url($PROTOCOL . '://' . $host);
  1116. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /Indexing [\d\,]+ active torrents/i) {
  1117. $search_url = $url;
  1118. last;
  1119. } elsif ($DEBUG) {
  1120. print STDERR 'Torrentz proxy not available: ' . $host . "\n";
  1121. }
  1122. }
  1123. # Only add Torrentz if one of the proxies is up
  1124. if ($search_url) {
  1125. my %tmp = (
  1126. 'host' => $host,
  1127. 'search_url' => $search_url,
  1128. 'search_suffix' => '',
  1129. 'weight' => 1,
  1130. 'quote' => 1
  1131. );
  1132. if (!$NO_QUALITY_CHECKS) {
  1133. $tmp{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1134. }
  1135. $sources{'Z'} = \%tmp;
  1136. }
  1137. }
  1138. # Sanity check
  1139. if (scalar(keys(%sources)) < 1) {
  1140. die("No sources available\n");
  1141. }
  1142. return \%sources;
  1143. }