findTorrent.pl 37 KB

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