findTorrent.pl 58 KB

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