findTorrent.pl 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  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 $tor = parseJSON($CONTENT->[$i]);
  153. if ($tor) {
  154. push(@{ $SERIES->{'tors'} }, $tor);
  155. }
  156. } else {
  157. my $tor = parseHTML($CONTENT->[$i]);
  158. if ($tor) {
  159. push(@{ $SERIES->{'tors'} }, $tor);
  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 $tor = undef();
  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(@{ $SERIES->{'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(@{ $SERIES->{'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(@{ $SERIES->{'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(@{ $SERIES->{'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 %tmp = (
  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. $tor = \%tmp;
  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. } else {
  1047. warn("Unknown HTML content:\n" . $content . "\n\n");
  1048. }
  1049. return $tor;
  1050. }
  1051. # Handle JSON content
  1052. sub parseJSON($) {
  1053. my ($content) = @_;
  1054. if (!defined($content) || length($content) < 1) {
  1055. return undef();
  1056. }
  1057. my $json = eval { decode_json($content); };
  1058. if (!defined($json) || !ref($json)) {
  1059. warn('JSON parsing failure on: ' . $content . "\n");
  1060. return undef();
  1061. }
  1062. my $tor = undef();
  1063. if (ref($json) eq 'ARRAY' && scalar(@{$json}) == 0) {
  1064. if ($DEBUG > 1) {
  1065. print STDERR "Empty JSON array\n";
  1066. }
  1067. } elsif (ref($json) eq 'HASH'
  1068. && exists($json->{'channel'})
  1069. && ref($json->{'channel'}) eq 'HASH'
  1070. && exists($json->{'channel'}->{'title'})
  1071. && $json->{'channel'}->{'title'} =~ /usenet\-crawler/i)
  1072. {
  1073. print STDERR "Index: usenet-crawler\n";
  1074. } elsif (ref($json) eq 'ARRAY'
  1075. && scalar(@{$json}) > 0
  1076. && ref($json->[0]) eq 'HASH'
  1077. && exists($json->[0]->{'guid'})
  1078. && exists($json->[0]->{'postdate'}))
  1079. {
  1080. foreach my $item (@{$json}) {
  1081. my $tmp = parseNZB($item);
  1082. if ($tmp) {
  1083. $tmp->{'source'} = 'IS';
  1084. $tor = $tmp;
  1085. }
  1086. }
  1087. } elsif (ref($json) eq 'HASH' && exists($json->{'title'}) && $json->{'title'} =~ /NZBCat/i) {
  1088. my $list = $json->{'item'};
  1089. if (!$list || ref($list) ne 'ARRAY') {
  1090. if ($DEBUG) {
  1091. warn("Empty/invalid NCAT list\n");
  1092. }
  1093. return undef();
  1094. }
  1095. foreach my $item (@{$list}) {
  1096. my $tmp = parseNZB($item);
  1097. if ($tmp) {
  1098. $tmp->{'source'} = 'NCAT';
  1099. $tor = $tmp;
  1100. }
  1101. }
  1102. } elsif (ref($json) eq 'HASH'
  1103. && exists($json->{'channel'})
  1104. && ref($json->{'channel'}) eq 'HASH'
  1105. && exists($json->{'channel'}->{'title'})
  1106. && $json->{'channel'}->{'title'} =~ /\bNzb\s+Planet\b/i)
  1107. {
  1108. if (!exists($json->{'channel'}->{'item'}) || ref($json->{'channel'}->{'item'}) ne 'ARRAY') {
  1109. if ($DEBUG) {
  1110. print STDERR "Empty/invalid NZB Planet result\n";
  1111. }
  1112. return undef();
  1113. }
  1114. foreach my $item (@{ $json->{'channel'}->{'item'} }) {
  1115. my $tmp = parseNZB($item);
  1116. if ($tmp) {
  1117. $tmp->{'source'} = 'PLANET';
  1118. $tor = $tmp;
  1119. }
  1120. }
  1121. } else {
  1122. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  1123. }
  1124. return $tor;
  1125. }
  1126. sub parseNZB($) {
  1127. my ($item) = @_;
  1128. if (!$item || ref($item) ne 'HASH' || !exists($item->{'guid'})) {
  1129. warn("Unable to parse NZB item\n");
  1130. return undef();
  1131. }
  1132. # Ensure the record is sensible
  1133. my $id = undef();
  1134. if (ref($item->{'guid'}) eq 'HASH' && exists($item->{'guid'}->{'text'})) {
  1135. $id = $item->{'guid'}->{'text'};
  1136. } elsif (!ref($item->{'guid'})) {
  1137. $id = $item->{'guid'};
  1138. }
  1139. if (!$id) {
  1140. warn("Unable to parse NZB item GUID\n");
  1141. return undef();
  1142. }
  1143. # NZB URL
  1144. my $url = undef();
  1145. if (exists($item->{'link'}) && $item->{'link'}) {
  1146. $url = $item->{'link'};
  1147. $url =~ s/^(https?)\:/$CONFIG->{'PROTOCOL'}\:/;
  1148. } else {
  1149. # Special case for IS, which leaks very little in its JSON results
  1150. # Whatever consumes this will need to follow a 302 redirect
  1151. $url = $SOURCES->{'IS'}->{'search_url'} . '?t=get&id=' . $id;
  1152. }
  1153. # Title
  1154. my $title = undef();
  1155. if (exists($item->{'searchname'}) && $item->{'searchname'}) {
  1156. $title = $item->{'searchname'};
  1157. } elsif (exists($item->{'name'}) && $item->{'name'}) {
  1158. $title = $item->{'name'};
  1159. } elsif (exists($item->{'title'}) && $item->{'title'}) {
  1160. $title = $item->{'title'};
  1161. } elsif (exists($item->{'description'}) && $item->{'description'}) {
  1162. $title = $item->{'description'};
  1163. }
  1164. if ($title) {
  1165. $url .= '#' . $title;
  1166. }
  1167. # Extract the season and episode numbers
  1168. my ($season, $episode) = findSE($title);
  1169. # Size
  1170. my $size = 0;
  1171. if (exists($item->{'newznab:attr'}) && $item->{'newznab:attr'} && ref($item->{'newznab:attr'}) eq 'ARRAY') {
  1172. foreach my $hash (@{ $item->{'newznab:attr'} }) {
  1173. if (ref($hash) eq 'HASH' && exists($hash->{'_name'}) && exists($hash->{'_value'}) && $hash->{'_name'} eq 'size') {
  1174. $size = int($hash->{'_value'} / 1024 / 1024);
  1175. last;
  1176. }
  1177. }
  1178. } elsif (exists($item->{'attr'}) && $item->{'attr'} && ref($item->{'attr'}) eq 'ARRAY') {
  1179. foreach my $hash (@{ $item->{'attr'} }) {
  1180. if (!exists($hash->{'@attributes'}) || ref($hash->{'@attributes'}) ne 'HASH') {
  1181. next;
  1182. }
  1183. $hash = $hash->{'@attributes'};
  1184. if (exists($hash->{'name'}) && $hash->{'name'} eq 'size' && exists($hash->{'value'})) {
  1185. $size = int($hash->{'value'} / 1024 / 1024);
  1186. last;
  1187. }
  1188. }
  1189. } elsif (exists($item->{'size'})) {
  1190. $size = int($item->{'size'} / 1024 / 1024);
  1191. }
  1192. # Date
  1193. my $date = undef();
  1194. if (exists($item->{'pubDate'}) && $item->{'pubDate'}) {
  1195. $date = str2time($item->{'pubDate'});
  1196. } elsif (exists($item->{'postdate'}) && $item->{'postdate'}) {
  1197. $date = str2time($item->{'postdate'});
  1198. }
  1199. # Sanity checks
  1200. if (!$url) {
  1201. warn('No URL in NZB item: ' . $id . "\n");
  1202. return undef();
  1203. }
  1204. if (!$title) {
  1205. warn('No title in NZB item: ' . $id . "\n");
  1206. return undef();
  1207. }
  1208. if (!$size) {
  1209. warn('No size in NZB item: ' . $id . "\n");
  1210. return undef();
  1211. }
  1212. if ($DEBUG) {
  1213. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  1214. }
  1215. # Save the extracted data
  1216. my %tor = (
  1217. 'title' => $title,
  1218. 'season' => $season,
  1219. 'episode' => $episode,
  1220. 'date' => $date,
  1221. 'size' => $size,
  1222. 'url' => $url,
  1223. );
  1224. return \%tor;
  1225. }
  1226. sub badTor($) {
  1227. my ($tor) = @_;
  1228. # Pre-calculate the regex
  1229. if (!$SERIES->{'name_regex'}) {
  1230. my $clean = $SERIES->{'name'};
  1231. $clean =~ s/[\"\']//g;
  1232. $clean =~ s/[\W_]+/\[\\W_\].*/g;
  1233. $SERIES->{'name_regex'} = qr/^${clean}[\W_]/i;
  1234. }
  1235. # Skip files that are in the torrent excludes list
  1236. if ($tor->{'hash'} && $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1237. if ($DEBUG) {
  1238. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1239. }
  1240. return 1;
  1241. }
  1242. # Skip files that don't start with our show title
  1243. if (!($tor->{'title'} =~ $SERIES->{'name_regex'})) {
  1244. if ($DEBUG) {
  1245. print STDERR 'Skipping file: Title does not match (' . $SERIES->{'name_regex'} . '): ' . $tor->{'title'} . "\n";
  1246. }
  1247. return 1;
  1248. # Skip leaked files
  1249. } elsif ($tor->{'title'} =~ /leaked/i) {
  1250. if ($DEBUG) {
  1251. print STDERR 'Skipping file: Title contains "leaked": ' . $tor->{'title'} . "\n";
  1252. }
  1253. return 1;
  1254. # Skip pre-air files
  1255. } elsif ($tor->{'title'} =~ /preair/i) {
  1256. if ($DEBUG) {
  1257. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  1258. }
  1259. return 1;
  1260. # Skip SWESUB files
  1261. } elsif ($tor->{'title'} =~ /swesub/i) {
  1262. if ($DEBUG) {
  1263. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  1264. }
  1265. return 1;
  1266. # Skip .rus. files
  1267. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  1268. if ($DEBUG) {
  1269. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  1270. }
  1271. return 1;
  1272. # Skip German files
  1273. } elsif ($tor->{'title'} =~ /german/i) {
  1274. if ($DEBUG) {
  1275. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  1276. }
  1277. return 1;
  1278. # Skip French files
  1279. } elsif ($tor->{'title'} =~ /french/i) {
  1280. if ($DEBUG) {
  1281. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  1282. }
  1283. return 1;
  1284. # Skip Spanish files
  1285. } elsif ($tor->{'title'} =~ /Español/i) {
  1286. if ($DEBUG) {
  1287. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  1288. }
  1289. return 1;
  1290. # Skip Castellano files
  1291. } elsif ($tor->{'title'} =~ /Castellano/i) {
  1292. if ($DEBUG) {
  1293. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  1294. }
  1295. return 1;
  1296. # Skip unedited files
  1297. } elsif ($tor->{'title'} =~ /unedited/i) {
  1298. if ($DEBUG) {
  1299. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  1300. }
  1301. return 1;
  1302. }
  1303. # If we're still around the TOR is good
  1304. return 0;
  1305. }
  1306. sub seedCleanup($) {
  1307. my ($tor) = @_;
  1308. # Cap seeds/leaches/date and ensure they are always defined
  1309. if (!exists($tor->{'seeds'}) || !$tor->{'seeds'}) {
  1310. $tor->{'seeds'} = 0;
  1311. }
  1312. if ($tor->{'seeds'} > $CONFIG->{'MAX_SEEDS'}) {
  1313. $tor->{'seeds'} = $CONFIG->{'MAX_SEEDS'};
  1314. }
  1315. if (!exists($tor->{'leaches'}) || !$tor->{'leaches'}) {
  1316. $tor->{'leaches'} = 0;
  1317. }
  1318. if ($tor->{'leaches'} > $CONFIG->{'MAX_SEEDS'}) {
  1319. $tor->{'leaches'} = $CONFIG->{'MAX_SEEDS'};
  1320. }
  1321. # Proxy publication date to seeder/leacher quality
  1322. if ($tor->{'date'} && !$tor->{'seeds'}) {
  1323. my $age = time() - $tor->{'date'};
  1324. if ($age < 0) {
  1325. warn('Invalid date (' . $tor->{'date'} . '): ' . $tor->{'title'} . "\n");
  1326. $age = 0;
  1327. }
  1328. $age /= 86400;
  1329. if ($age > $CONFIG->{'NZB_AGE_GOOD'}) {
  1330. $tor->{'seeds'} = $CONFIG->{'MIN_COUNT'};
  1331. if ($age > $CONFIG->{'NZB_AGE_MAX'}) {
  1332. $tor->{'seeds'} = ($CONFIG->{'MIN_COUNT'} / 2) - 1;
  1333. }
  1334. } else {
  1335. my $penalty = ($CONFIG->{'MAX_SEEDS'} / 2) / $CONFIG->{'NZB_AGE_GOOD'};
  1336. $tor->{'seeds'} = $CONFIG->{'MAX_SEEDS'} - ($age * $penalty);
  1337. }
  1338. $tor->{'seeds'} = int($tor->{'seeds'});
  1339. $tor->{'leaches'} = $tor->{'seeds'};
  1340. }
  1341. }
  1342. sub lowQualityTor($) {
  1343. my ($tor) = @_;
  1344. # Skip torrents with too few seeders/leachers
  1345. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $CONFIG->{'MIN_COUNT'}) {
  1346. if ($DEBUG) {
  1347. print STDERR 'Skipping file: Insufficient seeder/leacher count ('
  1348. . $tor->{'seeds'} . '/'
  1349. . $tor->{'leaches'} . '): '
  1350. . $tor->{'title'} . "\n";
  1351. }
  1352. return 1;
  1353. # Skip torrents with unusual seed/leach ratios
  1354. } elsif ($tor->{'seeds'} > 1
  1355. && $tor->{'seeds'} < $CONFIG->{'SEED_RATIO_COUNT'}
  1356. && $tor->{'seeds'} > $tor->{'leaches'} * $CONFIG->{'MAX_SEED_RATIO'})
  1357. {
  1358. if ($DEBUG) {
  1359. print STDERR 'Skipping file: Unusual seeder/leacher ratio ('
  1360. . $tor->{'seeds'} . '/'
  1361. . $tor->{'leaches'} . '): '
  1362. . $tor->{'title'} . "\n";
  1363. }
  1364. return 1;
  1365. # Skip torrents that are too small
  1366. } elsif ($tor->{'size'} < $CONFIG->{'MIN_SIZE'}) {
  1367. if ($DEBUG) {
  1368. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1369. }
  1370. return 1;
  1371. }
  1372. # If we're still around the TOR is good
  1373. return 0;
  1374. }
  1375. sub getHash($) {
  1376. my ($tor) = @_;
  1377. my $url;
  1378. # Allow either a URL or a tor hashref
  1379. if (ref($tor) eq 'HASH') {
  1380. if ($tor->{'hash'}) {
  1381. return $tor->{'hash'};
  1382. }
  1383. $url = $tor->{'url'};
  1384. } else {
  1385. $url = $tor;
  1386. undef($tor);
  1387. }
  1388. # Extract the BTIH hash or NZB ID, if available
  1389. my $hash = undef();
  1390. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1391. $hash = lc($1);
  1392. } elsif ($url =~ /\/getnzb\/(\w+)\.nzb\&/i) {
  1393. $hash = lc($1);
  1394. } elsif ($url =~ /\bt=get\b/i && $url =~ /\bid=(\w+)/) {
  1395. $hash = lc($1);
  1396. }
  1397. # Save back to the tor, if provided
  1398. if (defined($tor) && defined($hash)) {
  1399. $tor->{'hash'} = lc($hash);
  1400. }
  1401. # Always return the hash, or undef() if none can be found
  1402. return $hash;
  1403. }
  1404. # Save plausible results
  1405. sub checkTORs() {
  1406. foreach my $tor (@{ $SERIES->{'tors'} }) {
  1407. # Extract the BTIH/GUID, if available
  1408. getHash($tor);
  1409. # Skip bad TORs based on name/etc.
  1410. if (badTor($tor)) {
  1411. next;
  1412. }
  1413. # Skip files that contain a word from the series exclude list
  1414. my $exclude = undef();
  1415. foreach my $ex (keys(%{ $SERIES->{'exclude_hash'} })) {
  1416. $ex = quotemeta($ex);
  1417. if ($tor->{'title'} =~ m/${ex}/i) {
  1418. $exclude = $ex;
  1419. last;
  1420. }
  1421. }
  1422. if (defined($exclude)) {
  1423. if ($DEBUG) {
  1424. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  1425. }
  1426. next;
  1427. }
  1428. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  1429. if (!$CONFIG->{'CUSTOM_SEARCH'}) {
  1430. # Skip files that don't contain the right season number
  1431. if (!defined($tor->{'season'}) || $tor->{'season'} != $SERIES->{'season'}) {
  1432. if ($DEBUG) {
  1433. print STDERR 'Skipping file: No match for season number ('
  1434. . $SERIES->{'season'} . '): '
  1435. . $tor->{'title'} . "\n";
  1436. }
  1437. next;
  1438. # Skip files that don't contain a needed episode number, unless there is no episode number and no_quality_checks is set
  1439. } elsif ((defined($tor->{'episode'}) && !$SERIES->{'need_hash'}->{ $tor->{'episode'} })
  1440. || (!defined($tor->{'episode'}) && !$SERIES->{'no_quality_checks'}))
  1441. {
  1442. if ($DEBUG) {
  1443. print STDERR 'Skipping file: No match for episode number ('
  1444. . $tor->{'episode'} . '): '
  1445. . $tor->{'title'} . "\n";
  1446. }
  1447. next;
  1448. }
  1449. } elsif (ref($CONFIG->{'CUSTOM_SEARCH'}) eq 'Regexp') {
  1450. # Skip files that don't match the regex
  1451. if (!($tor->{'title'} =~ $CONFIG->{'CUSTOM_SEARCH'})) {
  1452. if ($DEBUG) {
  1453. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex ('
  1454. . $CONFIG->{'CUSTOM_SEARCH'} . '): '
  1455. . $tor->{'title'} . "\n";
  1456. }
  1457. next;
  1458. }
  1459. }
  1460. # Ensure the seed/leach count is usable
  1461. seedCleanup($tor);
  1462. # Only apply the quality rules if no_quality_checks is not in effect
  1463. if (!$SERIES->{'no_quality_checks'} && lowQualityTor($tor)) {
  1464. next;
  1465. }
  1466. # Save good torrents
  1467. push(@{ $SERIES->{'tors_hash'}->{ $tor->{'episode'} } }, $tor);
  1468. if ($DEBUG) {
  1469. print STDERR 'Possible URL ('
  1470. . $tor->{'seeds'} . '/'
  1471. . $tor->{'leaches'}
  1472. . ' seeds/leaches, '
  1473. . $tor->{'size'}
  1474. . ' MiB): '
  1475. . $tor->{'title'} . "\n";
  1476. }
  1477. }
  1478. }
  1479. # Find the average size and adjust the availablilty counts for easily comparison
  1480. sub checkSize() {
  1481. my %size = ();
  1482. my %max = ();
  1483. my %avg = ();
  1484. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1485. my $count = 0;
  1486. $avg{$episode} = 0.001;
  1487. $max{$episode} = 0.001;
  1488. foreach my $tor (@{ $SERIES->{'tors_hash'}->{$episode} }) {
  1489. $count++;
  1490. $avg{$episode} += $tor->{'size'};
  1491. if ($tor->{'size'} > $max{$episode}) {
  1492. $max{$episode} = $tor->{'size'};
  1493. }
  1494. }
  1495. if ($count > 0) {
  1496. $avg{$episode} /= $count;
  1497. }
  1498. if (!defined($max{$episode})) {
  1499. warn("Invalid max episode\n");
  1500. }
  1501. if (!defined($avg{$episode})) {
  1502. warn("Invalid avg episode\n");
  1503. }
  1504. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1505. if ($DEBUG) {
  1506. print STDERR 'Episode '
  1507. . $episode
  1508. . ' max/avg/cmp size: '
  1509. . int($max{$episode}) . '/'
  1510. . int($avg{$episode}) . '/'
  1511. . int($size{$episode})
  1512. . " MiB\n";
  1513. }
  1514. }
  1515. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1516. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1517. foreach my $tor (@{ $SERIES->{'tors_hash'}->{$episode} }) {
  1518. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1519. # Start with the peer count
  1520. $tor->{'adj_count'} = $count;
  1521. # Adjust based on file size
  1522. {
  1523. my $size_ratio = $tor->{'size'} / $size{$episode};
  1524. if ($tor->{'size'} >= $size{$episode}) {
  1525. $tor->{'adj_count'} *= $CONFIG->{'SIZE_BONUS'} * $size_ratio;
  1526. } else {
  1527. $tor->{'adj_count'} *= (1 / $CONFIG->{'SIZE_PENALTY'}) * $size_ratio;
  1528. }
  1529. }
  1530. # Adjust based on title contents
  1531. if ($tor->{'title'} =~ /Subtitulado/i) {
  1532. $tor->{'adj_count'} *= 1 / $CONFIG->{'TITLE_PENALTY'};
  1533. }
  1534. # Truncate to an integer
  1535. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1536. if ($DEBUG) {
  1537. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1538. }
  1539. }
  1540. }
  1541. }
  1542. # Resolve secondary URLs
  1543. sub resolveSecondary($) {
  1544. my ($tor) = @_;
  1545. # Fetch the torrent-specific page and extract the magent link
  1546. if ($tor->{'source'} eq 'ISO') {
  1547. my ($content, $code) = fetch($tor->{'url'}, 'secondary.html');
  1548. if ($code != 200) {
  1549. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1550. goto OUT;
  1551. }
  1552. my ($magnet) = $content =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1553. if (!defined($magnet) || length($magnet) < 1) {
  1554. if ($DEBUG) {
  1555. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1556. }
  1557. goto OUT;
  1558. }
  1559. $tor->{'url'} = decode_entities($magnet);
  1560. }
  1561. # Extract the hash
  1562. getHash($tor);
  1563. if (!$tor->{'hash'} || $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1564. if ($DEBUG) {
  1565. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1566. }
  1567. goto OUT;
  1568. }
  1569. OUT:
  1570. return $tor->{'url'};
  1571. }
  1572. sub resolveTrackers($) {
  1573. my ($url) = @_;
  1574. # Always append a few static trackers to the URI
  1575. if ($url =~ /^magnet\:/i) {
  1576. foreach my $tracker (@{ $CONFIG->{'TRACKERS'} }) {
  1577. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1578. my $match = quotemeta($arg);
  1579. if (!($url =~ /${match}/)) {
  1580. $url .= $arg;
  1581. }
  1582. }
  1583. }
  1584. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1585. if ($CONFIG->{'TRACKER_LOOKUP'} && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1586. my $hash = lc($1);
  1587. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1588. my $hashURL = $baseURL . '/' . $hash;
  1589. my ($content, $code) = fetch($hashURL, 'hashinfo.html');
  1590. if ($code != 200) {
  1591. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1592. return $url;
  1593. }
  1594. # Parse out and fetch the tracker list URL
  1595. my ($list) = $content =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1596. if (!defined($list)) {
  1597. if ($DEBUG) {
  1598. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1599. }
  1600. return $url;
  1601. }
  1602. my $listURL = $baseURL . $list;
  1603. ($content, $code) = fetch($listURL, 'tracker.html');
  1604. if ($code != 200) {
  1605. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1606. return $url;
  1607. }
  1608. # Parse the tracker list and append our URL
  1609. foreach my $line ($content) {
  1610. if ($line =~ /^\s*$/) {
  1611. next;
  1612. }
  1613. $line =~ s/^\s+//;
  1614. $line =~ s/\s+$//;
  1615. if ($line =~ /^(?:http|udp)\:/i) {
  1616. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1617. my $match = quotemeta($arg);
  1618. if (!($url =~ /${match}/)) {
  1619. if ($DEBUG) {
  1620. print STDERR 'Adding tracker: ' . $line . "\n";
  1621. }
  1622. $url .= $arg;
  1623. }
  1624. } else {
  1625. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1626. }
  1627. }
  1628. }
  1629. return $url;
  1630. }
  1631. # Pick the best-adjusted-count torrent for each episode
  1632. sub chooseTORs() {
  1633. my %urls = ();
  1634. my @output = ();
  1635. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1636. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $SERIES->{'tors_hash'}->{$episode} };
  1637. my $max = undef();
  1638. foreach my $tor (@sorted) {
  1639. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1640. if ($urls{$episode} = resolveSecondary($tor)) {
  1641. if (!$tor->{'hash'} || $CONFIG->{'EXCLUDES'}->{ $tor->{'hash'} }) {
  1642. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1643. next;
  1644. }
  1645. $max = $tor->{'adj_count'};
  1646. }
  1647. if ($DEBUG) {
  1648. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1649. }
  1650. } elsif ($DEBUG) {
  1651. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1652. }
  1653. }
  1654. }
  1655. # Output
  1656. foreach my $episode (keys(%{ $SERIES->{'tors_hash'} })) {
  1657. if (defined($urls{$episode})) {
  1658. $urls{$episode} = resolveTrackers($urls{$episode});
  1659. push(@output, $urls{$episode});
  1660. if ($CONFIG->{'SYSLOG'}) {
  1661. syslog(LOG_NOTICE, $SERIES->{'name'} . ': ' . getHash($urls{$episode}));
  1662. }
  1663. if ($DEBUG) {
  1664. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1665. }
  1666. } elsif ($DEBUG) {
  1667. print STDERR 'No URL for: ' . $episode . "\n";
  1668. }
  1669. }
  1670. return \@output;
  1671. }
  1672. sub splitTags($$$$) {
  1673. my ($content, $tag, $header, $match) = @_;
  1674. # Find each tag element
  1675. my @out = ();
  1676. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1677. foreach my $part (@parts) {
  1678. # Trim trailing tags and skip things that aren't complete tags
  1679. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1680. if ($DEBUG > 2) {
  1681. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1682. }
  1683. next;
  1684. }
  1685. # Skip headers
  1686. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1687. if ($DEBUG > 2) {
  1688. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1689. }
  1690. next;
  1691. }
  1692. # Skip non-matches
  1693. if (defined($match) && !($part =~ m/${match}/i)) {
  1694. if ($DEBUG > 2) {
  1695. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1696. }
  1697. next;
  1698. }
  1699. # Save good tags
  1700. push(@out, $part);
  1701. }
  1702. return @out;
  1703. }
  1704. # Extract season
  1705. sub findSE($) {
  1706. my ($name) = @_;
  1707. my $season = 0;
  1708. my $episode = 0;
  1709. my $seasonBlock = '';
  1710. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1711. $seasonBlock = $1;
  1712. my ($month, $day);
  1713. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1714. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1715. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1716. $seasonBlock = $1;
  1717. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1718. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1719. $seasonBlock = $1;
  1720. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1721. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1722. $seasonBlock = $1;
  1723. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1724. }
  1725. # Return something valid and INTy or UNDEF
  1726. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1727. if ($DEBUG) {
  1728. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1729. }
  1730. $season = undef();
  1731. $episode = undef();
  1732. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1733. # Episode-by-date
  1734. $season = int($season);
  1735. } else {
  1736. # Catchall
  1737. # This will warn and return undef() (which is valid) on error
  1738. $season = int($season);
  1739. $episode = int($episode);
  1740. }
  1741. return ($season, $episode);
  1742. }
  1743. sub initSources() {
  1744. my %sources = ();
  1745. # NZBplanet.net
  1746. if ($CONFIG->{'SOURCES'}->{'PLANET'}) {
  1747. my @proxies = ('api.nzbplanet.net/api');
  1748. my $source = findProxy(\@proxies, '\bNzbplanet\b');
  1749. if ($source && exists($CONFIG->{'PLANET_APIKEY'}) && $CONFIG->{'PLANET_APIKEY'}) {
  1750. $source->{'weight'} = 1.00;
  1751. $source->{'quote'} = 0;
  1752. $source->{'search_exclude'} = 0;
  1753. $source->{'search_suffix'} = '';
  1754. $source->{'custom_search'} = sub ($$$$) {
  1755. my ($urls, $series, $season, $episode) = @_;
  1756. my $url =
  1757. $source->{'search_url'}
  1758. . '?o=json&t=tvsearch&q='
  1759. . $series
  1760. . '&season='
  1761. . $season . '&ep='
  1762. . $episode
  1763. . '&apikey='
  1764. . $CONFIG->{'PLANET_APIKEY'};
  1765. push(@{$urls}, $url);
  1766. };
  1767. $sources{'PLANET'} = $source;
  1768. }
  1769. }
  1770. # NZB.is
  1771. if ($CONFIG->{'SOURCES'}->{'IS'}) {
  1772. my @proxies = ('nzb.is/api');
  1773. my $source = findProxy(\@proxies, '\bnzb\.is\b');
  1774. if ($source && exists($CONFIG->{'IS_APIKEY'}) && $CONFIG->{'IS_APIKEY'}) {
  1775. $source->{'weight'} = 1.00;
  1776. $source->{'quote'} = 0;
  1777. $source->{'search_exclude'} = 0;
  1778. $source->{'search_suffix'} = '';
  1779. $source->{'custom_search'} = sub ($$$$) {
  1780. my ($urls, $series, $season, $episode) = @_;
  1781. my $url =
  1782. $source->{'search_url'}
  1783. . '?o=json&t=tvsearch&q='
  1784. . $series
  1785. . '&season='
  1786. . $season . '&ep='
  1787. . $episode
  1788. . '&apikey='
  1789. . $CONFIG->{'IS_APIKEY'};
  1790. push(@{$urls}, $url);
  1791. };
  1792. $sources{'IS'} = $source;
  1793. }
  1794. }
  1795. # Usenet Crawler
  1796. if ($CONFIG->{'SOURCES'}->{'UC'}) {
  1797. my @proxies = ('www.usenet-crawler.com/api');
  1798. my $source = findProxy(\@proxies, '\busenet-crawler\b');
  1799. if ($source && exists($CONFIG->{'UC_APIKEY'}) && $CONFIG->{'UC_APIKEY'}) {
  1800. $source->{'weight'} = 1.00;
  1801. $source->{'quote'} = 0;
  1802. $source->{'search_exclude'} = 0;
  1803. $source->{'search_suffix'} = '';
  1804. $source->{'custom_search'} = sub ($$$$) {
  1805. my ($urls, $series, $season, $episode) = @_;
  1806. my $url =
  1807. $source->{'search_url'}
  1808. . '?o=json&t=tvsearch&q='
  1809. . $series
  1810. . '&season='
  1811. . $season . '&ep='
  1812. . $episode
  1813. . '&apikey='
  1814. . $CONFIG->{'UC_APIKEY'};
  1815. push(@{$urls}, $url);
  1816. };
  1817. $sources{'UC'} = $source;
  1818. }
  1819. }
  1820. # NZB Cat
  1821. if ($CONFIG->{'SOURCES'}->{'NCAT'}) {
  1822. my @proxies = ('nzb.cat/api');
  1823. my $source = findProxy(\@proxies, '\bforgottenpassword\b');
  1824. if ($source && exists($CONFIG->{'NCAT_APIKEY'}) && $CONFIG->{'NCAT_APIKEY'}) {
  1825. $source->{'weight'} = 1.00;
  1826. $source->{'quote'} = 0;
  1827. $source->{'search_exclude'} = 0;
  1828. $source->{'search_suffix'} = '';
  1829. $source->{'custom_search'} = sub ($$$$) {
  1830. my ($urls, $series, $season, $episode) = @_;
  1831. my $url =
  1832. $source->{'search_url'}
  1833. . '?o=json&t=tvsearch&q='
  1834. . $series
  1835. . '&season='
  1836. . $season . '&ep='
  1837. . $episode
  1838. . '&apikey='
  1839. . $CONFIG->{'NCAT_APIKEY'};
  1840. push(@{$urls}, $url);
  1841. };
  1842. $sources{'NCAT'} = $source;
  1843. }
  1844. }
  1845. # The Pirate Bay
  1846. if ($CONFIG->{'SOURCES'}->{'TPB'}) {
  1847. my @proxies = ('thepiratebay.org/search/', 'tpb.unblocked.co/search/');
  1848. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1849. if ($source) {
  1850. $source->{'weight'} = 1.00;
  1851. $source->{'quote'} = 0;
  1852. $source->{'search_exclude'} = 1;
  1853. $source->{'search_suffix'} = '/0/7/0';
  1854. $sources{'TPB'} = $source;
  1855. }
  1856. }
  1857. # ISOhunt
  1858. if ($CONFIG->{'SOURCES'}->{'ISO'}) {
  1859. my @proxies = ('isohunt.to/torrents/?ihq=', 'isohunters.net/torrents/?ihq=');
  1860. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1861. if ($source) {
  1862. $source->{'weight'} = 0.75;
  1863. $source->{'quote'} = 1;
  1864. $source->{'search_exclude'} = 1;
  1865. $source->{'search_suffix'} = '';
  1866. $sources{'ISO'} = $source;
  1867. }
  1868. }
  1869. # Kickass
  1870. if ($CONFIG->{'SOURCES'}->{'KICK'}) {
  1871. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1872. my $source = findProxy(\@proxies, '/search.php');
  1873. if ($source) {
  1874. $source->{'weight'} = 1.00;
  1875. $source->{'quote'} = 1;
  1876. $source->{'search_exclude'} = 1;
  1877. $source->{'search_suffix'} = '/';
  1878. $sources{'KICK'} = $source;
  1879. }
  1880. }
  1881. # Torrentz
  1882. if ($CONFIG->{'SOURCES'}->{'Z'}) {
  1883. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1884. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1885. if ($source) {
  1886. $source->{'weight'} = 1.00;
  1887. $source->{'quote'} = 1;
  1888. $source->{'search_exclude'} = 1;
  1889. $source->{'search_suffix'} = '';
  1890. if (!$SERIES->{'no_quality_checks'}) {
  1891. $source->{'search_suffix'} = '+peer+%3E+' . $CONFIG->{'MIN_COUNT'};
  1892. }
  1893. $sources{'Z'} = $source;
  1894. }
  1895. }
  1896. # ExtraTorrent
  1897. if ($CONFIG->{'SOURCES'}->{'ET'}) {
  1898. my @proxies = (
  1899. 'extra.to/search/?search=', 'etmirror.com/search/?search=',
  1900. 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search='
  1901. );
  1902. my $source = findProxy(\@proxies, '/search/');
  1903. if ($source) {
  1904. $source->{'weight'} = 1.00;
  1905. $source->{'quote'} = 1;
  1906. $source->{'search_exclude'} = 0;
  1907. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1908. $source->{'search_url'} = 'phantomjs:' . $source->{'search_url'};
  1909. $sources{'ET'} = $source;
  1910. }
  1911. }
  1912. # Sanity check
  1913. if (scalar(keys(%sources)) < 1) {
  1914. die("No sources available\n");
  1915. }
  1916. return \%sources;
  1917. }
  1918. sub findProxy($$) {
  1919. my ($proxies, $match) = @_;
  1920. # Automatically select a proxy
  1921. my $host = '';
  1922. my $protocol = '';
  1923. my $search_url = '';
  1924. foreach my $url (@{$proxies}) {
  1925. my $path;
  1926. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1927. if (!$protocol) {
  1928. $protocol = $CONFIG->{'PROTOCOL'};
  1929. }
  1930. if (!$host) {
  1931. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1932. next;
  1933. }
  1934. my ($content, $code) = fetch($protocol . '://' . $host, undef(), 1);
  1935. if ($code == 200 && $content =~ m/${match}/i) {
  1936. $search_url = $protocol . '://' . $host . $path;
  1937. last;
  1938. } elsif ($DEBUG) {
  1939. print STDERR 'Proxy not available: ' . $host . "\n";
  1940. if ($DEBUG > 1) {
  1941. print STDERR $content . "\n";
  1942. }
  1943. }
  1944. }
  1945. # Return the search data if at least one proxy is up
  1946. if ($search_url) {
  1947. my %tmp = (
  1948. 'protocol' => $protocol,
  1949. 'host' => $host,
  1950. 'search_url' => $search_url,
  1951. );
  1952. return \%tmp;
  1953. }
  1954. # Return undef if we didn't find any working proxies
  1955. return undef();
  1956. }
  1957. sub fetch($;$$) {
  1958. my ($url, $file, $nocheck) = @_;
  1959. if ($DEBUG > 1) {
  1960. print STDERR 'Fetch: ' . $url . "\n";
  1961. }
  1962. # Allow usage with short names
  1963. if ($file && !($file =~ /^\//)) {
  1964. $file = '/tmp/findTorrent-' . $file;
  1965. }
  1966. # Random delay
  1967. if ($DEBUG > 1) {
  1968. sleep($CONFIG->{'SLEEP'} * 0.25);
  1969. } else {
  1970. sleep($CONFIG->{'DELAY'} * (rand($CONFIG->{'SLEEP'}) + ($CONFIG->{'SLEEP'} / 2)));
  1971. }
  1972. # Allow JS processing
  1973. if ($url =~ /^phantomjs\:\s*(\S.*)$/i) {
  1974. return phantomFetch($1, $file);
  1975. }
  1976. # Fetch object
  1977. if (!$FETCH) {
  1978. if (!$COOKIES) {
  1979. $COOKIES = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  1980. }
  1981. $FETCH = Fetch->new(
  1982. 'cookiefile' => $COOKIES,
  1983. 'timeout' => $CONFIG->{'TIMEOUT'},
  1984. 'uas' => $CONFIG->{'UA'}
  1985. );
  1986. }
  1987. # Debug as requested
  1988. if ($DEBUG > 1 && $file) {
  1989. $FETCH->file($file);
  1990. } else {
  1991. $FETCH->file('');
  1992. }
  1993. # Standard fetch
  1994. $FETCH->url($url);
  1995. if ($nocheck) {
  1996. $FETCH->fetch('nocheck' => 1);
  1997. } else {
  1998. $FETCH->fetch();
  1999. }
  2000. return (scalar($FETCH->content()), $FETCH->status_code());
  2001. }
  2002. sub phantomFetch($$) {
  2003. my ($url, $file) = @_;
  2004. # Init
  2005. if (!$SCRIPT) {
  2006. $SCRIPT = mktemp('/tmp/findTorrent.phantom.XXXXXXXX');
  2007. open(my $fh, '>', $SCRIPT)
  2008. or die('Unable to open PhantomJS script file: ' . $! . "\n");
  2009. print $fh $CONFIG->{'PHANTOM_CONFIG'};
  2010. close($fh);
  2011. }
  2012. # Capture STDOUT, drop STDERR
  2013. my @cmd = ($CONFIG->{'PHANTOM_BIN'}, $SCRIPT, $url);
  2014. my ($content, undef(), undef()) = capture { system(@cmd); };
  2015. # Debug as requested
  2016. if ($DEBUG > 1 && $file) {
  2017. open(my $fh, '>', $file)
  2018. or warn('Unable to open phantom debug file: ' . $! . "\n");
  2019. if ($fh) {
  2020. print $fh $content;
  2021. close($fh);
  2022. }
  2023. }
  2024. # Try to get the response status code, fake one if we cannot
  2025. my ($code) = $content =~ /^(\d\d\d)$/m;
  2026. if (!defined($code)) {
  2027. warn("Unable to retrive HTTP status code. Faking success...\n");
  2028. $code = 200;
  2029. }
  2030. return ($content, $code);
  2031. }