findTorrent.pl 60 KB

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