findTorrent.pl 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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. if ($DEBUG) {
  596. print STDERR "Skipping empty TD\n";
  597. }
  598. next;
  599. }
  600. # Find the torrent title
  601. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  602. if (!defined($title) || length($title) < 1) {
  603. if ($DEBUG) {
  604. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  605. }
  606. next;
  607. }
  608. $title =~ s/^\s+//;
  609. # Find the torrent URL
  610. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  611. if (!defined($url) || length($url) < 1) {
  612. if ($DEBUG) {
  613. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  614. }
  615. next;
  616. }
  617. $url = decode_entities($url);
  618. # Extract the season and episode numbers
  619. my ($fileSeason, $episode) = findSE($title);
  620. # Extract the size
  621. my $size = 0;
  622. my $unit = 'M';
  623. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  624. $size = $1;
  625. $unit = $2;
  626. }
  627. if ($unit eq 'G') {
  628. $size *= 1024;
  629. }
  630. $size = int($size);
  631. # Count the sum of seeders and leachers
  632. my $seeds = 0;
  633. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  634. $seeds = $1;
  635. }
  636. my $leaches = 0;
  637. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  638. $leaches = $1;
  639. }
  640. if ($DEBUG) {
  641. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  642. }
  643. # Save the extracted data
  644. my %tor = (
  645. 'title' => $title,
  646. 'season' => $fileSeason,
  647. 'episode' => $episode,
  648. 'seeds' => $seeds,
  649. 'leaches' => $leaches,
  650. 'size' => $size,
  651. 'url' => $url,
  652. 'source' => 'KICK'
  653. );
  654. push(@tors, \%tor);
  655. }
  656. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  657. # We'll need to strip HTML
  658. my $hs = HTML::Strip->new();
  659. # Find each DL element from Torrentz
  660. my @dls = splitTags($content, 'DL', undef());
  661. foreach my $dl (@dls) {
  662. # Skip ads
  663. if ($dl =~ /\s+rel\=\"nofollow/i) {
  664. next;
  665. }
  666. # Find the torrent title
  667. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  668. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  669. if ($DEBUG) {
  670. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  671. }
  672. next;
  673. }
  674. $title = $hs->parse($title);
  675. $hs->eof;
  676. $title =~ s/^\s+//;
  677. # Extract the season and episode numbers
  678. my ($fileSeason, $episode) = findSE($title);
  679. # Extract the size
  680. my $size = 0;
  681. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  682. $size = $1;
  683. if ($2 eq 'G') {
  684. $size *= 1024;
  685. }
  686. $size = int($size);
  687. }
  688. # Count the sum of seeders and leachers
  689. my $seeds = 0;
  690. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  691. $seeds = $1;
  692. }
  693. my $leaches = 0;
  694. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  695. $leaches = $1;
  696. }
  697. # Construct a magnet URL from the hash
  698. # Assume the seconary lookup will append a list of trackers
  699. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  700. if ($DEBUG) {
  701. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  702. }
  703. # Save the extracted data
  704. my %tor = (
  705. 'title' => $title,
  706. 'season' => $fileSeason,
  707. 'episode' => $episode,
  708. 'seeds' => $seeds,
  709. 'leaches' => $leaches,
  710. 'size' => $size,
  711. 'url' => $url,
  712. 'source' => 'Z'
  713. );
  714. push(@tors, \%tor);
  715. }
  716. } elsif ($content =~ /Database\s+maintenance/i) {
  717. if ($DEBUG) {
  718. print STDERR "Source down for maintenance\n";
  719. }
  720. } elsif ($content =~ /^\s*$/) {
  721. if ($DEBUG) {
  722. print STDERR "Source returned no content\n";
  723. }
  724. } else {
  725. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  726. }
  727. }
  728. # Handle JSON content
  729. foreach my $content (@json_content) {
  730. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  731. }
  732. # Filter for size/count/etc.
  733. my %tors = ();
  734. my $showRegex = undef();
  735. {
  736. my $showClean = $show;
  737. $showClean =~ s/[\"\']//g;
  738. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  739. $showRegex = qr/^${showClean}[\W_]/i;
  740. }
  741. foreach my $tor (@tors) {
  742. # Skip files that don't start with our show title
  743. if (!($tor->{'title'} =~ $showRegex)) {
  744. if ($DEBUG) {
  745. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  746. }
  747. next;
  748. # Skip pre-air files
  749. } elsif ($tor->{'title'} =~ /preair/i) {
  750. if ($DEBUG) {
  751. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  752. }
  753. next;
  754. # Skip SWESUB files
  755. } elsif ($tor->{'title'} =~ /swesub/i) {
  756. if ($DEBUG) {
  757. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  758. }
  759. next;
  760. # Skip .rus. files
  761. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  762. if ($DEBUG) {
  763. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  764. }
  765. next;
  766. # Skip German files
  767. } elsif ($tor->{'title'} =~ /german/i) {
  768. if ($DEBUG) {
  769. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  770. }
  771. next;
  772. # Skip French files
  773. } elsif ($tor->{'title'} =~ /french/i) {
  774. if ($DEBUG) {
  775. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  776. }
  777. next;
  778. # Skip unedited files
  779. } elsif ($tor->{'title'} =~ /unedited/i) {
  780. if ($DEBUG) {
  781. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  782. }
  783. next;
  784. }
  785. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  786. if (!$CUSTOM_SEARCH) {
  787. # Skip files that don't contain the right season number
  788. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  789. if ($DEBUG) {
  790. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  791. }
  792. next;
  793. # Skip files that don't contain the episode number, unless MORE_NUMBER_FORMATS is set and NO_SEAONS is not
  794. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })
  795. && !($MORE_NUMBER_FORMATS && $NO_QUALITY_CHECKS && defined($tor->{'episode'}) && $tor->{'episode'} == 0))
  796. {
  797. if ($DEBUG) {
  798. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  799. }
  800. next;
  801. }
  802. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  803. # Skip files that don't match the regex
  804. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  805. if ($DEBUG) {
  806. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  807. }
  808. next;
  809. }
  810. }
  811. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  812. if (!$NO_QUALITY_CHECKS) {
  813. # Skip torrents with too few seeders/leachers
  814. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  815. if ($DEBUG) {
  816. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  817. }
  818. next;
  819. # Skip torrents with unusual seed/leach ratios
  820. } elsif ($tor->{'seeds'} > 1
  821. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  822. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  823. {
  824. if ($DEBUG) {
  825. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  826. }
  827. next;
  828. # Skip torrents that are too small
  829. } elsif ($tor->{'size'} < $MIN_SIZE) {
  830. if ($DEBUG) {
  831. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  832. }
  833. next;
  834. }
  835. }
  836. # Save good torrents
  837. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  838. if ($DEBUG) {
  839. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  840. }
  841. }
  842. # Find the average torrent size for each episode
  843. my %avg = ();
  844. foreach my $episode (keys(%tors)) {
  845. my $count = 0;
  846. $avg{$episode} = 0.001;
  847. foreach my $tor (@{ $tors{$episode} }) {
  848. $avg{$episode} += $tor->{'size'};
  849. $count++;
  850. }
  851. if ($count > 0) {
  852. $avg{$episode} /= $count;
  853. }
  854. if ($DEBUG) {
  855. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  856. }
  857. }
  858. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  859. foreach my $episode (keys(%tors)) {
  860. foreach my $tor (@{ $tors{$episode} }) {
  861. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  862. # Start with the peer count
  863. $tor->{'adj_count'} = $count;
  864. # Adjust based on file size
  865. {
  866. my $size_ratio = $tor->{'size'} / $avg{$episode};
  867. if ($tor->{'size'} >= $avg{$episode}) {
  868. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  869. } else {
  870. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  871. }
  872. }
  873. # Adjust based on title contents
  874. if ($tor->{'title'} =~ /Subtitulado/i) {
  875. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  876. }
  877. # Truncate to an integer
  878. $tor->{'adj_count'} = int($tor->{'adj_count'});
  879. if ($DEBUG) {
  880. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  881. }
  882. }
  883. }
  884. # Pick the best-adjusted-count torrent for each episode
  885. my %urls = ();
  886. foreach my $episode (keys(%tors)) {
  887. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  888. my $max = undef();
  889. foreach my $tor (@sorted) {
  890. if (!defined($max) || $tor->{'adj_count'} > $max) {
  891. if ($urls{$episode} = resolveSecondary($tor)) {
  892. $max = $tor->{'adj_count'};
  893. }
  894. if ($DEBUG) {
  895. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  896. }
  897. } elsif ($DEBUG) {
  898. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  899. }
  900. }
  901. }
  902. # Output
  903. foreach my $episode (keys(%tors)) {
  904. if (defined($urls{$episode})) {
  905. $urls{$episode} = resolveTrackers($urls{$episode});
  906. print $urls{$episode} . "\n";
  907. if ($DEBUG) {
  908. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  909. }
  910. } elsif ($DEBUG) {
  911. print STDERR 'No URL for: ' . $episode . "\n";
  912. }
  913. }
  914. # Cleanup
  915. unlink($cookies);
  916. exit(0);
  917. # Resolve secondary URLs
  918. sub resolveSecondary($) {
  919. my ($tor) = @_;
  920. my $url = $tor->{'url'};
  921. if ($tor->{'source'} eq 'ISO') {
  922. if ($DEBUG) {
  923. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  924. $fetch->file('/tmp/findTorrent-secondary.html');
  925. }
  926. sleep($DELAY * (rand(2) + 0.5));
  927. $fetch->url($tor->{'url'});
  928. $fetch->fetch();
  929. if ($fetch->status_code() != 200) {
  930. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  931. return undef();
  932. }
  933. ($url) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  934. if (!defined($url) || length($url) < 1) {
  935. if ($DEBUG) {
  936. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  937. }
  938. return undef();
  939. }
  940. $url = decode_entities($url);
  941. }
  942. return $url;
  943. }
  944. sub resolveTrackers($) {
  945. my ($url) = @_;
  946. # Always append a few static trackers to the URI
  947. if ($url =~ /^magnet\:/i) {
  948. foreach my $tracker (@TRACKERS) {
  949. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  950. my $match = quotemeta($arg);
  951. if (!($url =~ /${match}/)) {
  952. $url .= $arg;
  953. }
  954. }
  955. }
  956. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  957. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  958. my $hash = $1;
  959. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  960. my $hashURL = $baseURL . '/' . $hash;
  961. if ($DEBUG) {
  962. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  963. $fetch->file('/tmp/findTorrent-hashinfo.html');
  964. }
  965. sleep($DELAY * (rand(2) + 0.5));
  966. $fetch->url($hashURL);
  967. $fetch->fetch();
  968. if ($fetch->status_code() != 200) {
  969. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  970. return $url;
  971. }
  972. # Parse out and fetch the tracker list URL
  973. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  974. if (!defined($list)) {
  975. print STDERR "Unable to find tracker list link\n";
  976. return $url;
  977. }
  978. my $listURL = $baseURL . $list;
  979. if ($DEBUG) {
  980. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  981. $fetch->file('/tmp/findTorrent-tracker.html');
  982. }
  983. sleep($DELAY * (rand(2) + 0.5));
  984. $fetch->url($listURL);
  985. $fetch->fetch();
  986. if ($fetch->status_code() != 200) {
  987. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  988. return $url;
  989. }
  990. # Parse the tracker list and append our URL
  991. foreach my $line ($fetch->content()) {
  992. if ($line =~ /^\s*$/) {
  993. next;
  994. }
  995. $line =~ s/^\s+//;
  996. $line =~ s/\s+$//;
  997. if ($line =~ /^(?:http|udp)\:/i) {
  998. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  999. my $match = quotemeta($arg);
  1000. if (!($url =~ /${match}/)) {
  1001. if ($DEBUG) {
  1002. print STDERR 'Adding tracker: ' . $line . "\n";
  1003. }
  1004. $url .= $arg;
  1005. }
  1006. } else {
  1007. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1008. }
  1009. }
  1010. }
  1011. return $url;
  1012. }
  1013. sub splitTags($$$) {
  1014. my ($content, $tag, $header) = @_;
  1015. # Find each tag element
  1016. my @out = ();
  1017. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1018. foreach my $part (@parts) {
  1019. # Trim trailing tags and skip things that aren't complete tags
  1020. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1021. if ($DEBUG > 1) {
  1022. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1023. }
  1024. next;
  1025. }
  1026. # Skip headers
  1027. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1028. if ($DEBUG > 2) {
  1029. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1030. }
  1031. next;
  1032. }
  1033. # Save good tags
  1034. push(@out, $part);
  1035. }
  1036. return @out;
  1037. }
  1038. # Extract season
  1039. sub findSE($) {
  1040. my ($title) = @_;
  1041. my $season = 0;
  1042. my $episode = 0;
  1043. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  1044. $season = $1;
  1045. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  1046. $season = $1;
  1047. $episode = $2;
  1048. }
  1049. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  1050. $episode = $1;
  1051. }
  1052. $season = int($season);
  1053. $episode = int($episode);
  1054. return ($season, $episode);
  1055. }
  1056. sub initSources() {
  1057. my %sources = ();
  1058. # The Pirate Bay
  1059. if ($ENABLE_SOURCE{'TPB'}) {
  1060. my @proxies = ('thepiratebay.se/search/', 'pirateproxy.se/search/', 'tpb.unblocked.co/search/');
  1061. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1062. if ($source) {
  1063. $source->{'weight'} = 1.00;
  1064. $source->{'quote'} = 0;
  1065. $source->{'search_suffix'} = '/0/7/0';
  1066. $sources{'TPB'} = $source;
  1067. }
  1068. }
  1069. # ISOhunt
  1070. if ($ENABLE_SOURCE{'ISO'}) {
  1071. my @proxies = ('http://isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1072. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1073. if ($source) {
  1074. $source->{'weight'} = 0.25;
  1075. $source->{'quote'} = 1;
  1076. $source->{'search_suffix'} = '';
  1077. $sources{'ISO'} = $source;
  1078. }
  1079. }
  1080. # Kickass
  1081. if ($ENABLE_SOURCE{'KICK'}) {
  1082. my @proxies = ('http://katproxy.com/usearch/', 'kickass.so/usearch/');
  1083. my $source = findProxy(\@proxies, 'torrent name\<\/th\>');
  1084. if ($source) {
  1085. $source->{'weight'} = 0.50;
  1086. $source->{'quote'} = 1;
  1087. $source->{'search_suffix'} = '/';
  1088. $sources{'KICK'} = $source;
  1089. }
  1090. }
  1091. # Torrentz
  1092. if ($ENABLE_SOURCE{'Z'}) {
  1093. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1094. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1095. if ($source) {
  1096. $source->{'weight'} = 0.75;
  1097. $source->{'quote'} = 1;
  1098. $source->{'search_suffix'} = '';
  1099. if (!$NO_QUALITY_CHECKS) {
  1100. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1101. }
  1102. $sources{'Z'} = $source;
  1103. }
  1104. }
  1105. # Sanity check
  1106. if (scalar(keys(%sources)) < 1) {
  1107. die("No sources available\n");
  1108. }
  1109. return \%sources;
  1110. }
  1111. sub findProxy($$) {
  1112. my ($proxies, $match) = @_;
  1113. # Automatically select a proxy
  1114. my $host = '';
  1115. my $protocol = '';
  1116. my $search_url = '';
  1117. foreach my $url (@{$proxies}) {
  1118. my $path;
  1119. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1120. if (!$protocol) {
  1121. $protocol = $PROTOCOL;
  1122. }
  1123. if (!$host) {
  1124. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1125. next;
  1126. }
  1127. $fetch->url($protocol . '://' . $host);
  1128. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1129. $search_url = $protocol . '://' . $host . $path;
  1130. last;
  1131. } elsif ($DEBUG) {
  1132. print STDERR 'Proxy not available: ' . $host . "\n";
  1133. }
  1134. }
  1135. # Return the search data if at least one proxy is up
  1136. if ($search_url) {
  1137. my %tmp = (
  1138. 'protocol' => $protocol,
  1139. 'host' => $host,
  1140. 'search_url' => $search_url,
  1141. );
  1142. return \%tmp;
  1143. }
  1144. # Return undef if we didn't find any working proxies
  1145. return undef();
  1146. }