findTorrent.pl 61 KB

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