findTorrent.pl 43 KB

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