findTorrent.pl 59 KB

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