findTorrent.pl 40 KB

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