findTorrent.pl 35 KB

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