findTorrent.pl 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  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(), 'magnet\:');
  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. # Find the magnet URL
  842. my ($url) = $tr =~ /\<a\s+href=\"(magnet\:[^\"]+)\"/i;
  843. if (!defined($url) || length($url) < 1) {
  844. if ($DEBUG) {
  845. print STDERR "Skipping TR with no magnet URL\n";
  846. }
  847. next;
  848. }
  849. $url = decode_entities($url);
  850. # Extract the season and episode numbers
  851. my ($fileSeason, $episode) = findSE($title);
  852. # Count the sum of seeders and leachers
  853. my $seeds = 0;
  854. my $leaches = 0;
  855. if ($tr =~ /\<td\s+class=\"sy\">(\d+)\<\/td\>/) {
  856. $seeds = $1;
  857. }
  858. if ($tr =~ /\<td\s+class=\"ly\">(\d+)\<\/td\>/) {
  859. $leaches = $1;
  860. }
  861. # Extract the size (from separate column or inline)
  862. my $size = 0;
  863. my $unit = 'M';
  864. if ($tr =~ /\<td\>(\d+(?:\.\d+)?)\&nbsp\;(G|M)B\<\/td\>/) {
  865. $size = $1;
  866. $unit = $2;
  867. }
  868. if ($unit eq 'G') {
  869. $size *= 1024;
  870. }
  871. $size = int($size);
  872. if ($DEBUG) {
  873. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  874. }
  875. # Save the extracted data
  876. my %tor = (
  877. 'title' => $title,
  878. 'season' => $fileSeason,
  879. 'episode' => $episode,
  880. 'seeds' => $seeds,
  881. 'leaches' => $leaches,
  882. 'size' => $size,
  883. 'url' => $url,
  884. 'source' => 'ET'
  885. );
  886. push(@tors, \%tor);
  887. }
  888. } elsif ($content =~ /\<title\>Sorry/) {
  889. if ($DEBUG) {
  890. print STDERR "ISO offline\n";
  891. }
  892. } elsif ($content =~ /Database\s+maintenance/i) {
  893. if ($DEBUG) {
  894. print STDERR "TPB offline\n";
  895. }
  896. } elsif ($content =~ /^\s*$/) {
  897. if ($DEBUG) {
  898. print STDERR "Source returned no content\n";
  899. }
  900. } else {
  901. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  902. }
  903. }
  904. # Handle JSON content
  905. foreach my $content (@json_content) {
  906. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  907. }
  908. # Filter for size/count/etc.
  909. my %tors = ();
  910. my $showRegex = undef();
  911. {
  912. my $showClean = $show;
  913. $showClean =~ s/[\"\']//g;
  914. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  915. $showRegex = qr/^${showClean}[\W_]/i;
  916. }
  917. foreach my $tor (@tors) {
  918. # Extract the BTIH, if available
  919. getHash($tor);
  920. # Skip files that are in the torrent excludes list
  921. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  922. if ($DEBUG) {
  923. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  924. }
  925. next;
  926. }
  927. # Skip files that don't start with our show title
  928. if (!($tor->{'title'} =~ $showRegex)) {
  929. if ($DEBUG) {
  930. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  931. }
  932. next;
  933. # Skip pre-air files
  934. } elsif ($tor->{'title'} =~ /preair/i) {
  935. if ($DEBUG) {
  936. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  937. }
  938. next;
  939. # Skip SWESUB files
  940. } elsif ($tor->{'title'} =~ /swesub/i) {
  941. if ($DEBUG) {
  942. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  943. }
  944. next;
  945. # Skip .rus. files
  946. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  947. if ($DEBUG) {
  948. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  949. }
  950. next;
  951. # Skip German files
  952. } elsif ($tor->{'title'} =~ /german/i) {
  953. if ($DEBUG) {
  954. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  955. }
  956. next;
  957. # Skip French files
  958. } elsif ($tor->{'title'} =~ /french/i) {
  959. if ($DEBUG) {
  960. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  961. }
  962. next;
  963. # Skip Spanish files
  964. } elsif ($tor->{'title'} =~ /Español/i) {
  965. if ($DEBUG) {
  966. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  967. }
  968. next;
  969. # Skip Castellano files
  970. } elsif ($tor->{'title'} =~ /Castellano/i) {
  971. if ($DEBUG) {
  972. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  973. }
  974. next;
  975. # Skip unedited files
  976. } elsif ($tor->{'title'} =~ /unedited/i) {
  977. if ($DEBUG) {
  978. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  979. }
  980. next;
  981. }
  982. # Skip files that contain a word from the series exclude list
  983. my $exclude = undef();
  984. foreach my $ex (keys(%TITLE_EXCLUDES)) {
  985. $ex = quotemeta($ex);
  986. if ($tor->{'title'} =~ m/${ex}/i) {
  987. $exclude = $ex;
  988. last;
  989. }
  990. }
  991. if (defined($exclude)) {
  992. if ($DEBUG) {
  993. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  994. }
  995. next;
  996. }
  997. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  998. if (!$CUSTOM_SEARCH) {
  999. # Skip files that don't contain the right season number
  1000. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  1001. if ($DEBUG) {
  1002. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  1003. }
  1004. next;
  1005. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  1006. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} })
  1007. || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS))
  1008. {
  1009. if ($DEBUG) {
  1010. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  1011. }
  1012. next;
  1013. }
  1014. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  1015. # Skip files that don't match the regex
  1016. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  1017. if ($DEBUG) {
  1018. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  1019. }
  1020. next;
  1021. }
  1022. }
  1023. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  1024. if (!$NO_QUALITY_CHECKS) {
  1025. # Skip torrents with too few seeders/leachers
  1026. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  1027. if ($DEBUG) {
  1028. print STDERR 'Skipping file: Insufficient seeder/leacher count ('
  1029. . $tor->{'seeds'} . '/'
  1030. . $tor->{'leaches'} . '): '
  1031. . $tor->{'title'} . "\n";
  1032. }
  1033. next;
  1034. # Skip torrents with unusual seed/leach ratios
  1035. } elsif ($tor->{'seeds'} > 1
  1036. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  1037. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  1038. {
  1039. if ($DEBUG) {
  1040. print STDERR 'Skipping file: Unusual seeder/leacher ratio ('
  1041. . $tor->{'seeds'} . '/'
  1042. . $tor->{'leaches'} . '): '
  1043. . $tor->{'title'} . "\n";
  1044. }
  1045. next;
  1046. # Skip torrents that are too small
  1047. } elsif ($tor->{'size'} < $MIN_SIZE) {
  1048. if ($DEBUG) {
  1049. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1050. }
  1051. next;
  1052. }
  1053. }
  1054. # Save good torrents
  1055. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  1056. if ($DEBUG) {
  1057. print STDERR 'Possible URL ('
  1058. . $tor->{'seeds'} . '/'
  1059. . $tor->{'leaches'}
  1060. . ' seeds/leaches, '
  1061. . $tor->{'size'}
  1062. . ' MiB): '
  1063. . $tor->{'title'} . "\n";
  1064. }
  1065. }
  1066. # Find the average torrent size for each episode
  1067. my %size = ();
  1068. {
  1069. my %max = ();
  1070. my %avg = ();
  1071. foreach my $episode (keys(%tors)) {
  1072. my $count = 0;
  1073. $avg{$episode} = 0.001;
  1074. $max{$episode} = 0.001;
  1075. foreach my $tor (@{ $tors{$episode} }) {
  1076. $count++;
  1077. $avg{$episode} += $tor->{'size'};
  1078. if ($tor->{'size'} > $max{$episode}) {
  1079. $max{$episode} = $tor->{'size'};
  1080. }
  1081. }
  1082. if ($count > 0) {
  1083. $avg{$episode} /= $count;
  1084. }
  1085. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1086. if ($DEBUG) {
  1087. print STDERR 'Episode '
  1088. . $episode
  1089. . ' max/avg/cmp size: '
  1090. . int($max{$episode}) . '/'
  1091. . int($avg{$episode}) . '/'
  1092. . int($size{$episode})
  1093. . " MiB\n";
  1094. }
  1095. }
  1096. }
  1097. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1098. foreach my $episode (keys(%tors)) {
  1099. foreach my $tor (@{ $tors{$episode} }) {
  1100. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1101. # Start with the peer count
  1102. $tor->{'adj_count'} = $count;
  1103. # Adjust based on file size
  1104. {
  1105. my $size_ratio = $tor->{'size'} / $size{$episode};
  1106. if ($tor->{'size'} >= $size{$episode}) {
  1107. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  1108. } else {
  1109. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  1110. }
  1111. }
  1112. # Adjust based on title contents
  1113. if ($tor->{'title'} =~ /Subtitulado/i) {
  1114. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  1115. }
  1116. # Truncate to an integer
  1117. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1118. if ($DEBUG) {
  1119. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1120. }
  1121. }
  1122. }
  1123. # Pick the best-adjusted-count torrent for each episode
  1124. my %urls = ();
  1125. foreach my $episode (keys(%tors)) {
  1126. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  1127. my $max = undef();
  1128. foreach my $tor (@sorted) {
  1129. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1130. if ($urls{$episode} = resolveSecondary($tor)) {
  1131. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1132. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1133. next;
  1134. }
  1135. $max = $tor->{'adj_count'};
  1136. }
  1137. if ($DEBUG) {
  1138. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1139. }
  1140. } elsif ($DEBUG) {
  1141. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1142. }
  1143. }
  1144. }
  1145. # Output
  1146. foreach my $episode (keys(%tors)) {
  1147. if (defined($urls{$episode})) {
  1148. $urls{$episode} = resolveTrackers($urls{$episode});
  1149. print $urls{$episode} . "\n";
  1150. if ($SYSLOG) {
  1151. syslog(LOG_NOTICE, $show . ': ' . getHash($urls{$episode}));
  1152. }
  1153. if ($DEBUG) {
  1154. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1155. }
  1156. } elsif ($DEBUG) {
  1157. print STDERR 'No URL for: ' . $episode . "\n";
  1158. }
  1159. }
  1160. # Cleanup
  1161. unlink($cookies);
  1162. unlink($script);
  1163. if ($SYSLOG) {
  1164. closelog();
  1165. }
  1166. exit(0);
  1167. sub getHash($) {
  1168. my ($tor) = @_;
  1169. my $url;
  1170. # Allow either a URL or a tor hashref
  1171. if (ref($tor) eq 'HASH') {
  1172. $url = $tor->{'url'};
  1173. } else {
  1174. $url = $tor;
  1175. undef($tor);
  1176. }
  1177. # Extract the BTIH hash, if available
  1178. my $hash = undef();
  1179. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1180. $hash = lc($1);
  1181. }
  1182. # Save back to the tor, if provided
  1183. if (defined($tor)) {
  1184. $tor->{'hash'} = lc($hash);
  1185. }
  1186. # Always return the hash, or undef() if none can be found
  1187. return $hash;
  1188. }
  1189. # Resolve secondary URLs
  1190. sub resolveSecondary($) {
  1191. my ($tor) = @_;
  1192. # Fetch the torrent-specific page and extract the magent link
  1193. if ($tor->{'source'} eq 'ISO') {
  1194. if ($DEBUG) {
  1195. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  1196. $fetch->file('/tmp/findTorrent-secondary.html');
  1197. }
  1198. sleep($DELAY * (rand(2) + 0.5));
  1199. $fetch->url($tor->{'url'});
  1200. $fetch->fetch();
  1201. if ($fetch->status_code() != 200) {
  1202. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1203. goto OUT;
  1204. }
  1205. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1206. if (!defined($magnet) || length($magnet) < 1) {
  1207. if ($DEBUG) {
  1208. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1209. }
  1210. goto OUT;
  1211. }
  1212. $tor->{'url'} = decode_entities($magnet);
  1213. }
  1214. # Extract the hash
  1215. getHash($tor);
  1216. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1217. if ($DEBUG) {
  1218. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1219. }
  1220. goto OUT;
  1221. }
  1222. OUT:
  1223. return $tor->{'url'};
  1224. }
  1225. sub resolveTrackers($) {
  1226. my ($url) = @_;
  1227. # Always append a few static trackers to the URI
  1228. if ($url =~ /^magnet\:/i) {
  1229. foreach my $tracker (@TRACKERS) {
  1230. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1231. my $match = quotemeta($arg);
  1232. if (!($url =~ /${match}/)) {
  1233. $url .= $arg;
  1234. }
  1235. }
  1236. }
  1237. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1238. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1239. my $hash = lc($1);
  1240. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1241. my $hashURL = $baseURL . '/' . $hash;
  1242. if ($DEBUG) {
  1243. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1244. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1245. }
  1246. sleep($DELAY * (rand(2) + 0.5));
  1247. $fetch->url($hashURL);
  1248. $fetch->fetch();
  1249. if ($fetch->status_code() != 200) {
  1250. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1251. return $url;
  1252. }
  1253. # Parse out and fetch the tracker list URL
  1254. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1255. if (!defined($list)) {
  1256. if ($DEBUG) {
  1257. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1258. }
  1259. return $url;
  1260. }
  1261. my $listURL = $baseURL . $list;
  1262. if ($DEBUG) {
  1263. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1264. $fetch->file('/tmp/findTorrent-tracker.html');
  1265. }
  1266. sleep($DELAY * (rand(2) + 0.5));
  1267. $fetch->url($listURL);
  1268. $fetch->fetch();
  1269. if ($fetch->status_code() != 200) {
  1270. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1271. return $url;
  1272. }
  1273. # Parse the tracker list and append our URL
  1274. foreach my $line ($fetch->content()) {
  1275. if ($line =~ /^\s*$/) {
  1276. next;
  1277. }
  1278. $line =~ s/^\s+//;
  1279. $line =~ s/\s+$//;
  1280. if ($line =~ /^(?:http|udp)\:/i) {
  1281. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1282. my $match = quotemeta($arg);
  1283. if (!($url =~ /${match}/)) {
  1284. if ($DEBUG) {
  1285. print STDERR 'Adding tracker: ' . $line . "\n";
  1286. }
  1287. $url .= $arg;
  1288. }
  1289. } else {
  1290. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1291. }
  1292. }
  1293. }
  1294. return $url;
  1295. }
  1296. sub splitTags($$$$) {
  1297. my ($content, $tag, $header, $match) = @_;
  1298. # Find each tag element
  1299. my @out = ();
  1300. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1301. foreach my $part (@parts) {
  1302. # Trim trailing tags and skip things that aren't complete tags
  1303. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1304. if ($DEBUG > 1) {
  1305. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1306. }
  1307. next;
  1308. }
  1309. # Skip headers
  1310. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1311. if ($DEBUG > 2) {
  1312. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1313. }
  1314. next;
  1315. }
  1316. # Skip non-matches
  1317. if (defined($match) && !($part =~ m/${match}/i)) {
  1318. if ($DEBUG > 2) {
  1319. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1320. }
  1321. next;
  1322. }
  1323. # Save good tags
  1324. push(@out, $part);
  1325. }
  1326. return @out;
  1327. }
  1328. # Extract season
  1329. sub findSE($) {
  1330. my ($name) = @_;
  1331. my $season = 0;
  1332. my $episode = 0;
  1333. my $seasonBlock = '';
  1334. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1335. $seasonBlock = $1;
  1336. my ($month, $day);
  1337. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1338. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1339. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1340. $seasonBlock = $1;
  1341. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1342. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1343. $seasonBlock = $1;
  1344. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1345. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1346. $seasonBlock = $1;
  1347. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1348. }
  1349. # Return something valid and INTy or UNDEF
  1350. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1351. if ($DEBUG) {
  1352. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1353. }
  1354. $season = undef();
  1355. $episode = undef();
  1356. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1357. # Episode-by-date
  1358. $season = int($season);
  1359. } else {
  1360. # Catchall
  1361. # This will warn and return undef() (which is valid) on error
  1362. $season = int($season);
  1363. $episode = int($episode);
  1364. }
  1365. return ($season, $episode);
  1366. }
  1367. sub initSources() {
  1368. my %sources = ();
  1369. # The Pirate Bay
  1370. if ($ENABLE_SOURCE{'TPB'}) {
  1371. my @proxies = ('thepiratebay.org/search/', 'pirateproxy.la/search/', 'tpb.unblocked.co/search/');
  1372. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1373. if ($source) {
  1374. $source->{'weight'} = 1.00;
  1375. $source->{'quote'} = 0;
  1376. $source->{'search_exclude'} = 1;
  1377. $source->{'search_suffix'} = '/0/7/0';
  1378. $sources{'TPB'} = $source;
  1379. }
  1380. }
  1381. # ISOhunt
  1382. if ($ENABLE_SOURCE{'ISO'}) {
  1383. my @proxies = ('isohunt.to/torrents/?ihq=', 'isohunters.net/torrents/?ihq=');
  1384. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1385. if ($source) {
  1386. $source->{'weight'} = 0.75;
  1387. $source->{'quote'} = 1;
  1388. $source->{'search_exclude'} = 1;
  1389. $source->{'search_suffix'} = '';
  1390. $sources{'ISO'} = $source;
  1391. }
  1392. }
  1393. # Kickass
  1394. if ($ENABLE_SOURCE{'KICK'}) {
  1395. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1396. my $source = findProxy(\@proxies, '/search.php');
  1397. if ($source) {
  1398. $source->{'weight'} = 1.00;
  1399. $source->{'quote'} = 1;
  1400. $source->{'search_exclude'} = 1;
  1401. $source->{'search_suffix'} = '/';
  1402. $sources{'KICK'} = $source;
  1403. }
  1404. }
  1405. # Torrentz
  1406. if ($ENABLE_SOURCE{'Z'}) {
  1407. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1408. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1409. if ($source) {
  1410. $source->{'weight'} = 1.00;
  1411. $source->{'quote'} = 1;
  1412. $source->{'search_exclude'} = 1;
  1413. $source->{'search_suffix'} = '';
  1414. if (!$NO_QUALITY_CHECKS) {
  1415. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1416. }
  1417. $sources{'Z'} = $source;
  1418. }
  1419. }
  1420. # ExtraTorrent
  1421. if ($ENABLE_SOURCE{'ET'}) {
  1422. my @proxies = (
  1423. 'extratorrent.cc/search/?search=', 'etmirror.com/search/?search=',
  1424. 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search='
  1425. );
  1426. my $source = findProxy(\@proxies, '/search/');
  1427. if ($source) {
  1428. $source->{'weight'} = 1.00;
  1429. $source->{'quote'} = 1;
  1430. $source->{'search_exclude'} = 0;
  1431. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1432. $sources{'ET'} = $source;
  1433. }
  1434. }
  1435. # Sanity check
  1436. if (scalar(keys(%sources)) < 1) {
  1437. die("No sources available\n");
  1438. }
  1439. return \%sources;
  1440. }
  1441. sub findProxy($$) {
  1442. my ($proxies, $match) = @_;
  1443. # Automatically select a proxy
  1444. my $host = '';
  1445. my $protocol = '';
  1446. my $search_url = '';
  1447. foreach my $url (@{$proxies}) {
  1448. my $path;
  1449. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1450. if (!$protocol) {
  1451. $protocol = $PROTOCOL;
  1452. }
  1453. if (!$host) {
  1454. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1455. next;
  1456. }
  1457. $fetch->url($protocol . '://' . $host);
  1458. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1459. $search_url = $protocol . '://' . $host . $path;
  1460. last;
  1461. } elsif ($DEBUG) {
  1462. print STDERR 'Proxy not available: ' . $host . "\n";
  1463. if ($DEBUG > 1) {
  1464. print STDERR $fetch->content() . "\n";
  1465. }
  1466. }
  1467. }
  1468. # Return the search data if at least one proxy is up
  1469. if ($search_url) {
  1470. my %tmp = (
  1471. 'protocol' => $protocol,
  1472. 'host' => $host,
  1473. 'search_url' => $search_url,
  1474. );
  1475. return \%tmp;
  1476. }
  1477. # Return undef if we didn't find any working proxies
  1478. return undef();
  1479. }
  1480. sub phantomFetch($) {
  1481. my ($url) = @_;
  1482. # Capture STDOUT, drop STDERR
  1483. my @cmd = ($PHANTOM, $script, $url);
  1484. my ($content, undef(), undef()) = capture { system(@cmd); };
  1485. # Try to get the response status code, fake one if we cannot
  1486. my ($code) = $content =~ /^(\d\d\d)$/m;
  1487. if (!defined($code)) {
  1488. warn("Unable to retrive HTTP status code. Faking success...\n");
  1489. $code = 200;
  1490. }
  1491. return ($content, $code);
  1492. }