findTorrent.pl 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355
  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'} . '?t=get&id=' . $id . '&apikey=' . $CONFIG->{'IS_APIKEY'};
  1192. }
  1193. # Title
  1194. my $title = undef();
  1195. if (exists($item->{'searchname'}) && $item->{'searchname'}) {
  1196. $title = $item->{'searchname'};
  1197. } elsif (exists($item->{'name'}) && $item->{'name'}) {
  1198. $title = $item->{'name'};
  1199. } elsif (exists($item->{'title'}) && $item->{'title'}) {
  1200. $title = $item->{'title'};
  1201. } elsif (exists($item->{'description'}) && $item->{'description'}) {
  1202. $title = $item->{'description'};
  1203. }
  1204. if ($title) {
  1205. my $title_clean = $title;
  1206. $title_clean =~ s/[\/\(\)]/_/g;
  1207. $url .= '#' . uri_encode($title_clean);
  1208. }
  1209. # Extract the season and episode numbers
  1210. my ($season, $episode) = findSE($title);
  1211. # Size
  1212. my $size = 0;
  1213. if (exists($item->{'newznab:attr'}) && $item->{'newznab:attr'} && ref($item->{'newznab:attr'}) eq 'ARRAY') {
  1214. foreach my $hash (@{ $item->{'newznab:attr'} }) {
  1215. if (ref($hash) eq 'HASH' && exists($hash->{'_name'}) && exists($hash->{'_value'}) && $hash->{'_name'} eq 'size') {
  1216. $size = int($hash->{'_value'} / 1024 / 1024);
  1217. last;
  1218. }
  1219. }
  1220. } elsif (exists($item->{'attr'}) && $item->{'attr'} && ref($item->{'attr'}) eq 'ARRAY') {
  1221. foreach my $hash (@{ $item->{'attr'} }) {
  1222. if (!exists($hash->{'@attributes'}) || ref($hash->{'@attributes'}) ne 'HASH') {
  1223. next;
  1224. }
  1225. $hash = $hash->{'@attributes'};
  1226. if (exists($hash->{'name'}) && $hash->{'name'} eq 'size' && exists($hash->{'value'})) {
  1227. $size = int($hash->{'value'} / 1024 / 1024);
  1228. last;
  1229. }
  1230. }
  1231. } elsif (exists($item->{'size'})) {
  1232. $size = int($item->{'size'} / 1024 / 1024);
  1233. }
  1234. # Date
  1235. my $date = undef();
  1236. if (exists($item->{'pubDate'}) && $item->{'pubDate'}) {
  1237. $date = str2time($item->{'pubDate'});
  1238. } elsif (exists($item->{'postdate'}) && $item->{'postdate'}) {
  1239. $date = str2time($item->{'postdate'});
  1240. }
  1241. # Sanity checks
  1242. if (!$url) {
  1243. warn('No URL in NZB item: ' . $id . "\n");
  1244. return undef();
  1245. }
  1246. if (!$title) {
  1247. warn('No title in NZB item: ' . $id . "\n");
  1248. return undef();
  1249. }
  1250. if (!$size) {
  1251. warn('No size in NZB item: ' . $id . "\n");
  1252. return undef();
  1253. }
  1254. if ($DEBUG) {
  1255. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  1256. }
  1257. # Save the extracted data
  1258. my %tor = (
  1259. 'title' => $title,
  1260. 'season' => $season,
  1261. 'episode' => $episode,
  1262. 'date' => $date,
  1263. 'size' => $size,
  1264. 'url' => $url,
  1265. );
  1266. return \%tor;
  1267. }
  1268. sub badTor($) {
  1269. my ($tor) = @_;
  1270. # Pre-calculate the regex
  1271. if (!$SERIES->{'name_regex'}) {
  1272. my $clean = $SERIES->{'name'};
  1273. $clean =~ s/[\"\']//g;
  1274. $clean =~ s/[\W_]+/\[\\W_\].*/g;
  1275. $SERIES->{'name_regex'} = qr/^${clean}[\W_]/i;
  1276. }
  1277. # Skip files that are in the torrent excludes list
  1278. if ($tor->{'hash'} && $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1279. if ($DEBUG) {
  1280. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1281. }
  1282. return 1;
  1283. }
  1284. # Skip files that don't start with our show title
  1285. if (!($tor->{'title'} =~ $SERIES->{'name_regex'})) {
  1286. if ($DEBUG) {
  1287. print STDERR 'Skipping file: Title does not match (' . $SERIES->{'name_regex'} . '): ' . $tor->{'title'} . "\n";
  1288. }
  1289. return 1;
  1290. # Skip leaked files
  1291. } elsif ($tor->{'title'} =~ /leaked/i) {
  1292. if ($DEBUG) {
  1293. print STDERR 'Skipping file: Title contains "leaked": ' . $tor->{'title'} . "\n";
  1294. }
  1295. return 1;
  1296. # Skip pre-air files
  1297. } elsif ($tor->{'title'} =~ /preair/i) {
  1298. if ($DEBUG) {
  1299. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  1300. }
  1301. return 1;
  1302. # Skip SWESUB files
  1303. } elsif ($tor->{'title'} =~ /swesub/i) {
  1304. if ($DEBUG) {
  1305. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  1306. }
  1307. return 1;
  1308. # Skip .rus. files
  1309. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  1310. if ($DEBUG) {
  1311. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  1312. }
  1313. return 1;
  1314. # Skip German files
  1315. } elsif ($tor->{'title'} =~ /german/i) {
  1316. if ($DEBUG) {
  1317. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  1318. }
  1319. return 1;
  1320. # Skip French files
  1321. } elsif ($tor->{'title'} =~ /french/i) {
  1322. if ($DEBUG) {
  1323. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  1324. }
  1325. return 1;
  1326. # Skip Spanish files
  1327. } elsif ($tor->{'title'} =~ /Español/i) {
  1328. if ($DEBUG) {
  1329. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  1330. }
  1331. return 1;
  1332. # Skip Castellano files
  1333. } elsif ($tor->{'title'} =~ /Castellano/i) {
  1334. if ($DEBUG) {
  1335. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  1336. }
  1337. return 1;
  1338. # Skip unedited files
  1339. } elsif ($tor->{'title'} =~ /unedited/i) {
  1340. if ($DEBUG) {
  1341. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  1342. }
  1343. return 1;
  1344. }
  1345. # If we're still around the TOR is good
  1346. return 0;
  1347. }
  1348. sub seedCleanup($) {
  1349. my ($tor) = @_;
  1350. # Cap seeds/leaches/date and ensure they are always defined
  1351. if (!exists($tor->{'seeds'}) || !$tor->{'seeds'}) {
  1352. $tor->{'seeds'} = 0;
  1353. }
  1354. if ($tor->{'seeds'} > $CONFIG->{'MAX_SEEDS'}) {
  1355. $tor->{'seeds'} = $CONFIG->{'MAX_SEEDS'};
  1356. }
  1357. if (!exists($tor->{'leaches'}) || !$tor->{'leaches'}) {
  1358. $tor->{'leaches'} = 0;
  1359. }
  1360. if ($tor->{'leaches'} > $CONFIG->{'MAX_SEEDS'}) {
  1361. $tor->{'leaches'} = $CONFIG->{'MAX_SEEDS'};
  1362. }
  1363. # Proxy publication date to seeder/leacher quality
  1364. if ($tor->{'date'} && !$tor->{'seeds'}) {
  1365. my $age = time() - $tor->{'date'};
  1366. if ($age < -$DAY_IN_SECS) {
  1367. warn('Invalid date (' . $tor->{'date'} . '): ' . $tor->{'title'} . "\n");
  1368. $age = 0;
  1369. }
  1370. $age /= $DAY_IN_SECS;
  1371. if ($age > $CONFIG->{'NZB_AGE_GOOD'}) {
  1372. $tor->{'seeds'} = $CONFIG->{'MIN_COUNT'};
  1373. if ($age > $CONFIG->{'NZB_AGE_MAX'}) {
  1374. $tor->{'seeds'} = ($CONFIG->{'MIN_COUNT'} / 2) - 1;
  1375. }
  1376. } else {
  1377. my $penalty = ($CONFIG->{'MAX_SEEDS'} / 2) / $CONFIG->{'NZB_AGE_GOOD'};
  1378. $tor->{'seeds'} = $CONFIG->{'MAX_SEEDS'} - ($age * $penalty);
  1379. }
  1380. $tor->{'seeds'} = int($tor->{'seeds'});
  1381. $tor->{'leaches'} = $tor->{'seeds'};
  1382. }
  1383. }
  1384. sub lowQualityTor($) {
  1385. my ($tor) = @_;
  1386. # Skip torrents with too few seeders/leachers
  1387. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $CONFIG->{'MIN_COUNT'}) {
  1388. if ($DEBUG) {
  1389. print STDERR 'Skipping file: Insufficient seeder/leacher count ('
  1390. . $tor->{'seeds'} . '/'
  1391. . $tor->{'leaches'} . '): '
  1392. . $tor->{'title'} . "\n";
  1393. }
  1394. return 1;
  1395. # Skip torrents with unusual seed/leach ratios
  1396. } elsif ($tor->{'seeds'} > 1
  1397. && $tor->{'seeds'} < $CONFIG->{'SEED_RATIO_COUNT'}
  1398. && $tor->{'seeds'} > $tor->{'leaches'} * $CONFIG->{'MAX_SEED_RATIO'})
  1399. {
  1400. if ($DEBUG) {
  1401. print STDERR 'Skipping file: Unusual seeder/leacher ratio ('
  1402. . $tor->{'seeds'} . '/'
  1403. . $tor->{'leaches'} . '): '
  1404. . $tor->{'title'} . "\n";
  1405. }
  1406. return 1;
  1407. # Skip torrents that are too small
  1408. } elsif ($tor->{'size'} < $CONFIG->{'MIN_SIZE'}) {
  1409. if ($DEBUG) {
  1410. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1411. }
  1412. return 1;
  1413. }
  1414. # If we're still around the TOR is good
  1415. return 0;
  1416. }
  1417. sub getHash($) {
  1418. my ($tor) = @_;
  1419. my $url;
  1420. # Allow either a URL or a tor hashref
  1421. if (ref($tor) eq 'HASH') {
  1422. if ($tor->{'hash'}) {
  1423. return $tor->{'hash'};
  1424. }
  1425. $url = $tor->{'url'};
  1426. } else {
  1427. $url = $tor;
  1428. undef($tor);
  1429. }
  1430. # Extract the BTIH hash or NZB ID, if available
  1431. my $hash = undef();
  1432. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1433. $hash = lc($1);
  1434. } elsif ($url =~ /\/getnzb\/(\w+)\.nzb\&/i) {
  1435. $hash = lc($1);
  1436. } elsif ($url =~ /\bt=get\b/i && $url =~ /\bid=(\w+)/) {
  1437. $hash = lc($1);
  1438. }
  1439. # Save back to the tor, if provided
  1440. if (defined($tor) && defined($hash)) {
  1441. $tor->{'hash'} = lc($hash);
  1442. }
  1443. # Always return the hash, or undef() if none can be found
  1444. return $hash;
  1445. }
  1446. # Save plausible results
  1447. sub checkTORs() {
  1448. foreach my $tor (@{ $SERIES->{'tors'} }) {
  1449. # Extract the BTIH/GUID, if available
  1450. getHash($tor);
  1451. # Skip bad TORs based on name/etc.
  1452. if (badTor($tor)) {
  1453. next;
  1454. }
  1455. # Skip files that contain a word from the series exclude list
  1456. my $exclude = undef();
  1457. foreach my $ex (keys(%{ $SERIES->{'exclude_hash'} })) {
  1458. $ex = quotemeta($ex);
  1459. if ($tor->{'title'} =~ m/${ex}/i) {
  1460. $exclude = $ex;
  1461. last;
  1462. }
  1463. }
  1464. if (defined($exclude)) {
  1465. if ($DEBUG) {
  1466. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  1467. }
  1468. next;
  1469. }
  1470. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  1471. if (!$CONFIG->{'CUSTOM_SEARCH'}) {
  1472. # Skip files that don't contain the right season number
  1473. if (!defined($tor->{'season'}) || $tor->{'season'} != $SERIES->{'season'}) {
  1474. if ($DEBUG) {
  1475. print STDERR 'Skipping file: No match for season number ('
  1476. . $SERIES->{'season'} . '): '
  1477. . $tor->{'title'} . "\n";
  1478. }
  1479. next;
  1480. # Skip files that don't contain a needed episode number, unless there is no episode number and no_quality_checks is set
  1481. } elsif ((defined($tor->{'episode'}) && !$SERIES->{'need_hash'}->{ $tor->{'episode'} })
  1482. || (!defined($tor->{'episode'}) && !$SERIES->{'no_quality_checks'}))
  1483. {
  1484. if ($DEBUG) {
  1485. print STDERR 'Skipping file: No match for episode number ('
  1486. . $tor->{'episode'} . '): '
  1487. . $tor->{'title'} . "\n";
  1488. }
  1489. next;
  1490. }
  1491. } elsif (ref($CONFIG->{'CUSTOM_SEARCH'}) eq 'Regexp') {
  1492. # Skip files that don't match the regex
  1493. if (!($tor->{'title'} =~ $CONFIG->{'CUSTOM_SEARCH'})) {
  1494. if ($DEBUG) {
  1495. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex ('
  1496. . $CONFIG->{'CUSTOM_SEARCH'} . '): '
  1497. . $tor->{'title'} . "\n";
  1498. }
  1499. next;
  1500. }
  1501. }
  1502. # Ensure the seed/leach count is usable
  1503. seedCleanup($tor);
  1504. # Only apply the quality rules if no_quality_checks is not in effect
  1505. if (!$SERIES->{'no_quality_checks'} && lowQualityTor($tor)) {
  1506. next;
  1507. }
  1508. # Save good torrents
  1509. push(@{ $SERIES->{'tors_hash'}->{ $tor->{'episode'} } }, $tor);
  1510. if ($DEBUG) {
  1511. print STDERR 'Possible URL ('
  1512. . $tor->{'seeds'} . '/'
  1513. . $tor->{'leaches'}
  1514. . ' seeds/leaches, '
  1515. . $tor->{'size'}
  1516. . ' MiB): '
  1517. . $tor->{'title'} . "\n";
  1518. }
  1519. }
  1520. }
  1521. # Find the average size and adjust the availablilty counts for easily comparison
  1522. sub checkSize() {
  1523. my %size = ();
  1524. my %max = ();
  1525. my %avg = ();
  1526. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1527. my $count = 0;
  1528. $avg{$episode} = 0.001;
  1529. $max{$episode} = 0.001;
  1530. foreach my $tor (@{ $SERIES->{'tors_hash'}->{$episode} }) {
  1531. $count++;
  1532. $avg{$episode} += $tor->{'size'};
  1533. if ($tor->{'size'} > $max{$episode}) {
  1534. $max{$episode} = $tor->{'size'};
  1535. }
  1536. }
  1537. if ($count > 0) {
  1538. $avg{$episode} /= $count;
  1539. }
  1540. if (!defined($max{$episode})) {
  1541. warn("Invalid max episode\n");
  1542. }
  1543. if (!defined($avg{$episode})) {
  1544. warn("Invalid avg episode\n");
  1545. }
  1546. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1547. if ($DEBUG) {
  1548. print STDERR 'Episode '
  1549. . $episode
  1550. . ' max/avg/cmp size: '
  1551. . int($max{$episode}) . '/'
  1552. . int($avg{$episode}) . '/'
  1553. . int($size{$episode})
  1554. . " MiB\n";
  1555. }
  1556. }
  1557. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1558. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1559. foreach my $tor (@{ $SERIES->{'tors_hash'}->{$episode} }) {
  1560. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1561. # Start with the peer count
  1562. $tor->{'adj_count'} = $count;
  1563. # HVEC encoding gets a size bonus for efficency
  1564. if ($tor->{'title'} =~ /HEVC/ || $tor->{'title'} =~ /x265/) {
  1565. $tor->{'size'} *= $CONFIG->{'HEVC_BONUS'};
  1566. }
  1567. # Adjust based on file size
  1568. {
  1569. my $size_ratio = $tor->{'size'} / $size{$episode};
  1570. if ($tor->{'size'} >= $size{$episode}) {
  1571. $tor->{'adj_count'} *= $CONFIG->{'SIZE_BONUS'} * $size_ratio;
  1572. } else {
  1573. $tor->{'adj_count'} *= (1 / $CONFIG->{'SIZE_PENALTY'}) * $size_ratio;
  1574. }
  1575. }
  1576. # Some titles suggest low quality
  1577. if ($tor->{'title'} =~ /Subtitulado/i) {
  1578. $tor->{'adj_count'} *= 1 / $CONFIG->{'TITLE_PENALTY'};
  1579. }
  1580. # Truncate to an integer
  1581. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1582. if ($DEBUG) {
  1583. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1584. }
  1585. }
  1586. }
  1587. }
  1588. # Resolve secondary URLs
  1589. sub resolveSecondary($) {
  1590. my ($tor) = @_;
  1591. # Fetch the torrent-specific page and extract the magent link
  1592. if ($tor->{'source'} eq 'ISO') {
  1593. my ($content, $code) = fetch($tor->{'url'}, 'secondary.html');
  1594. if ($code != 200) {
  1595. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1596. goto OUT;
  1597. }
  1598. my ($magnet) = $content =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1599. if (!defined($magnet) || length($magnet) < 1) {
  1600. if ($DEBUG) {
  1601. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1602. }
  1603. goto OUT;
  1604. }
  1605. $tor->{'url'} = decode_entities($magnet);
  1606. }
  1607. # Extract the hash
  1608. getHash($tor);
  1609. if (!$tor->{'hash'} || $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1610. if ($DEBUG) {
  1611. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1612. }
  1613. goto OUT;
  1614. }
  1615. OUT:
  1616. return $tor->{'url'};
  1617. }
  1618. sub resolveTrackers($) {
  1619. my ($url) = @_;
  1620. # Always append a few static trackers to the URI
  1621. if ($url =~ /^magnet\:/i) {
  1622. foreach my $tracker (@{ $CONFIG->{'TRACKERS'} }) {
  1623. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1624. my $match = quotemeta($arg);
  1625. if (!($url =~ /${match}/)) {
  1626. $url .= $arg;
  1627. }
  1628. }
  1629. }
  1630. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1631. if ($CONFIG->{'TRACKER_LOOKUP'} && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1632. my $hash = lc($1);
  1633. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1634. my $hashURL = $baseURL . '/' . $hash;
  1635. my ($content, $code) = fetch($hashURL, 'hashinfo.html');
  1636. if ($code != 200) {
  1637. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1638. return $url;
  1639. }
  1640. # Parse out and fetch the tracker list URL
  1641. my ($list) = $content =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1642. if (!defined($list)) {
  1643. if ($DEBUG) {
  1644. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1645. }
  1646. return $url;
  1647. }
  1648. my $listURL = $baseURL . $list;
  1649. ($content, $code) = fetch($listURL, 'tracker.html');
  1650. if ($code != 200) {
  1651. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1652. return $url;
  1653. }
  1654. # Parse the tracker list and append our URL
  1655. foreach my $line ($content) {
  1656. if ($line =~ /^\s*$/) {
  1657. next;
  1658. }
  1659. $line =~ s/^\s+//;
  1660. $line =~ s/\s+$//;
  1661. if ($line =~ /^(?:http|udp)\:/i) {
  1662. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1663. my $match = quotemeta($arg);
  1664. if (!($url =~ /${match}/)) {
  1665. if ($DEBUG) {
  1666. print STDERR 'Adding tracker: ' . $line . "\n";
  1667. }
  1668. $url .= $arg;
  1669. }
  1670. } else {
  1671. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1672. }
  1673. }
  1674. }
  1675. return $url;
  1676. }
  1677. # Pick the best-adjusted-count torrent for each episode
  1678. sub chooseTORs() {
  1679. my %urls = ();
  1680. my @output = ();
  1681. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1682. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $SERIES->{'tors_hash'}->{$episode} };
  1683. my $max = undef();
  1684. foreach my $tor (@sorted) {
  1685. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1686. if ($urls{$episode} = resolveSecondary($tor)) {
  1687. if (!$tor->{'hash'} || $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1688. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1689. next;
  1690. }
  1691. $max = $tor->{'adj_count'};
  1692. }
  1693. if ($DEBUG) {
  1694. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1695. }
  1696. } elsif ($DEBUG) {
  1697. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1698. }
  1699. }
  1700. }
  1701. # Output
  1702. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1703. if (defined($urls{$episode})) {
  1704. $urls{$episode} = resolveTrackers($urls{$episode});
  1705. push(@output, $urls{$episode});
  1706. if ($CONFIG->{'SYSLOG'}) {
  1707. syslog(LOG_NOTICE, $SERIES->{'name'} . ': ' . getHash($urls{$episode}));
  1708. }
  1709. if ($DEBUG) {
  1710. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1711. }
  1712. } elsif ($DEBUG) {
  1713. print STDERR 'No URL for: ' . $episode . "\n";
  1714. }
  1715. }
  1716. return \@output;
  1717. }
  1718. sub splitTags($$$$) {
  1719. my ($content, $tag, $header, $match) = @_;
  1720. # Find each tag element
  1721. my @out = ();
  1722. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1723. foreach my $part (@parts) {
  1724. # Trim trailing tags and skip things that aren't complete tags
  1725. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1726. if ($DEBUG > 2) {
  1727. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1728. }
  1729. next;
  1730. }
  1731. # Skip headers
  1732. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1733. if ($DEBUG > 2) {
  1734. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1735. }
  1736. next;
  1737. }
  1738. # Skip non-matches
  1739. if (defined($match) && !($part =~ m/${match}/i)) {
  1740. if ($DEBUG > 2) {
  1741. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1742. }
  1743. next;
  1744. }
  1745. # Save good tags
  1746. push(@out, $part);
  1747. }
  1748. return @out;
  1749. }
  1750. # Extract season
  1751. sub findSE($) {
  1752. my ($name) = @_;
  1753. my $season = 0;
  1754. my $episode = 0;
  1755. my $seasonBlock = '';
  1756. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1757. $seasonBlock = $1;
  1758. my ($month, $day);
  1759. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1760. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1761. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1762. $seasonBlock = $1;
  1763. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1764. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1765. $seasonBlock = $1;
  1766. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1767. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1768. $seasonBlock = $1;
  1769. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1770. }
  1771. # Return something valid and INTy or UNDEF
  1772. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1773. if ($DEBUG) {
  1774. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1775. }
  1776. $season = undef();
  1777. $episode = undef();
  1778. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1779. # Episode-by-date
  1780. $season = int($season);
  1781. } else {
  1782. # Catchall
  1783. # This will warn and return undef() (which is valid) on error
  1784. $season = int($season);
  1785. $episode = int($episode);
  1786. }
  1787. return ($season, $episode);
  1788. }
  1789. sub initSources() {
  1790. my %sources = ();
  1791. # NZBplanet.net
  1792. if ($CONFIG->{'SOURCES'}->{'PLANET'}) {
  1793. my @proxies = ('api.nzbplanet.net/api');
  1794. my $source = findProxy(\@proxies, '\bNzbplanet\b');
  1795. if ($source && exists($CONFIG->{'PLANET_APIKEY'}) && $CONFIG->{'PLANET_APIKEY'}) {
  1796. $source->{'weight'} = 1.00;
  1797. $source->{'quote'} = 0;
  1798. $source->{'search_exclude'} = 0;
  1799. $source->{'search_suffix'} = '';
  1800. $source->{'custom_search'} = sub ($$$$) {
  1801. my ($urls, $series, $season, $episode) = @_;
  1802. my $url =
  1803. $source->{'search_url'}
  1804. . '?o=json&t=tvsearch&q='
  1805. . $series
  1806. . '&season='
  1807. . $season . '&ep='
  1808. . $episode
  1809. . '&apikey='
  1810. . $CONFIG->{'PLANET_APIKEY'};
  1811. push(@{$urls}, $url);
  1812. };
  1813. $source->{'search_url'} .= '?o=json&apikey=' . $CONFIG->{'PLANET_APIKEY'} . '&t=search&q=';
  1814. $sources{'PLANET'} = $source;
  1815. }
  1816. }
  1817. # NZB.is
  1818. if ($CONFIG->{'SOURCES'}->{'IS'}) {
  1819. my @proxies = ('nzb.is/api');
  1820. my $source = findProxy(\@proxies, '\bnzb\.is\b');
  1821. if ($source && exists($CONFIG->{'IS_APIKEY'}) && $CONFIG->{'IS_APIKEY'}) {
  1822. $source->{'weight'} = 1.00;
  1823. $source->{'quote'} = 0;
  1824. $source->{'search_exclude'} = 0;
  1825. $source->{'search_suffix'} = '';
  1826. $source->{'custom_search'} = sub ($$$$) {
  1827. my ($urls, $series, $season, $episode) = @_;
  1828. my $url =
  1829. $source->{'search_url'}
  1830. . '?o=json&t=tvsearch&q='
  1831. . $series
  1832. . '&season='
  1833. . $season . '&ep='
  1834. . $episode
  1835. . '&apikey='
  1836. . $CONFIG->{'IS_APIKEY'};
  1837. push(@{$urls}, $url);
  1838. };
  1839. $source->{'search_url'} .= '?o=json&apikey=' . $CONFIG->{'IS_APIKEY'} . '&t=search&q=';
  1840. $sources{'IS'} = $source;
  1841. }
  1842. }
  1843. # Usenet Crawler
  1844. if ($CONFIG->{'SOURCES'}->{'UC'}) {
  1845. my @proxies = ('www.usenet-crawler.com/api');
  1846. my $source = findProxy(\@proxies, '\busenet-crawler\b');
  1847. if ($source && exists($CONFIG->{'UC_APIKEY'}) && $CONFIG->{'UC_APIKEY'}) {
  1848. $source->{'weight'} = 1.00;
  1849. $source->{'quote'} = 0;
  1850. $source->{'search_exclude'} = 0;
  1851. $source->{'search_suffix'} = '';
  1852. $source->{'custom_search'} = sub ($$$$) {
  1853. my ($urls, $series, $season, $episode) = @_;
  1854. my $url =
  1855. $source->{'search_url'}
  1856. . '?o=json&t=tvsearch&q='
  1857. . $series
  1858. . '&season='
  1859. . $season . '&ep='
  1860. . $episode
  1861. . '&apikey='
  1862. . $CONFIG->{'UC_APIKEY'};
  1863. push(@{$urls}, $url);
  1864. };
  1865. $source->{'search_url'} .= '?o=json&apikey=' . $CONFIG->{'UC_APIKEY'} . '&t=search&q=';
  1866. $sources{'UC'} = $source;
  1867. }
  1868. }
  1869. # NZB Cat
  1870. if ($CONFIG->{'SOURCES'}->{'NCAT'}) {
  1871. my @proxies = ('nzb.cat/api');
  1872. my $source = findProxy(\@proxies, '\bforgottenpassword\b');
  1873. if ($source && exists($CONFIG->{'NCAT_APIKEY'}) && $CONFIG->{'NCAT_APIKEY'}) {
  1874. $source->{'weight'} = 1.00;
  1875. $source->{'quote'} = 0;
  1876. $source->{'search_exclude'} = 0;
  1877. $source->{'search_suffix'} = '';
  1878. $source->{'custom_search'} = sub ($$$$) {
  1879. my ($urls, $series, $season, $episode) = @_;
  1880. my $url =
  1881. $source->{'search_url'}
  1882. . '?o=json&t=tvsearch&q='
  1883. . $series
  1884. . '&season='
  1885. . $season . '&ep='
  1886. . $episode
  1887. . '&apikey='
  1888. . $CONFIG->{'NCAT_APIKEY'};
  1889. push(@{$urls}, $url);
  1890. };
  1891. $source->{'search_url'} .= '?o=json&apikey=' . $CONFIG->{'NCAT_APIKEY'} . '&t=search&q=';
  1892. $sources{'NCAT'} = $source;
  1893. }
  1894. }
  1895. # The Pirate Bay
  1896. if ($CONFIG->{'SOURCES'}->{'TPB'}) {
  1897. my @proxies = ('thepiratebay.org/search/', 'tpb.unblocked.co/search/');
  1898. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1899. if ($source) {
  1900. $source->{'weight'} = 1.00;
  1901. $source->{'quote'} = 0;
  1902. $source->{'search_exclude'} = 1;
  1903. $source->{'search_suffix'} = '/0/7/0';
  1904. $sources{'TPB'} = $source;
  1905. }
  1906. }
  1907. # ISOhunt
  1908. if ($CONFIG->{'SOURCES'}->{'ISO'}) {
  1909. my @proxies = ('isohunt.to/torrents/?ihq=', 'isohunters.net/torrents/?ihq=');
  1910. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1911. if ($source) {
  1912. $source->{'weight'} = 0.75;
  1913. $source->{'quote'} = 1;
  1914. $source->{'search_exclude'} = 1;
  1915. $source->{'search_suffix'} = '';
  1916. $sources{'ISO'} = $source;
  1917. }
  1918. }
  1919. # Kickass
  1920. if ($CONFIG->{'SOURCES'}->{'KICK'}) {
  1921. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1922. my $source = findProxy(\@proxies, '/search.php');
  1923. if ($source) {
  1924. $source->{'weight'} = 1.00;
  1925. $source->{'quote'} = 1;
  1926. $source->{'search_exclude'} = 1;
  1927. $source->{'search_suffix'} = '/';
  1928. $sources{'KICK'} = $source;
  1929. }
  1930. }
  1931. # Torrentz
  1932. if ($CONFIG->{'SOURCES'}->{'Z'}) {
  1933. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1934. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1935. if ($source) {
  1936. $source->{'weight'} = 1.00;
  1937. $source->{'quote'} = 1;
  1938. $source->{'search_exclude'} = 1;
  1939. $source->{'search_suffix'} = '';
  1940. if (!$SERIES->{'no_quality_checks'}) {
  1941. $source->{'search_suffix'} = '+peer+%3E+' . $CONFIG->{'MIN_COUNT'};
  1942. }
  1943. $sources{'Z'} = $source;
  1944. }
  1945. }
  1946. # ExtraTorrent
  1947. if ($CONFIG->{'SOURCES'}->{'ET'}) {
  1948. my @proxies = (
  1949. 'extra.to/search/?search=', 'etmirror.com/search/?search=',
  1950. 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search='
  1951. );
  1952. my $source = findProxy(\@proxies, '/search/');
  1953. if ($source) {
  1954. $source->{'weight'} = 1.00;
  1955. $source->{'quote'} = 1;
  1956. $source->{'search_exclude'} = 0;
  1957. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1958. $source->{'search_url'} = 'phantomjs:' . $source->{'search_url'};
  1959. $sources{'ET'} = $source;
  1960. }
  1961. }
  1962. # Sanity check
  1963. if (scalar(keys(%sources)) < 1) {
  1964. die("No sources available\n");
  1965. }
  1966. return \%sources;
  1967. }
  1968. sub findProxy($$) {
  1969. my ($proxies, $match) = @_;
  1970. # Automatically select a proxy
  1971. my $host = '';
  1972. my $protocol = '';
  1973. my $search_url = '';
  1974. foreach my $url (@{$proxies}) {
  1975. my $path;
  1976. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1977. if (!$protocol) {
  1978. $protocol = $CONFIG->{'PROTOCOL'};
  1979. }
  1980. if (!$host) {
  1981. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1982. next;
  1983. }
  1984. my ($content, $code) = fetch($protocol . '://' . $host, undef(), 1);
  1985. if ($code == 200 && $content =~ m/${match}/i) {
  1986. $search_url = $protocol . '://' . $host . $path;
  1987. last;
  1988. } elsif ($DEBUG) {
  1989. print STDERR 'Proxy not available: ' . $host . "\n";
  1990. if ($DEBUG > 1) {
  1991. print STDERR $content . "\n";
  1992. }
  1993. }
  1994. }
  1995. # Return the search data if at least one proxy is up
  1996. if ($search_url) {
  1997. my %tmp = (
  1998. 'protocol' => $protocol,
  1999. 'host' => $host,
  2000. 'search_url' => $search_url,
  2001. );
  2002. return \%tmp;
  2003. }
  2004. # Return undef if we didn't find any working proxies
  2005. return undef();
  2006. }
  2007. sub fetch($;$$) {
  2008. my ($url, $file, $nocheck) = @_;
  2009. if ($DEBUG > 1) {
  2010. print STDERR 'Fetch: ' . $url . "\n";
  2011. }
  2012. # Allow usage with short names
  2013. if ($file && !($file =~ /^\//)) {
  2014. $file = '/tmp/findTorrent-' . $file;
  2015. }
  2016. # Random delay
  2017. if ($DEBUG > 1) {
  2018. sleep($CONFIG->{'SLEEP'} * 0.25);
  2019. } else {
  2020. sleep($CONFIG->{'DELAY'} * (rand($CONFIG->{'SLEEP'}) + ($CONFIG->{'SLEEP'} / 2)));
  2021. }
  2022. # Allow JS processing
  2023. if ($url =~ /^phantomjs\:\s*(\S.*)$/i) {
  2024. return phantomFetch($1, $file);
  2025. }
  2026. # Fetch object
  2027. if (!$FETCH) {
  2028. if (!$COOKIES) {
  2029. $COOKIES = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  2030. }
  2031. $FETCH = Fetch->new(
  2032. 'cookiefile' => $COOKIES,
  2033. 'timeout' => $CONFIG->{'TIMEOUT'},
  2034. 'uas' => $CONFIG->{'UA'}
  2035. );
  2036. }
  2037. # Debug as requested
  2038. if ($DEBUG > 1 && $file) {
  2039. $FETCH->file($file);
  2040. } else {
  2041. $FETCH->file('');
  2042. }
  2043. # Standard fetch
  2044. $FETCH->url($url);
  2045. if ($nocheck) {
  2046. $FETCH->fetch('nocheck' => 1);
  2047. } else {
  2048. $FETCH->fetch();
  2049. }
  2050. return (scalar($FETCH->content()), $FETCH->status_code());
  2051. }
  2052. sub phantomFetch($$) {
  2053. my ($url, $file) = @_;
  2054. # Init
  2055. if (!$SCRIPT) {
  2056. $SCRIPT = mktemp('/tmp/findTorrent.phantom.XXXXXXXX');
  2057. open(my $fh, '>', $SCRIPT)
  2058. or die('Unable to open PhantomJS script file: ' . $! . "\n");
  2059. print $fh $CONFIG->{'PHANTOM_CONFIG'};
  2060. close($fh);
  2061. }
  2062. # Capture STDOUT, drop STDERR
  2063. my @cmd = ($CONFIG->{'PHANTOM_BIN'}, $SCRIPT, $url);
  2064. my ($content, undef(), undef()) = capture { system(@cmd); };
  2065. # Debug as requested
  2066. if ($DEBUG > 1 && $file) {
  2067. open(my $fh, '>', $file)
  2068. or warn('Unable to open phantom debug file: ' . $! . "\n");
  2069. if ($fh) {
  2070. print $fh $content;
  2071. close($fh);
  2072. }
  2073. }
  2074. # Try to get the response status code, fake one if we cannot
  2075. my ($code) = $content =~ /^(\d\d\d)$/m;
  2076. if (!defined($code)) {
  2077. warn("Unable to retrive HTTP status code. Faking success...\n");
  2078. $code = 200;
  2079. }
  2080. return ($content, $code);
  2081. }