findTorrent.pl 35 KB

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