findTorrent.pl 60 KB

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