findTorrent.pl 55 KB

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