findTorrent.pl 51 KB

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