findTorrent.pl 48 KB

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