findTorrent.pl 59 KB

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