findTorrent.pl 58 KB

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