findTorrent.pl 59 KB

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