findTorrent.pl 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Defaults
  5. my $DEBUG = 0;
  6. my $SYSLOG = 1;
  7. my $NO_QUALITY_CHECKS = 0;
  8. my $MORE_NUMBER_FORMATS = 0;
  9. my $MIN_DAYS_BACK = 0;
  10. my $MAX_DAYS_BACK = 3;
  11. my $NEXT_EPISODES = 3;
  12. # Local config
  13. my $TV_DIR = `~/bin/video/mediaPath` . '/TV';
  14. my $CONF_FILE = $ENV{'HOME'} . +'/.findTorrent.config';
  15. my $EXCLUDES_FILE = $ENV{'HOME'} . '/.findTorrent.exclude';
  16. # Selection parameters
  17. my $MIN_COUNT = 10;
  18. my $MIN_SIZE = 100;
  19. my $SIZE_BONUS = 5;
  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. my $QUALITY_AGE = (86400 * 365);
  26. # App config
  27. my $SLEEP = 1;
  28. my $DELAY = 10;
  29. my $TIMEOUT = 15;
  30. my $ERR_DELAY = $TIMEOUT * 2;
  31. my $ERR_RETRIES = 3;
  32. my $COOKIES = undef();
  33. my $FETCH = undef();
  34. my $PHANTOM = '/usr/local/bin/phantomjs';
  35. 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';
  36. my $PHANTOM_CONFIG = "var system = require('system');
  37. var page = require('webpage').create();
  38. var resources = [];
  39. page.open(system.args[1], function(status)
  40. {
  41. console.log(resources[0].status);
  42. console.log(page.content);
  43. phantom.exit();
  44. });
  45. // Add responses for completed text/html resources
  46. page.onResourceReceived = function(response) {
  47. if (response.stage !== 'end') return;
  48. if (response.headers.filter(function(header) {
  49. if (header.name == 'Content-Type' && header.value.indexOf('text/html') == 0) {
  50. return true;
  51. }
  52. return false;
  53. }).length > 0)
  54. resources.push(response);
  55. };";
  56. # Includes
  57. use Date::Parse;
  58. use URI::Encode qw(uri_encode);
  59. use HTML::Entities;
  60. use HTML::Strip;
  61. use JSON;
  62. use Sys::Syslog qw(:standard :macros);
  63. use Capture::Tiny ':all';
  64. use File::Temp;
  65. use File::Spec;
  66. use File::Basename;
  67. use FindBin qw($Bin);
  68. use lib $Bin;
  69. use Fetch;
  70. # Prototypes
  71. sub getHash($);
  72. sub resolveSecondary($);
  73. sub resolveTrackers($);
  74. sub splitTags($$$$);
  75. sub findSE($);
  76. sub initSources();
  77. sub findProxy($$);
  78. sub fetch($;$$);
  79. sub phantomFetch($$);
  80. # Command line
  81. my ($dir, $search) = @ARGV;
  82. if (!defined($dir)) {
  83. die('Usage: ' . basename($0) . " input_directory [search_string]\n");
  84. }
  85. # Environment
  86. if ($ENV{'DEBUG'}) {
  87. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  88. $DEBUG = $1;
  89. } else {
  90. $DEBUG = 1;
  91. }
  92. }
  93. if (exists($ENV{'EXCLUDES_FILE'})) {
  94. $EXCLUDES_FILE = $ENV{'EXCLUDES_FILE'};
  95. }
  96. if ($ENV{'NO_QUALITY_CHECKS'}) {
  97. $NO_QUALITY_CHECKS = 1;
  98. }
  99. if ($ENV{'MORE_NUMBER_FORMATS'}) {
  100. $MORE_NUMBER_FORMATS = 1;
  101. }
  102. if (defined($ENV{'MIN_DAYS_BACK'})) {
  103. $MIN_DAYS_BACK = $ENV{'MIN_DAYS_BACK'};
  104. }
  105. if (defined($ENV{'MAX_DAYS_BACK'})) {
  106. $MAX_DAYS_BACK = $ENV{'MAX_DAYS_BACK'};
  107. }
  108. if (defined($ENV{'NEXT_EPISODES'})) {
  109. $NEXT_EPISODES = $ENV{'NEXT_EPISODES'};
  110. }
  111. if (defined($ENV{'SYSLOG'})) {
  112. $SYSLOG = $ENV{'SYSLOG'};
  113. }
  114. # Read the config file
  115. my %CONFIG = ();
  116. if ($CONF_FILE && -r $CONF_FILE) {
  117. my $fh;
  118. open($fh, '<', $CONF_FILE)
  119. or die('Unable to open config file: ' . $CONF_FILE . ': ' . $! . "\n");
  120. while (<$fh>) {
  121. # Skip blank lines and comments
  122. if (/^\s*#/ || /^\s*$/) {
  123. next;
  124. }
  125. # Assume everything else is key = val pairs
  126. if (my ($key, $val) = $_ =~ /^\s*(\S[^\=]+)\=\>?\s*(\S.*)$/) {
  127. $key =~ s/^\s+//;
  128. $key =~ s/\s+$//;
  129. $val =~ s/^\s+//;
  130. $val =~ s/\s+$//;
  131. $CONFIG{$key} = $val;
  132. if ($DEBUG) {
  133. print STDERR 'Adding config: ' . $key . ' => ' . $val . "\n";
  134. }
  135. } else {
  136. warn('Ignoring config line: ' . $_ . "\n");
  137. }
  138. }
  139. close($fh);
  140. }
  141. # Parse config items
  142. my $PROTOCOL = 'https';
  143. if (exists($CONFIG{'PROTOCOL'})) {
  144. $PROTOCOL = $CONFIG{'PROTOCOL'};
  145. }
  146. my @TRACKERS = ();
  147. if (exists($CONFIG{'TRACKERS'})) {
  148. foreach my $tracker (split(/\s*,\s*/, $CONFIG{'TRACKERS'})) {
  149. $tracker =~ s/^\s+//;
  150. $tracker =~ s/\s+$//;
  151. push(@TRACKERS, $tracker);
  152. }
  153. }
  154. my %ENABLE_SOURCE = ();
  155. if (exists($CONFIG{'SOURCES'})) {
  156. foreach my $source (split(/\s*,\s*/, $CONFIG{'SOURCES'})) {
  157. $source =~ s/^\s+//;
  158. $source =~ s/\s+$//;
  159. $source = uc($source);
  160. $ENABLE_SOURCE{$source} = 1;
  161. }
  162. }
  163. # Phantom setup
  164. my $SCRIPT = undef();
  165. # Open the log if enabled
  166. if ($SYSLOG) {
  167. openlog(basename($0), '', LOG_DAEMON);
  168. }
  169. # Read the torrent excludes list
  170. my %EXCLUDES = ();
  171. if ($EXCLUDES_FILE && -r $EXCLUDES_FILE) {
  172. my $fh;
  173. open($fh, '<', $EXCLUDES_FILE)
  174. or die('Unable to open excludes file: ' . $EXCLUDES_FILE . ': ' . $! . "\n");
  175. while (<$fh>) {
  176. # Skip blank lines and comments
  177. if (/^\s*$/ || /^\s*#/) {
  178. next;
  179. }
  180. # Assume everything else is one BT hash per line
  181. if (/^\s*(\w+)\s*$/) {
  182. my $hash = lc($1);
  183. if ($DEBUG > 1) {
  184. print STDERR 'Excluding hash: ' . $hash . "\n";
  185. }
  186. $EXCLUDES{$hash} = 1;
  187. } else {
  188. die('Invalid exclude line: ' . $_ . "\n");
  189. }
  190. }
  191. close($fh);
  192. } elsif ($DEBUG) {
  193. print STDERR 'No excludes file available';
  194. if ($EXCLUDES_FILE) {
  195. print STDERR ': ' . $EXCLUDES_FILE;
  196. }
  197. print STDERR "\n";
  198. }
  199. # Figure out what we're searching for
  200. my $show = '';
  201. my @urls = ();
  202. my $CUSTOM_SEARCH = 0;
  203. my $season = 0;
  204. my @need = ();
  205. my %need = ();
  206. # Clean up the input "directory" path
  207. {
  208. # Allow use of the raw series name
  209. if (!($dir =~ /\//)) {
  210. $show = $dir;
  211. $dir = $TV_DIR . '/' . $dir;
  212. }
  213. # Allow use of relative paths
  214. $dir = File::Spec->rel2abs($dir);
  215. # Sanity check
  216. if (!-d $dir) {
  217. die('Invalid input directory: ' . $dir . "\n");
  218. }
  219. # Isolate the season from the path, if provided
  220. $dir =~ /\/Season\s+(\d+)\/?$/i;
  221. if ($1) {
  222. $season = $1;
  223. $dir = dirname($dir);
  224. }
  225. # If no season is provided find the latest
  226. if (!$season) {
  227. opendir(SERIES, $dir)
  228. or die("Unable to open series directory: ${!}\n");
  229. while (my $file = readdir(SERIES)) {
  230. if ($file =~ /^Season\s+(\d+)$/i) {
  231. if (!$season || $season < $1) {
  232. $season = $1;
  233. }
  234. }
  235. }
  236. closedir(SERIES);
  237. }
  238. # Isolate and clean the series name
  239. if (!$show) {
  240. $show = basename($dir);
  241. }
  242. $show =~ s/[\'\"\.]//g;
  243. if ($DEBUG) {
  244. print STDERR 'Checking directory: ' . $dir . "\n";
  245. }
  246. if ($SYSLOG) {
  247. syslog(LOG_NOTICE, $show);
  248. }
  249. }
  250. # Allow the show name to be overriden
  251. {
  252. my $search_name = $dir . '/search_name';
  253. if (-e $search_name) {
  254. local ($/, *FH);
  255. open(FH, $search_name)
  256. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  257. my $text = <FH>;
  258. close(FH);
  259. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  260. $show = $1;
  261. } else {
  262. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  263. }
  264. }
  265. if ($DEBUG) {
  266. print STDERR 'Searching with series title: ' . $show . "\n";
  267. }
  268. }
  269. # Allow quality checks to be disabled
  270. if (-e $dir . '/no_quality_checks') {
  271. $NO_QUALITY_CHECKS = 1;
  272. if ($DEBUG) {
  273. print STDERR 'Searching with no quality checks: ' . $show . "\n";
  274. }
  275. }
  276. # Allow use of more number formats
  277. if (-e $dir . '/more_number_formats') {
  278. $MORE_NUMBER_FORMATS = 1;
  279. if ($DEBUG) {
  280. print STDERR 'Searching with more number formats: ' . $show . "\n";
  281. }
  282. }
  283. # Read the search excludes file, if any
  284. my $exclude = '';
  285. my %TITLE_EXCLUDES = ();
  286. if (-e $dir . '/excludes') {
  287. local $/ = undef;
  288. open(EX, $dir . '/excludes')
  289. or die("Unable to open series excludes file: ${!}\n");
  290. my $ex = <EX>;
  291. close(EX);
  292. $ex =~ s/^\s+//;
  293. $ex =~ s/\s+$//;
  294. my @excludes = split(/\s*,\s*/, $ex);
  295. foreach my $ex (@excludes) {
  296. $TITLE_EXCLUDES{$ex} = 1;
  297. if (length($exclude)) {
  298. $exclude .= ' ';
  299. }
  300. $exclude .= '-"' . $ex . '"';
  301. }
  302. $exclude = uri_encode(' ' . $exclude);
  303. }
  304. # Setup our sources
  305. my $SOURCES = initSources();
  306. # Adjust the inter-page delay with respect to the number of unique sources
  307. $DELAY /= scalar(keys(%{$SOURCES})) / 2;
  308. # Handle custom searches
  309. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  310. # Note the custom search string
  311. $CUSTOM_SEARCH = 1;
  312. if ($DEBUG) {
  313. print STDERR "Custom search\n";
  314. }
  315. # Create the relevent search strings
  316. foreach my $key (keys(%{$SOURCES})) {
  317. my $source = $SOURCES->{$key};
  318. push(@urls, $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  319. }
  320. }
  321. # Handle search-by-date series
  322. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  323. # Note the search-by-date status
  324. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  325. $CUSTOM_SEARCH = 1;
  326. # Read the find-by-date string
  327. my $search_by_date = '';
  328. local ($/, *FH);
  329. open(FH, $dir . '/search_by_date')
  330. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  331. my $text = <FH>;
  332. close(FH);
  333. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  334. $search_by_date = $1;
  335. } else {
  336. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  337. }
  338. # Create search strings for each date in the range, unless the related file already exists
  339. my (%years, %months, %days) = ();
  340. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  341. # Calculate the date
  342. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  343. # Format as strings
  344. $year = sprintf('%04d', $year + 1900);
  345. $month = sprintf('%02d', $month + 1);
  346. $day = sprintf('%02d', $day);
  347. # Check for an existing file
  348. my $exists = 0;
  349. {
  350. my $season_dir = $dir . '/Season ' . $year;
  351. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  352. opendir(SEASON, $season_dir)
  353. or die('Unable to open season directory (' . $season_dir . '): ' . $! . "\n");
  354. while (my $file = readdir(SEASON)) {
  355. if ($file =~ $prefix) {
  356. $exists = 1;
  357. last;
  358. }
  359. }
  360. closedir(SEASON);
  361. }
  362. if ($exists) {
  363. next;
  364. }
  365. # Save all the date string components
  366. $years{$year} = 1;
  367. $months{$month} = 1;
  368. $days{$day} = 1;
  369. # Create the relevent search strings
  370. my $search_str = $search_by_date;
  371. $search_str =~ s/%Y/${year}/g;
  372. $search_str =~ s/%m/${month}/g;
  373. $search_str =~ s/%d/${day}/g;
  374. foreach my $key (keys(%{$SOURCES})) {
  375. my $source = $SOURCES->{$key};
  376. push(@urls, $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  377. }
  378. }
  379. # Build a date string matching regex
  380. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  381. $str .= '.*';
  382. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  383. $str .= '.*';
  384. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  385. $CUSTOM_SEARCH = qr/${str}/;
  386. # Debug
  387. if ($DEBUG) {
  388. print STDERR 'Searching with date template: ' . $str . "\n";
  389. }
  390. }
  391. # Handle standard series
  392. if (scalar(@urls) < 1) {
  393. # Validate the season number
  394. if (!defined($season) || $season < 1 || $season > 2000) {
  395. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  396. }
  397. # Get the last episode number
  398. my $no_next = 0;
  399. my %episodes = ();
  400. my $highest = 0;
  401. opendir(SEASON, $dir . '/Season ' . $season)
  402. or die("Unable to open season directory: ${!}\n");
  403. while (my $file = readdir(SEASON)) {
  404. # Skip support files
  405. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  406. next;
  407. }
  408. # Check for a season_done file
  409. if ($file eq 'season_done') {
  410. $no_next = 1;
  411. next;
  412. }
  413. # Extract the episode number
  414. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  415. if (defined($num)) {
  416. $num = int($num);
  417. if ($DEBUG) {
  418. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  419. }
  420. # Record it
  421. $episodes{$num} = 1;
  422. # Track the highest episode number
  423. if ($num > $highest) {
  424. $highest = $num;
  425. }
  426. }
  427. }
  428. close(SEASON);
  429. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  430. if (!$no_next) {
  431. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  432. push(@need, $highest + $i);
  433. }
  434. }
  435. # Find any missing episodes
  436. for (my $i = 1 ; $i <= $highest ; $i++) {
  437. if (!$episodes{$i}) {
  438. push(@need, $i);
  439. }
  440. }
  441. if ($DEBUG) {
  442. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  443. }
  444. # Reverse the array for later matching
  445. foreach my $episode (@need) {
  446. $need{$episode} = 1;
  447. }
  448. # Construct a URL-friendly show name
  449. my $safeShow = $show;
  450. $safeShow =~ s/\s+\&\s+/ and /i;
  451. $safeShow =~ s/^\s*The\b//i;
  452. $safeShow =~ s/\s+\-\s+/ /g;
  453. $safeShow =~ s/[\'\:]//g;
  454. $safeShow =~ s/[^\w\"\-]+/ /g;
  455. $safeShow =~ s/^\s+//;
  456. $safeShow =~ s/\s+$//;
  457. $safeShow =~ s/\s\s+/ /g;
  458. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  459. $safeShow =~ s/\%20/\+/g;
  460. # Calculate possible name variations
  461. my @urlShowVarients = ();
  462. {
  463. # Default name
  464. push(@urlShowVarients, $safeShow);
  465. # Search for both "and" and "&"
  466. if ($safeShow =~ /\+and\+/i) {
  467. my $tmp = $safeShow;
  468. $tmp =~ s/\+and\+/\+%26\+/;
  469. push(@urlShowVarients, $tmp);
  470. }
  471. }
  472. # Construct the URL for each title varient of each needed episode
  473. foreach my $urlShow (@urlShowVarients) {
  474. foreach my $episode (@need) {
  475. my $episode_long = sprintf('%02d', $episode);
  476. my $season_long = sprintf('%02d', $season);
  477. foreach my $source (values(%{$SOURCES})) {
  478. # Allow custom handling
  479. if (defined($source->{'custom_search'}) && ref($source->{'custom_search'}) eq 'CODE') {
  480. $source->{'custom_search'}->(\@urls, $urlShow, $season, $episode);
  481. next;
  482. }
  483. # Use quotes around the show name if the source needs them
  484. my $quote = '%22';
  485. if (!$source->{'quote'}) {
  486. $quote = '';
  487. }
  488. # Calculate the compete search prefix and suffix to simplify later concatenations
  489. my $prefix = $source->{'search_url'} . $quote . $urlShow . $quote;
  490. my $suffix = '';
  491. if ($source->{'search_exclude'}) {
  492. $suffix .= $exclude;
  493. }
  494. if ($source->{'search_suffix'}) {
  495. $suffix .= $source->{'search_suffix'};
  496. }
  497. # SXXEYY
  498. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  499. push(@urls, $url);
  500. # Extra searches for shows that have lazy/non-standard number formats
  501. if ($MORE_NUMBER_FORMATS) {
  502. # SXEY
  503. if ($season_long ne $season || $episode_long ne $episode) {
  504. $url = $prefix . '+s' . $season . 'e' . $episode . $suffix;
  505. push(@urls, $url);
  506. }
  507. # SXX EYY
  508. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $suffix;
  509. push(@urls, $url);
  510. # Season XX Episode YY
  511. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $suffix;
  512. push(@urls, $url);
  513. # Series X Episode Y
  514. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $suffix;
  515. push(@urls, $url);
  516. # SxEE
  517. $url = $prefix . '+' . $season . 'x' . $episode_long . $suffix;
  518. push(@urls, $url);
  519. # Season X
  520. if ($NO_QUALITY_CHECKS) {
  521. $url = $prefix . '+Season+' . $season . $suffix;
  522. push(@urls, $url);
  523. }
  524. }
  525. }
  526. }
  527. }
  528. }
  529. my @html_content = ();
  530. my @json_content = ();
  531. foreach my $url (@urls) {
  532. # Fetch the page
  533. my $errCount = 0;
  534. my $content = '';
  535. HTTP_ERR_LOOP: {
  536. my $code = 0;
  537. if ($DEBUG) {
  538. print STDERR 'Searching with URL: ' . $url . "\n";
  539. }
  540. # Fetch
  541. ($content, $code) = fetch($url, 'primary.html');
  542. # Check for useful errors
  543. if ($code == 404) {
  544. if ($DEBUG) {
  545. print STDERR "Skipping content from 404 response\n";
  546. }
  547. next;
  548. }
  549. # Check for less useful errors
  550. if ($code != 200) {
  551. if ($code >= 500 && $code <= 599) {
  552. if ($errCount > $ERR_RETRIES) {
  553. print STDERR 'Unable to fetch URL: ' . $url . "\n";
  554. $errCount = 0;
  555. next;
  556. }
  557. if ($DEBUG) {
  558. print STDERR 'Retrying URL (' . $code . '): ' . $url . "\n";
  559. }
  560. $errCount++;
  561. sleep($ERR_DELAY);
  562. redo HTTP_ERR_LOOP;
  563. } else {
  564. print STDERR 'Error fetching URL (' . $code . '): ' . $url . "\n";
  565. }
  566. next;
  567. }
  568. }
  569. # Save the content, discriminating by data type
  570. if ($DEBUG) {
  571. print STDERR 'Fetched ' . length($content) . " bytes\n";
  572. }
  573. if ($content =~ /^\s*{/) {
  574. my $json = eval { decode_json($content); };
  575. if (defined($json) && ref($json)) {
  576. push(@json_content, $json);
  577. } elsif ($DEBUG) {
  578. print STDERR 'JSON parsing failure on: ' . $content . "\n";
  579. }
  580. } else {
  581. push(@html_content, scalar($content));
  582. }
  583. }
  584. # We need someplace to store parsed torrent data from the various sources
  585. my @tors = ();
  586. # Handle HTML content
  587. foreach my $content (@html_content) {
  588. if ($content =~ /\<title\>The Pirate Bay/i) {
  589. # Find TR elements from TPB
  590. my @trs = splitTags($content, 'TR', 'TH', undef());
  591. foreach my $tr (@trs) {
  592. # Find the show title
  593. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  594. if (!defined($title) || length($title) < 1) {
  595. if ($DEBUG) {
  596. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  597. }
  598. next;
  599. }
  600. $title =~ s/^\s+//;
  601. # Extract the season and episode numbers
  602. my ($fileSeason, $episode) = findSE($title);
  603. # Extract the URL
  604. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  605. if (!defined($url) || length($url) < 1) {
  606. if ($DEBUG) {
  607. print STDERR "Skipping TR with no magnet URL\n";
  608. }
  609. next;
  610. }
  611. $url = decode_entities($url);
  612. # Count the sum of seeders and leachers
  613. my $seeds = 0;
  614. my $leaches = 0;
  615. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  616. $seeds = $1;
  617. $leaches = $2;
  618. }
  619. # Extract the size (from separate column or inline)
  620. my $size = 0;
  621. my $unit = 'M';
  622. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  623. $size = $1;
  624. $unit = $2;
  625. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  626. $size = $1;
  627. $unit = $2;
  628. }
  629. if ($unit eq 'G') {
  630. $size *= 1024;
  631. }
  632. $size = int($size);
  633. if ($DEBUG) {
  634. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  635. }
  636. # Save the extracted data
  637. my %tor = (
  638. 'title' => $title,
  639. 'season' => $fileSeason,
  640. 'episode' => $episode,
  641. 'seeds' => $seeds,
  642. 'leaches' => $leaches,
  643. 'size' => $size,
  644. 'url' => $url,
  645. 'source' => 'TPB'
  646. );
  647. push(@tors, \%tor);
  648. }
  649. } elsif ($content =~ /\<title\>[^\<\>]*\bisoHunt\b[^\<\>]*\<\/title\>/i) {
  650. # Find each TR element from ISOHunt
  651. my @trs = splitTags($content, 'TR', 'TH', undef());
  652. foreach my $tr (@trs) {
  653. # Split each TD element from the row
  654. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  655. if (scalar(@tds) > 10 || scalar(@tds) < 9) {
  656. if ($tds[1] =~ /No results found/) {
  657. next;
  658. }
  659. print STDERR 'Skipping invalid ISO TR: ' . $tr . "\n";
  660. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  661. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  662. }
  663. next;
  664. }
  665. # Skip sponsored results
  666. if ($tds[1] =~ /\bSponsored\b/i) {
  667. if ($DEBUG > 1) {
  668. print STDERR "Skipping sponsored result\n";
  669. }
  670. next;
  671. }
  672. # Find the torrent ID and show title
  673. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+\/[^\"]+)\"\>\<span\>([^\>]+)\<\/span\>/i;
  674. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  675. if ($DEBUG > 1) {
  676. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  677. }
  678. next;
  679. }
  680. $title =~ s/^\s+//;
  681. # Extract the season and episode numbers
  682. my ($fileSeason, $episode) = findSE($title);
  683. # Extract the size
  684. my $size = 0;
  685. my $unit = 'M';
  686. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  687. $size = $1;
  688. $unit = $2;
  689. }
  690. if ($unit eq 'G') {
  691. $size *= 1024;
  692. }
  693. $size = int($size);
  694. # Count the sum of seeders and leachers
  695. my $seeds = 0;
  696. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  697. $seeds = $1;
  698. }
  699. my $leaches = 0;
  700. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  701. $leaches = $1;
  702. }
  703. # Build the detail page URL
  704. my $url = $SOURCES->{'ISO'}->{'protocol'} . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id;
  705. if ($DEBUG) {
  706. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  707. }
  708. # Save the extracted data
  709. my %tor = (
  710. 'title' => $title,
  711. 'season' => $fileSeason,
  712. 'episode' => $episode,
  713. 'seeds' => $seeds,
  714. 'leaches' => $leaches,
  715. 'size' => $size,
  716. 'url' => $url,
  717. 'source' => 'ISO'
  718. );
  719. push(@tors, \%tor);
  720. }
  721. } elsif ($content =~ /Kickass\s*Torrents\<\/title\>/i) {
  722. # Find each TR element from Kickass
  723. my @trs = splitTags($content, 'TR', 'TH', undef());
  724. foreach my $tr (@trs) {
  725. # Split each TD element from the row
  726. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  727. if (scalar(@tds) != 6) {
  728. print STDERR "Invalid KICK TR:\n";
  729. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  730. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  731. }
  732. next;
  733. }
  734. # Skip empty results
  735. if ( $tds[1] =~ /\<h2\>Nothing found\!\<\/h2\>/i
  736. || $tds[1] =~ /\<p\>\<strong\>Page not found\<\/strong\>\<\/p\>/i)
  737. {
  738. if ($DEBUG) {
  739. print STDERR "Skipping empty TD\n";
  740. }
  741. next;
  742. }
  743. # Find the torrent title
  744. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  745. if (!defined($title) || length($title) < 1) {
  746. if ($DEBUG) {
  747. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  748. }
  749. next;
  750. }
  751. $title =~ s/^\s+//;
  752. # Find the torrent URL
  753. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  754. if (!defined($url) || length($url) < 1) {
  755. if ($DEBUG) {
  756. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  757. }
  758. next;
  759. }
  760. $url = decode_entities($url);
  761. # Extract the season and episode numbers
  762. my ($fileSeason, $episode) = findSE($title);
  763. # Extract the size
  764. my $size = 0;
  765. my $unit = 'M';
  766. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  767. $size = $1;
  768. $unit = $2;
  769. }
  770. if ($unit eq 'G') {
  771. $size *= 1024;
  772. }
  773. $size = int($size);
  774. # Count the sum of seeders and leachers
  775. my $seeds = 0;
  776. if ($tds[4] =~ /(\d+)\<\/td\>/i) {
  777. $seeds = $1;
  778. }
  779. my $leaches = 0;
  780. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  781. $leaches = $1;
  782. }
  783. if ($DEBUG) {
  784. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  785. }
  786. # Save the extracted data
  787. my %tor = (
  788. 'title' => $title,
  789. 'season' => $fileSeason,
  790. 'episode' => $episode,
  791. 'seeds' => $seeds,
  792. 'leaches' => $leaches,
  793. 'size' => $size,
  794. 'url' => $url,
  795. 'source' => 'KICK'
  796. );
  797. push(@tors, \%tor);
  798. }
  799. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  800. # We'll need to strip HTML
  801. my $hs = HTML::Strip->new();
  802. # Find each DL element from Torrentz
  803. my @dls = splitTags($content, 'DL', undef(), undef());
  804. foreach my $dl (@dls) {
  805. # Skip ads
  806. if ($dl =~ /\s+rel\=\"nofollow/i) {
  807. next;
  808. }
  809. # Find the torrent title
  810. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  811. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  812. if ($DEBUG) {
  813. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  814. }
  815. next;
  816. }
  817. $hash = lc($hash);
  818. $title = $hs->parse($title);
  819. $hs->eof;
  820. $title =~ s/^\s+//;
  821. # Extract the season and episode numbers
  822. my ($fileSeason, $episode) = findSE($title);
  823. # Extract the size
  824. my $size = 0;
  825. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  826. $size = $1;
  827. if ($2 eq 'G') {
  828. $size *= 1024;
  829. }
  830. $size = int($size);
  831. }
  832. # Count the sum of seeders and leachers
  833. my $seeds = 0;
  834. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  835. $seeds = $1;
  836. }
  837. my $leaches = 0;
  838. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  839. $leaches = $1;
  840. }
  841. # Construct a magnet URL from the hash
  842. # Assume the seconary lookup will append a list of trackers
  843. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  844. if ($DEBUG) {
  845. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  846. }
  847. # Save the extracted data
  848. my %tor = (
  849. 'title' => $title,
  850. 'season' => $fileSeason,
  851. 'episode' => $episode,
  852. 'seeds' => $seeds,
  853. 'leaches' => $leaches,
  854. 'size' => $size,
  855. 'url' => $url,
  856. 'source' => 'Z'
  857. );
  858. push(@tors, \%tor);
  859. }
  860. } elsif ($content =~ /ExtraTorrent\.cc The World\'s Largest BitTorrent System\<\/title\>/i) {
  861. # Find TR elements from ET
  862. my @trs = splitTags($content, 'TR', undef(), 'magnet\:');
  863. foreach my $tr (@trs) {
  864. # Find the show title
  865. my ($title) = $tr =~ /title\=\"Download\s+([^\"]*)\s+torrent\"/i;
  866. if (!defined($title) || length($title) < 1) {
  867. if ($DEBUG) {
  868. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  869. }
  870. next;
  871. }
  872. $title =~ s/^\s+//;
  873. # Find the magnet URL
  874. my ($url) = $tr =~ /\<a\s+href=\"(magnet\:[^\"]+)\"/i;
  875. if (!defined($url) || length($url) < 1) {
  876. if ($DEBUG) {
  877. print STDERR "Skipping TR with no magnet URL\n";
  878. }
  879. next;
  880. }
  881. $url = decode_entities($url);
  882. # Extract the season and episode numbers
  883. my ($fileSeason, $episode) = findSE($title);
  884. # Count the sum of seeders and leachers
  885. my $seeds = 0;
  886. my $leaches = 0;
  887. if ($tr =~ /\<td\s+class=\"sy\">(\d+)\<\/td\>/) {
  888. $seeds = $1;
  889. }
  890. if ($tr =~ /\<td\s+class=\"ly\">(\d+)\<\/td\>/) {
  891. $leaches = $1;
  892. }
  893. # Extract the size (from separate column or inline)
  894. my $size = 0;
  895. my $unit = 'M';
  896. if ($tr =~ /\<td\>(\d+(?:\.\d+)?)\&nbsp\;(G|M)B\<\/td\>/) {
  897. $size = $1;
  898. $unit = $2;
  899. }
  900. if ($unit eq 'G') {
  901. $size *= 1024;
  902. }
  903. $size = int($size);
  904. if ($DEBUG) {
  905. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  906. }
  907. # Save the extracted data
  908. my %tor = (
  909. 'title' => $title,
  910. 'season' => $fileSeason,
  911. 'episode' => $episode,
  912. 'seeds' => $seeds,
  913. 'leaches' => $leaches,
  914. 'size' => $size,
  915. 'url' => $url,
  916. 'source' => 'ET'
  917. );
  918. push(@tors, \%tor);
  919. }
  920. } elsif ($content =~ /\<title\>Sorry/) {
  921. if ($DEBUG) {
  922. print STDERR "ISO offline\n";
  923. }
  924. } elsif ($content =~ /Database\s+maintenance/i) {
  925. if ($DEBUG) {
  926. print STDERR "TPB offline\n";
  927. }
  928. } elsif ($content =~ /^\s*$/) {
  929. if ($DEBUG) {
  930. print STDERR "Source returned no content\n";
  931. }
  932. } else {
  933. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  934. }
  935. }
  936. # Handle JSON content
  937. foreach my $content (@json_content) {
  938. if (exists($content->{'title'}) && $content->{'title'} =~ /NZBCat/i) {
  939. my $list = $content->{'item'};
  940. if (!$list || ref($list) ne 'ARRAY') {
  941. warn("Invalid NCAT list\n");
  942. next;
  943. }
  944. foreach my $item (@{$list}) {
  945. # Ensure the record is sensible
  946. my $id = undef();
  947. if ( ref($item) eq 'HASH'
  948. && exists($item->{'guid'})
  949. && ref($item->{'guid'}) eq 'HASH'
  950. && exists($item->{'guid'}->{'text'}))
  951. {
  952. $id = $item->{'guid'}->{'text'};
  953. }
  954. if (!$id) {
  955. warn("Unable to parse NCAT list item\n");
  956. next;
  957. }
  958. # NZB URL
  959. my $url = undef();
  960. if (exists($item->{'link'}) && $item->{'link'}) {
  961. $url = $item->{'link'};
  962. $url =~ s/^(https?)\:/${PROTOCOL}\:/;
  963. }
  964. # Title
  965. my $title = undef();
  966. if (exists($item->{'title'}) && $item->{'title'}) {
  967. $title = $item->{'title'};
  968. } elsif (exists($item->{'description'}) && $item->{'description'}) {
  969. $title = $item->{'description'};
  970. }
  971. if ($title) {
  972. $url .= '#' . $title;
  973. }
  974. # Extract the season and episode numbers
  975. my ($season, $episode) = findSE($title);
  976. # Size
  977. my $size = 0;
  978. if (exists($item->{'newznab:attr'}) && $item->{'newznab:attr'} && ref($item->{'newznab:attr'}) eq 'ARRAY') {
  979. foreach my $hash (@{ $item->{'newznab:attr'} }) {
  980. if (ref($hash) eq 'HASH' && exists($hash->{'_name'}) && exists($hash->{'_value'}) && $hash->{'_name'} eq 'size')
  981. {
  982. $size = int($hash->{'_value'}) / 1024;
  983. }
  984. }
  985. }
  986. # Date
  987. my $date = undef();
  988. if (exists($item->{'pubDate'}) && $item->{'pubDate'}) {
  989. $date = str2time($item->{'pubDate'});
  990. }
  991. # Sanity checks
  992. if (!$url) {
  993. warn('No URL in NCAT item: ' . $id . "\n");
  994. next;
  995. }
  996. if (!$title) {
  997. warn('No title in NCAT item: ' . $id . "\n");
  998. next;
  999. }
  1000. if (!$size) {
  1001. warn('No size in NCAT item: ' . $id . "\n");
  1002. next;
  1003. }
  1004. if ($DEBUG) {
  1005. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  1006. }
  1007. # Save the extracted data
  1008. my %tor = (
  1009. 'title' => $title,
  1010. 'season' => $season,
  1011. 'episode' => $episode,
  1012. 'date' => $date,
  1013. 'size' => $size,
  1014. 'url' => $url,
  1015. 'source' => 'NCAT'
  1016. );
  1017. push(@tors, \%tor);
  1018. }
  1019. } else {
  1020. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  1021. }
  1022. }
  1023. # Filter for size/count/etc.
  1024. my %tors = ();
  1025. my $showRegex = undef();
  1026. {
  1027. my $showClean = $show;
  1028. $showClean =~ s/[\"\']//g;
  1029. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  1030. $showRegex = qr/^${showClean}[\W_]/i;
  1031. }
  1032. foreach my $tor (@tors) {
  1033. # Extract the BTIH, if available
  1034. getHash($tor);
  1035. # Skip files that are in the torrent excludes list
  1036. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  1037. if ($DEBUG) {
  1038. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1039. }
  1040. next;
  1041. }
  1042. # Skip files that don't start with our show title
  1043. if (!($tor->{'title'} =~ $showRegex)) {
  1044. if ($DEBUG) {
  1045. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  1046. }
  1047. next;
  1048. # Skip pre-air files
  1049. } elsif ($tor->{'title'} =~ /preair/i) {
  1050. if ($DEBUG) {
  1051. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  1052. }
  1053. next;
  1054. # Skip SWESUB files
  1055. } elsif ($tor->{'title'} =~ /swesub/i) {
  1056. if ($DEBUG) {
  1057. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  1058. }
  1059. next;
  1060. # Skip .rus. files
  1061. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  1062. if ($DEBUG) {
  1063. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  1064. }
  1065. next;
  1066. # Skip German files
  1067. } elsif ($tor->{'title'} =~ /german/i) {
  1068. if ($DEBUG) {
  1069. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  1070. }
  1071. next;
  1072. # Skip French files
  1073. } elsif ($tor->{'title'} =~ /french/i) {
  1074. if ($DEBUG) {
  1075. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  1076. }
  1077. next;
  1078. # Skip Spanish files
  1079. } elsif ($tor->{'title'} =~ /Español/i) {
  1080. if ($DEBUG) {
  1081. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  1082. }
  1083. next;
  1084. # Skip Castellano files
  1085. } elsif ($tor->{'title'} =~ /Castellano/i) {
  1086. if ($DEBUG) {
  1087. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  1088. }
  1089. next;
  1090. # Skip unedited files
  1091. } elsif ($tor->{'title'} =~ /unedited/i) {
  1092. if ($DEBUG) {
  1093. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  1094. }
  1095. next;
  1096. }
  1097. # Skip files that contain a word from the series exclude list
  1098. my $exclude = undef();
  1099. foreach my $ex (keys(%TITLE_EXCLUDES)) {
  1100. $ex = quotemeta($ex);
  1101. if ($tor->{'title'} =~ m/${ex}/i) {
  1102. $exclude = $ex;
  1103. last;
  1104. }
  1105. }
  1106. if (defined($exclude)) {
  1107. if ($DEBUG) {
  1108. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  1109. }
  1110. next;
  1111. }
  1112. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  1113. if (!$CUSTOM_SEARCH) {
  1114. # Skip files that don't contain the right season number
  1115. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  1116. if ($DEBUG) {
  1117. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  1118. }
  1119. next;
  1120. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  1121. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} })
  1122. || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS))
  1123. {
  1124. if ($DEBUG) {
  1125. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  1126. }
  1127. next;
  1128. }
  1129. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  1130. # Skip files that don't match the regex
  1131. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  1132. if ($DEBUG) {
  1133. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  1134. }
  1135. next;
  1136. }
  1137. }
  1138. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  1139. if (!$NO_QUALITY_CHECKS) {
  1140. # Proxy publication date to seeder/leacher quality
  1141. if ($tor->{'date'} && !$tor->{'seeds'}) {
  1142. if ($tor->{'date'} > time() - $QUALITY_AGE) {
  1143. $tor->{'seeds'} = $SEED_RATIO_COUNT + 1;
  1144. } else {
  1145. $tor->{'seeds'} = ($MIN_COUNT / 2) - 1;
  1146. }
  1147. $tor->{'leaches'} = $tor->{'seeds'};
  1148. }
  1149. # Skip torrents with too few seeders/leachers
  1150. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  1151. if ($DEBUG) {
  1152. print STDERR 'Skipping file: Insufficient seeder/leacher count ('
  1153. . $tor->{'seeds'} . '/'
  1154. . $tor->{'leaches'} . '): '
  1155. . $tor->{'title'} . "\n";
  1156. }
  1157. next;
  1158. # Skip torrents with unusual seed/leach ratios
  1159. } elsif ($tor->{'seeds'} > 1
  1160. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  1161. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  1162. {
  1163. if ($DEBUG) {
  1164. print STDERR 'Skipping file: Unusual seeder/leacher ratio ('
  1165. . $tor->{'seeds'} . '/'
  1166. . $tor->{'leaches'} . '): '
  1167. . $tor->{'title'} . "\n";
  1168. }
  1169. next;
  1170. # Skip torrents that are too small
  1171. } elsif ($tor->{'size'} < $MIN_SIZE) {
  1172. if ($DEBUG) {
  1173. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1174. }
  1175. next;
  1176. }
  1177. }
  1178. # Save good torrents
  1179. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  1180. if ($DEBUG) {
  1181. print STDERR 'Possible URL ('
  1182. . $tor->{'seeds'} . '/'
  1183. . $tor->{'leaches'}
  1184. . ' seeds/leaches, '
  1185. . $tor->{'size'}
  1186. . ' MiB): '
  1187. . $tor->{'title'} . "\n";
  1188. }
  1189. }
  1190. # Find the average torrent size for each episode
  1191. my %size = ();
  1192. {
  1193. my %max = ();
  1194. my %avg = ();
  1195. foreach my $episode (keys(%tors)) {
  1196. my $count = 0;
  1197. $avg{$episode} = 0.001;
  1198. $max{$episode} = 0.001;
  1199. foreach my $tor (@{ $tors{$episode} }) {
  1200. $count++;
  1201. $avg{$episode} += $tor->{'size'};
  1202. if ($tor->{'size'} > $max{$episode}) {
  1203. $max{$episode} = $tor->{'size'};
  1204. }
  1205. }
  1206. if ($count > 0) {
  1207. $avg{$episode} /= $count;
  1208. }
  1209. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1210. if ($DEBUG) {
  1211. print STDERR 'Episode '
  1212. . $episode
  1213. . ' max/avg/cmp size: '
  1214. . int($max{$episode}) . '/'
  1215. . int($avg{$episode}) . '/'
  1216. . int($size{$episode})
  1217. . " MiB\n";
  1218. }
  1219. }
  1220. }
  1221. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1222. foreach my $episode (keys(%tors)) {
  1223. foreach my $tor (@{ $tors{$episode} }) {
  1224. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1225. # Start with the peer count
  1226. $tor->{'adj_count'} = $count;
  1227. # Adjust based on file size
  1228. {
  1229. my $size_ratio = $tor->{'size'} / $size{$episode};
  1230. if ($tor->{'size'} >= $size{$episode}) {
  1231. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  1232. } else {
  1233. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  1234. }
  1235. }
  1236. # Adjust based on title contents
  1237. if ($tor->{'title'} =~ /Subtitulado/i) {
  1238. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  1239. }
  1240. # Truncate to an integer
  1241. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1242. if ($DEBUG) {
  1243. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1244. }
  1245. }
  1246. }
  1247. # Pick the best-adjusted-count torrent for each episode
  1248. my %urls = ();
  1249. foreach my $episode (keys(%tors)) {
  1250. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  1251. my $max = undef();
  1252. foreach my $tor (@sorted) {
  1253. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1254. if ($urls{$episode} = resolveSecondary($tor)) {
  1255. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1256. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1257. next;
  1258. }
  1259. $max = $tor->{'adj_count'};
  1260. }
  1261. if ($DEBUG) {
  1262. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1263. }
  1264. } elsif ($DEBUG) {
  1265. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1266. }
  1267. }
  1268. }
  1269. # Output
  1270. foreach my $episode (keys(%tors)) {
  1271. if (defined($urls{$episode})) {
  1272. $urls{$episode} = resolveTrackers($urls{$episode});
  1273. print $urls{$episode} . "\n";
  1274. if ($SYSLOG) {
  1275. syslog(LOG_NOTICE, $show . ': ' . getHash($urls{$episode}));
  1276. }
  1277. if ($DEBUG) {
  1278. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1279. }
  1280. } elsif ($DEBUG) {
  1281. print STDERR 'No URL for: ' . $episode . "\n";
  1282. }
  1283. }
  1284. # Cleanup
  1285. if ($COOKIES) {
  1286. unlink($COOKIES);
  1287. }
  1288. if ($SCRIPT) {
  1289. unlink($SCRIPT);
  1290. }
  1291. if ($SYSLOG) {
  1292. closelog();
  1293. }
  1294. exit(0);
  1295. sub getHash($) {
  1296. my ($tor) = @_;
  1297. my $url;
  1298. # Allow either a URL or a tor hashref
  1299. if (ref($tor) eq 'HASH') {
  1300. $url = $tor->{'url'};
  1301. } else {
  1302. $url = $tor;
  1303. undef($tor);
  1304. }
  1305. # Extract the BTIH hash or NZB ID, if available
  1306. my $hash = undef();
  1307. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1308. $hash = lc($1);
  1309. } elsif ($url =~ /\/getnzb\/(\w+)\.nzb\&/i) {
  1310. $hash = lc($1);
  1311. }
  1312. # Save back to the tor, if provided
  1313. if (defined($tor) && defined($hash)) {
  1314. $tor->{'hash'} = lc($hash);
  1315. }
  1316. # Always return the hash, or undef() if none can be found
  1317. return $hash;
  1318. }
  1319. # Resolve secondary URLs
  1320. sub resolveSecondary($) {
  1321. my ($tor) = @_;
  1322. # Fetch the torrent-specific page and extract the magent link
  1323. if ($tor->{'source'} eq 'ISO') {
  1324. my ($content, $code) = fetch($tor->{'url'}, 'secondary.html');
  1325. if ($code != 200) {
  1326. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1327. goto OUT;
  1328. }
  1329. my ($magnet) = $content =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1330. if (!defined($magnet) || length($magnet) < 1) {
  1331. if ($DEBUG) {
  1332. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1333. }
  1334. goto OUT;
  1335. }
  1336. $tor->{'url'} = decode_entities($magnet);
  1337. }
  1338. # Extract the hash
  1339. getHash($tor);
  1340. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1341. if ($DEBUG) {
  1342. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1343. }
  1344. goto OUT;
  1345. }
  1346. OUT:
  1347. return $tor->{'url'};
  1348. }
  1349. sub resolveTrackers($) {
  1350. my ($url) = @_;
  1351. # Always append a few static trackers to the URI
  1352. if ($url =~ /^magnet\:/i) {
  1353. foreach my $tracker (@TRACKERS) {
  1354. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1355. my $match = quotemeta($arg);
  1356. if (!($url =~ /${match}/)) {
  1357. $url .= $arg;
  1358. }
  1359. }
  1360. }
  1361. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1362. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1363. my $hash = lc($1);
  1364. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1365. my $hashURL = $baseURL . '/' . $hash;
  1366. my ($content, $code) = fetch($hashURL, 'hashinfo.html');
  1367. if ($code != 200) {
  1368. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1369. return $url;
  1370. }
  1371. # Parse out and fetch the tracker list URL
  1372. my ($list) = $content =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1373. if (!defined($list)) {
  1374. if ($DEBUG) {
  1375. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1376. }
  1377. return $url;
  1378. }
  1379. my $listURL = $baseURL . $list;
  1380. ($content, $code) = fetch($listURL, 'tracker.html');
  1381. if ($code != 200) {
  1382. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1383. return $url;
  1384. }
  1385. # Parse the tracker list and append our URL
  1386. foreach my $line ($content) {
  1387. if ($line =~ /^\s*$/) {
  1388. next;
  1389. }
  1390. $line =~ s/^\s+//;
  1391. $line =~ s/\s+$//;
  1392. if ($line =~ /^(?:http|udp)\:/i) {
  1393. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1394. my $match = quotemeta($arg);
  1395. if (!($url =~ /${match}/)) {
  1396. if ($DEBUG) {
  1397. print STDERR 'Adding tracker: ' . $line . "\n";
  1398. }
  1399. $url .= $arg;
  1400. }
  1401. } else {
  1402. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1403. }
  1404. }
  1405. }
  1406. return $url;
  1407. }
  1408. sub splitTags($$$$) {
  1409. my ($content, $tag, $header, $match) = @_;
  1410. # Find each tag element
  1411. my @out = ();
  1412. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1413. foreach my $part (@parts) {
  1414. # Trim trailing tags and skip things that aren't complete tags
  1415. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1416. if ($DEBUG > 1) {
  1417. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1418. }
  1419. next;
  1420. }
  1421. # Skip headers
  1422. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1423. if ($DEBUG > 2) {
  1424. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1425. }
  1426. next;
  1427. }
  1428. # Skip non-matches
  1429. if (defined($match) && !($part =~ m/${match}/i)) {
  1430. if ($DEBUG > 2) {
  1431. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1432. }
  1433. next;
  1434. }
  1435. # Save good tags
  1436. push(@out, $part);
  1437. }
  1438. return @out;
  1439. }
  1440. # Extract season
  1441. sub findSE($) {
  1442. my ($name) = @_;
  1443. my $season = 0;
  1444. my $episode = 0;
  1445. my $seasonBlock = '';
  1446. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1447. $seasonBlock = $1;
  1448. my ($month, $day);
  1449. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1450. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1451. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1452. $seasonBlock = $1;
  1453. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1454. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1455. $seasonBlock = $1;
  1456. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1457. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1458. $seasonBlock = $1;
  1459. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1460. }
  1461. # Return something valid and INTy or UNDEF
  1462. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1463. if ($DEBUG) {
  1464. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1465. }
  1466. $season = undef();
  1467. $episode = undef();
  1468. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1469. # Episode-by-date
  1470. $season = int($season);
  1471. } else {
  1472. # Catchall
  1473. # This will warn and return undef() (which is valid) on error
  1474. $season = int($season);
  1475. $episode = int($episode);
  1476. }
  1477. return ($season, $episode);
  1478. }
  1479. sub initSources() {
  1480. my %sources = ();
  1481. # NZB Cat
  1482. if ($ENABLE_SOURCE{'NCAT'}) {
  1483. my @proxies = ('nzb.cat/api');
  1484. my $source = findProxy(\@proxies, '\bforgottenpassword\b');
  1485. if ($source && exists($CONFIG{'NCAT_APIKEY'}) && $CONFIG{'NCAT_APIKEY'}) {
  1486. $source->{'weight'} = 1.00;
  1487. $source->{'quote'} = 0;
  1488. $source->{'search_exclude'} = 0;
  1489. $source->{'search_suffix'} = '';
  1490. $source->{'custom_search'} = sub ($$$$) {
  1491. my ($urls, $series, $season, $episode) = @_;
  1492. my $url =
  1493. $source->{'search_url'}
  1494. . '?o=json&t=tvsearch&q='
  1495. . $series
  1496. . '&season='
  1497. . $season . '&ep='
  1498. . $episode
  1499. . '&apikey='
  1500. . $CONFIG{'NCAT_APIKEY'};
  1501. push(@{$urls}, $url);
  1502. };
  1503. $sources{'NCAT'} = $source;
  1504. }
  1505. }
  1506. # The Pirate Bay
  1507. if ($ENABLE_SOURCE{'TPB'}) {
  1508. my @proxies = ('thepiratebay.org/search/', 'tpb.unblocked.co/search/');
  1509. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1510. if ($source) {
  1511. $source->{'weight'} = 1.00;
  1512. $source->{'quote'} = 0;
  1513. $source->{'search_exclude'} = 1;
  1514. $source->{'search_suffix'} = '/0/7/0';
  1515. $sources{'TPB'} = $source;
  1516. }
  1517. }
  1518. # ISOhunt
  1519. if ($ENABLE_SOURCE{'ISO'}) {
  1520. my @proxies = ('isohunt.to/torrents/?ihq=', 'isohunters.net/torrents/?ihq=');
  1521. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1522. if ($source) {
  1523. $source->{'weight'} = 0.75;
  1524. $source->{'quote'} = 1;
  1525. $source->{'search_exclude'} = 1;
  1526. $source->{'search_suffix'} = '';
  1527. $sources{'ISO'} = $source;
  1528. }
  1529. }
  1530. # Kickass
  1531. if ($ENABLE_SOURCE{'KICK'}) {
  1532. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1533. my $source = findProxy(\@proxies, '/search.php');
  1534. if ($source) {
  1535. $source->{'weight'} = 1.00;
  1536. $source->{'quote'} = 1;
  1537. $source->{'search_exclude'} = 1;
  1538. $source->{'search_suffix'} = '/';
  1539. $sources{'KICK'} = $source;
  1540. }
  1541. }
  1542. # Torrentz
  1543. if ($ENABLE_SOURCE{'Z'}) {
  1544. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1545. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1546. if ($source) {
  1547. $source->{'weight'} = 1.00;
  1548. $source->{'quote'} = 1;
  1549. $source->{'search_exclude'} = 1;
  1550. $source->{'search_suffix'} = '';
  1551. if (!$NO_QUALITY_CHECKS) {
  1552. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1553. }
  1554. $sources{'Z'} = $source;
  1555. }
  1556. }
  1557. # ExtraTorrent
  1558. if ($ENABLE_SOURCE{'ET'}) {
  1559. my @proxies = (
  1560. 'extra.to/search/?search=', 'etmirror.com/search/?search=',
  1561. 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search='
  1562. );
  1563. my $source = findProxy(\@proxies, '/search/');
  1564. if ($source) {
  1565. $source->{'weight'} = 1.00;
  1566. $source->{'quote'} = 1;
  1567. $source->{'search_exclude'} = 0;
  1568. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1569. $source->{'search_url'} = 'phantomjs:' . $source->{'search_url'};
  1570. $sources{'ET'} = $source;
  1571. }
  1572. }
  1573. # Sanity check
  1574. if (scalar(keys(%sources)) < 1) {
  1575. die("No sources available\n");
  1576. }
  1577. return \%sources;
  1578. }
  1579. sub findProxy($$) {
  1580. my ($proxies, $match) = @_;
  1581. # Automatically select a proxy
  1582. my $host = '';
  1583. my $protocol = '';
  1584. my $search_url = '';
  1585. foreach my $url (@{$proxies}) {
  1586. my $path;
  1587. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1588. if (!$protocol) {
  1589. $protocol = $PROTOCOL;
  1590. }
  1591. if (!$host) {
  1592. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1593. next;
  1594. }
  1595. my ($content, $code) = fetch($protocol . '://' . $host, undef(), 1);
  1596. if ($code == 200 && $content =~ m/${match}/i) {
  1597. $search_url = $protocol . '://' . $host . $path;
  1598. last;
  1599. } elsif ($DEBUG) {
  1600. print STDERR 'Proxy not available: ' . $host . "\n";
  1601. if ($DEBUG > 1) {
  1602. print STDERR $content . "\n";
  1603. }
  1604. }
  1605. }
  1606. # Return the search data if at least one proxy is up
  1607. if ($search_url) {
  1608. my %tmp = (
  1609. 'protocol' => $protocol,
  1610. 'host' => $host,
  1611. 'search_url' => $search_url,
  1612. );
  1613. return \%tmp;
  1614. }
  1615. # Return undef if we didn't find any working proxies
  1616. return undef();
  1617. }
  1618. sub fetch($;$$) {
  1619. my ($url, $file, $nocheck) = @_;
  1620. if ($DEBUG) {
  1621. print STDERR 'Fetch: ' . $url . "\n";
  1622. }
  1623. # Allow usage with short names
  1624. if ($file && !($file =~ /^\//)) {
  1625. $file = '/tmp/findTorrent-' . $file;
  1626. }
  1627. # Random delay
  1628. if ($DEBUG > 1) {
  1629. sleep($SLEEP * 0.25);
  1630. } else {
  1631. sleep($DELAY * (rand($SLEEP) + ($SLEEP / 2)));
  1632. }
  1633. # Allow JS processing
  1634. if ($url =~ /^phantomjs\:\s*(\S.*)$/i) {
  1635. return phantomFetch($1, $file);
  1636. }
  1637. # Fetch object
  1638. if (!$FETCH) {
  1639. if (!$COOKIES) {
  1640. $COOKIES = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  1641. }
  1642. $FETCH = Fetch->new(
  1643. 'cookiefile' => $COOKIES,
  1644. 'timeout' => $TIMEOUT,
  1645. 'uas' => $UA
  1646. );
  1647. }
  1648. # Debug as requested
  1649. if ($DEBUG > 1 && $file) {
  1650. $FETCH->file($file);
  1651. } else {
  1652. $FETCH->file('');
  1653. }
  1654. # Standard fetch
  1655. $FETCH->url($url);
  1656. if ($nocheck) {
  1657. $FETCH->fetch('nocheck' => 1);
  1658. } else {
  1659. $FETCH->fetch();
  1660. }
  1661. return (scalar($FETCH->content()), $FETCH->status_code());
  1662. }
  1663. sub phantomFetch($$) {
  1664. my ($url, $file) = @_;
  1665. # Init
  1666. if (!$SCRIPT) {
  1667. $SCRIPT = mktemp('/tmp/findTorrent.phantom.XXXXXXXX');
  1668. open(my $fh, '>', $SCRIPT)
  1669. or die('Unable to open PhantomJS script file: ' . $! . "\n");
  1670. print $fh $PHANTOM_CONFIG;
  1671. close($fh);
  1672. }
  1673. # Capture STDOUT, drop STDERR
  1674. my @cmd = ($PHANTOM, $SCRIPT, $url);
  1675. my ($content, undef(), undef()) = capture { system(@cmd); };
  1676. # Debug as requested
  1677. if ($DEBUG > 1 && $file) {
  1678. open(my $fh, '>', $file)
  1679. or warn('Unable to open phantom debug file: ' . $! . "\n");
  1680. if ($fh) {
  1681. print $fh $content;
  1682. close($fh);
  1683. }
  1684. }
  1685. # Try to get the response status code, fake one if we cannot
  1686. my ($code) = $content =~ /^(\d\d\d)$/m;
  1687. if (!defined($code)) {
  1688. warn("Unable to retrive HTTP status code. Faking success...\n");
  1689. $code = 200;
  1690. }
  1691. return ($content, $code);
  1692. }