findTorrent.pl 59 KB

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