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