findTorrent.pl 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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' => 0, 'ISO' => 1, 'KICK' => 1, 'Z' => 1);
  16. # Selection parameters
  17. my $MIN_COUNT = 10;
  18. my $MIN_SIZE = 100;
  19. my $SIZE_BONUS = 7;
  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 = 4;
  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_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A';
  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 quality checks to be disabled
  170. if (-e $dir . '/no_quality_checks') {
  171. $NO_QUALITY_CHECKS = 1;
  172. }
  173. # Read the search excludes file, if any
  174. my $exclude = '';
  175. if (-e $dir . '/excludes') {
  176. local $/ = undef;
  177. open(EX, $dir . '/excludes')
  178. or die("Unable to open series excludes file: ${!}\n");
  179. my $ex = <EX>;
  180. close(EX);
  181. $ex =~ s/^\s+//;
  182. $ex =~ s/\s+$//;
  183. my @excludes = split(/\s*,\s*/, $ex);
  184. foreach my $ex (@excludes) {
  185. if (length($exclude)) {
  186. $exclude .= ' ';
  187. }
  188. $exclude .= '-"' . $ex . '"';
  189. }
  190. $exclude = uri_encode(' ' . $exclude);
  191. }
  192. # Setup our sources
  193. my $SOURCES = initSources();
  194. # Adjust the inter-page delay with respect to the number of unique sources
  195. $DELAY /= scalar(keys(%{$SOURCES}));
  196. # Handle custom searches
  197. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  198. # Note the custom search string
  199. $CUSTOM_SEARCH = 1;
  200. if ($DEBUG) {
  201. print STDERR "Custom search\n";
  202. }
  203. # Create the relevent search strings
  204. foreach my $key (keys(%{$SOURCES})) {
  205. my $source = $SOURCES->{$key};
  206. push(@urls, $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  207. }
  208. }
  209. # Handle search-by-date series
  210. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  211. # Note the search-by-date status
  212. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  213. $CUSTOM_SEARCH = 1;
  214. if ($DEBUG) {
  215. print STDERR "Find by date\n";
  216. }
  217. # Read the find-by-date string
  218. my $search_by_date = '';
  219. local ($/, *FH);
  220. open(FH, $dir . '/search_by_date')
  221. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  222. my $text = <FH>;
  223. close(FH);
  224. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  225. $search_by_date = $1;
  226. } else {
  227. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  228. }
  229. # Create search strings for each date in the range, unless the related file already exists
  230. my (%years, %months, %days) = ();
  231. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  232. # Calculate the date
  233. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  234. # Format as strings
  235. $year = sprintf('%04d', $year + 1900);
  236. $month = sprintf('%02d', $month + 1);
  237. $day = sprintf('%02d', $day);
  238. # Check for an existing file
  239. my $exists = 0;
  240. {
  241. my $season_dir = $dir . '/Season ' . $year;
  242. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  243. opendir(SEASON, $season_dir)
  244. or die('Unable to open season directory (' . $season_dir . '): ' . $! . "\n");
  245. while (my $file = readdir(SEASON)) {
  246. if ($file =~ $prefix) {
  247. $exists = 1;
  248. last;
  249. }
  250. }
  251. closedir(SEASON);
  252. }
  253. if ($exists) {
  254. next;
  255. }
  256. # Save all the date string components
  257. $years{$year} = 1;
  258. $months{$month} = 1;
  259. $days{$day} = 1;
  260. # Create the relevent search strings
  261. my $search_str = $search_by_date;
  262. $search_str =~ s/%Y/${year}/g;
  263. $search_str =~ s/%m/${month}/g;
  264. $search_str =~ s/%d/${day}/g;
  265. foreach my $key (keys(%{$SOURCES})) {
  266. my $source = $SOURCES->{$key};
  267. push(@urls, $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  268. }
  269. }
  270. # Build a date string matching regex
  271. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  272. $str .= '.*';
  273. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  274. $str .= '.*';
  275. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  276. $CUSTOM_SEARCH = qr/${str}/;
  277. }
  278. # Handle standard series
  279. if (scalar(@urls) < 1) {
  280. # Allow use of more number formats
  281. if (-e $dir . '/more_number_formats') {
  282. $MORE_NUMBER_FORMATS = 1;
  283. }
  284. # Allow the show name to be overriden
  285. {
  286. my $search_name = $dir . '/search_name';
  287. if (-e $search_name) {
  288. local ($/, *FH);
  289. open(FH, $search_name)
  290. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  291. my $text = <FH>;
  292. close(FH);
  293. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  294. $show = $1;
  295. } else {
  296. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  297. }
  298. }
  299. }
  300. if ($DEBUG) {
  301. print STDERR 'Searching with series title: ' . $show . "\n";
  302. }
  303. # Validate the season number
  304. if (!defined($season) || $season < 1 || $season > 2000) {
  305. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  306. }
  307. # Get the last episode number
  308. my $no_next = 0;
  309. my %episodes = ();
  310. my $highest = 0;
  311. opendir(SEASON, $dir . '/Season ' . $season)
  312. or die("Unable to open season directory: ${!}\n");
  313. while (my $file = readdir(SEASON)) {
  314. # Skip support files
  315. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  316. next;
  317. }
  318. # Check for a season_done file
  319. if ($file eq 'season_done') {
  320. $no_next = 1;
  321. next;
  322. }
  323. # Extract the episode number
  324. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  325. if (defined($num)) {
  326. $num = int($num);
  327. if ($DEBUG) {
  328. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  329. }
  330. # Record it
  331. $episodes{$num} = 1;
  332. # Track the highest episode number
  333. if ($num > $highest) {
  334. $highest = $num;
  335. }
  336. }
  337. }
  338. close(SEASON);
  339. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  340. if (!$no_next) {
  341. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  342. push(@need, $highest + $i);
  343. }
  344. }
  345. # Find any missing episodes
  346. for (my $i = 1 ; $i <= $highest ; $i++) {
  347. if (!$episodes{$i}) {
  348. push(@need, $i);
  349. }
  350. }
  351. if ($DEBUG) {
  352. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  353. }
  354. # Reverse the array for later matching
  355. foreach my $episode (@need) {
  356. $need{$episode} = 1;
  357. }
  358. # Construct a URL-friendly show name
  359. my $safeShow = $show;
  360. $safeShow =~ s/\s+\&\s+/ and /i;
  361. $safeShow =~ s/^\s*The\b//i;
  362. $safeShow =~ s/\s+\-\s+/ /g;
  363. $safeShow =~ s/[\'\:]//g;
  364. $safeShow =~ s/[^\w\"\-]+/ /g;
  365. $safeShow =~ s/^\s+//;
  366. $safeShow =~ s/\s+$//;
  367. $safeShow =~ s/\s\s+/ /g;
  368. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  369. $safeShow =~ s/\%20/\+/g;
  370. # Calculate possible name variations
  371. my @urlShowVarients = ();
  372. {
  373. # Default name
  374. push(@urlShowVarients, $safeShow);
  375. # Search for both "and" and "&"
  376. if ($safeShow =~ /\+and\+/i) {
  377. my $tmp = $safeShow;
  378. $tmp =~ s/\+and\+/\+%26\+/;
  379. push(@urlShowVarients, $tmp);
  380. }
  381. }
  382. # Construct the URL for each title varient of each needed episode
  383. foreach my $urlShow (@urlShowVarients) {
  384. foreach my $episode (@need) {
  385. my $episode_long = sprintf('%02d', $episode);
  386. my $season_long = sprintf('%02d', $season);
  387. foreach my $source (values(%{$SOURCES})) {
  388. # Use quotes around the show name if the source needs them
  389. my $quote = '%22';
  390. if (!$source->{'quote'}) {
  391. $quote = '';
  392. }
  393. # Calculate the compete search prefix and suffix to simplify later concatenations
  394. my $prefix = $source->{'search_url'} . $quote . $urlShow . $quote;
  395. my $suffix = $exclude;
  396. if ($source->{'search_suffix'}) {
  397. $suffix .= $source->{'search_suffix'};
  398. }
  399. # SXXEYY
  400. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  401. push(@urls, $url);
  402. # Extra searches for shows that have lazy/non-standard number formats
  403. if ($MORE_NUMBER_FORMATS) {
  404. # SXEY
  405. if ($season_long ne $season || $episode_long ne $episode) {
  406. $url = $prefix . '+s' . $season . 'e' . $episode . $exclude . $suffix;
  407. push(@urls, $url);
  408. }
  409. # SXX EYY
  410. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $exclude . $suffix;
  411. push(@urls, $url);
  412. # Season XX Episode YY
  413. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $exclude . $suffix;
  414. push(@urls, $url);
  415. # Series X Episode Y
  416. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $exclude . $suffix;
  417. push(@urls, $url);
  418. # SxEE
  419. $url = $prefix . '+' . $season . 'x' . $episode_long . $exclude . $suffix;
  420. push(@urls, $url);
  421. # Season X
  422. if ($NO_QUALITY_CHECKS) {
  423. $url = $prefix . '+Season+' . $season . $exclude . $suffix;
  424. push(@urls, $url);
  425. }
  426. }
  427. }
  428. }
  429. }
  430. }
  431. my @html_content = ();
  432. my @json_content = ();
  433. foreach my $url (@urls) {
  434. # Fetch the page
  435. my $errCount = 0;
  436. HTTP_ERR_LOOP: {
  437. if ($DEBUG) {
  438. print STDERR 'Searching with URL: ' . $url . "\n";
  439. $fetch->file('/tmp/findTorrent-lastPage.html');
  440. }
  441. sleep($DELAY * (rand(2) + 0.5));
  442. $fetch->url($url);
  443. $fetch->fetch('nocheck' => 1);
  444. # Check for useful errors
  445. if ($fetch->status_code() == 404) {
  446. if ($DEBUG) {
  447. print STDERR "Skipping content from 404 response\n";
  448. }
  449. next;
  450. }
  451. # Check for errors
  452. if ($fetch->status_code() != 200) {
  453. if ($fetch->status_code() >= 500 && $fetch->status_code() <= 599) {
  454. if ($errCount > $ERR_RETRIES) {
  455. print STDERR 'Unable to fetch URL: ' . $url . "\n";
  456. $errCount = 0;
  457. next;
  458. }
  459. if ($DEBUG) {
  460. print STDERR 'Retrying URL (' . $fetch->status_code() . '): ' . $url . "\n";
  461. }
  462. $errCount++;
  463. sleep($ERR_DELAY);
  464. redo HTTP_ERR_LOOP;
  465. } else {
  466. print STDERR 'Error fetching URL (' . $fetch->status_code() . '): ' . $url . "\n";
  467. }
  468. next;
  469. }
  470. }
  471. # Save the content, discriminating by data type
  472. if ($DEBUG) {
  473. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  474. }
  475. if ($fetch->content() =~ /^\s*{/) {
  476. my $json = eval { decode_json($fetch->content()); };
  477. if (defined($json) && ref($json)) {
  478. push(@json_content, \@{ $json->{'items'}->{'list'} });
  479. } elsif ($DEBUG) {
  480. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  481. }
  482. } else {
  483. push(@html_content, scalar($fetch->content()));
  484. }
  485. }
  486. # We need someplace to store parsed torrent data from the various sources
  487. my @tors = ();
  488. # Handle HTML content
  489. foreach my $content (@html_content) {
  490. if ($content =~ /\<title\>The Pirate Bay/i) {
  491. # Find TR elements from TPB
  492. my @trs = splitTags($content, 'TR', 'TH');
  493. foreach my $tr (@trs) {
  494. # Find the show title
  495. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  496. if (!defined($title) || length($title) < 1) {
  497. if ($DEBUG) {
  498. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  499. }
  500. next;
  501. }
  502. $title =~ s/^\s+//;
  503. # Extract the season and episode numbers
  504. my ($fileSeason, $episode) = findSE($title);
  505. # Extract the URL
  506. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  507. if (!defined($url) || length($url) < 1) {
  508. if ($DEBUG) {
  509. print STDERR "Skipping TR with no magnet URL\n";
  510. }
  511. next;
  512. }
  513. $url = decode_entities($url);
  514. # Count the sum of seeders and leachers
  515. my $seeds = 0;
  516. my $leaches = 0;
  517. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  518. $seeds = $1;
  519. $leaches = $2;
  520. }
  521. # Extract the size (from separate column or inline)
  522. my $size = 0;
  523. my $unit = 'M';
  524. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  525. $size = $1;
  526. $unit = $2;
  527. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  528. $size = $1;
  529. $unit = $2;
  530. }
  531. if ($unit eq 'G') {
  532. $size *= 1024;
  533. }
  534. $size = int($size);
  535. if ($DEBUG) {
  536. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  537. }
  538. # Save the extracted data
  539. my %tor = (
  540. 'title' => $title,
  541. 'season' => $fileSeason,
  542. 'episode' => $episode,
  543. 'seeds' => $seeds,
  544. 'leaches' => $leaches,
  545. 'size' => $size,
  546. 'url' => $url,
  547. 'source' => 'TPB'
  548. );
  549. push(@tors, \%tor);
  550. }
  551. } elsif ($content =~ /\<title\>[^\<\>]*\bisoHunt\b[^\<\>]*\<\/title\>/i) {
  552. # Find each TR element from ISOHunt
  553. my @trs = splitTags($content, 'TR', 'TH');
  554. foreach my $tr (@trs) {
  555. # Split each TD element from the row
  556. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  557. my $numCols = scalar(@tds) - 1;
  558. if ($numCols > 9 && $numCols < 8) {
  559. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  560. next;
  561. }
  562. # Skip sponsored results
  563. if ($tds[1] =~ /\bSponsored\b/i) {
  564. if ($DEBUG > 1) {
  565. print STDERR "Skipping sponsored result\n";
  566. }
  567. next;
  568. }
  569. # Find the torrent ID and show title
  570. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+)\/[^\"]*\"\>\<span\>([^\>]+)\<\/span\>/i;
  571. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  572. if ($DEBUG) {
  573. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  574. }
  575. next;
  576. }
  577. $title =~ s/^\s+//;
  578. # Extract the season and episode numbers
  579. my ($fileSeason, $episode) = findSE($title);
  580. # Extract the size
  581. my $size = 0;
  582. my $unit = 'M';
  583. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  584. $size = $1;
  585. $unit = $2;
  586. }
  587. if ($unit eq 'G') {
  588. $size *= 1024;
  589. }
  590. $size = int($size);
  591. # Count the sum of seeders and leachers
  592. my $seeds = 0;
  593. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  594. $seeds = $1;
  595. }
  596. my $leaches = 0;
  597. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  598. $leaches = $1;
  599. }
  600. # Fetch the detail page for the URL
  601. my $url = $SOURCES->{'ISO'}->{'protocol'} . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id . '/';
  602. if ($DEBUG) {
  603. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  604. }
  605. # Save the extracted data
  606. my %tor = (
  607. 'title' => $title,
  608. 'season' => $fileSeason,
  609. 'episode' => $episode,
  610. 'seeds' => $seeds,
  611. 'leaches' => $leaches,
  612. 'size' => $size,
  613. 'url' => $url,
  614. 'source' => 'ISO'
  615. );
  616. push(@tors, \%tor);
  617. }
  618. } elsif ($content =~ /KickassTorrents\<\/title\>/i) {
  619. # Find each TR element from Kickass
  620. my @trs = splitTags($content, 'TR', 'TH');
  621. foreach my $tr (@trs) {
  622. # Split each TD element from the row
  623. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  624. my $numCols = scalar(@tds) - 1;
  625. if ($numCols > 9 && $numCols < 8) {
  626. print STDERR 'Invalid KICK TR: ' . $tr . "\n";
  627. next;
  628. }
  629. # Skip empty results
  630. if ( $tds[1] =~ /\<h2\>Nothing found\!\<\/h2\>/i
  631. || $tds[1] =~ /\<p\>\<strong\>Page not found\<\/strong\>\<\/p\>/i)
  632. {
  633. if ($DEBUG) {
  634. print STDERR "Skipping empty TD\n";
  635. }
  636. next;
  637. }
  638. # Find the torrent title
  639. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  640. if (!defined($title) || length($title) < 1) {
  641. if ($DEBUG) {
  642. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  643. }
  644. next;
  645. }
  646. $title =~ s/^\s+//;
  647. # Find the torrent URL
  648. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  649. if (!defined($url) || length($url) < 1) {
  650. if ($DEBUG) {
  651. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  652. }
  653. next;
  654. }
  655. $url = decode_entities($url);
  656. # Extract the season and episode numbers
  657. my ($fileSeason, $episode) = findSE($title);
  658. # Extract the size
  659. my $size = 0;
  660. my $unit = 'M';
  661. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  662. $size = $1;
  663. $unit = $2;
  664. }
  665. if ($unit eq 'G') {
  666. $size *= 1024;
  667. }
  668. $size = int($size);
  669. # Count the sum of seeders and leachers
  670. my $seeds = 0;
  671. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  672. $seeds = $1;
  673. }
  674. my $leaches = 0;
  675. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  676. $leaches = $1;
  677. }
  678. if ($DEBUG) {
  679. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  680. }
  681. # Save the extracted data
  682. my %tor = (
  683. 'title' => $title,
  684. 'season' => $fileSeason,
  685. 'episode' => $episode,
  686. 'seeds' => $seeds,
  687. 'leaches' => $leaches,
  688. 'size' => $size,
  689. 'url' => $url,
  690. 'source' => 'KICK'
  691. );
  692. push(@tors, \%tor);
  693. }
  694. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  695. # We'll need to strip HTML
  696. my $hs = HTML::Strip->new();
  697. # Find each DL element from Torrentz
  698. my @dls = splitTags($content, 'DL', undef());
  699. foreach my $dl (@dls) {
  700. # Skip ads
  701. if ($dl =~ /\s+rel\=\"nofollow/i) {
  702. next;
  703. }
  704. # Find the torrent title
  705. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  706. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  707. if ($DEBUG) {
  708. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  709. }
  710. next;
  711. }
  712. $hash = lc($hash);
  713. $title = $hs->parse($title);
  714. $hs->eof;
  715. $title =~ s/^\s+//;
  716. # Extract the season and episode numbers
  717. my ($fileSeason, $episode) = findSE($title);
  718. # Extract the size
  719. my $size = 0;
  720. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  721. $size = $1;
  722. if ($2 eq 'G') {
  723. $size *= 1024;
  724. }
  725. $size = int($size);
  726. }
  727. # Count the sum of seeders and leachers
  728. my $seeds = 0;
  729. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  730. $seeds = $1;
  731. }
  732. my $leaches = 0;
  733. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  734. $leaches = $1;
  735. }
  736. # Construct a magnet URL from the hash
  737. # Assume the seconary lookup will append a list of trackers
  738. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  739. if ($DEBUG) {
  740. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  741. }
  742. # Save the extracted data
  743. my %tor = (
  744. 'title' => $title,
  745. 'season' => $fileSeason,
  746. 'episode' => $episode,
  747. 'seeds' => $seeds,
  748. 'leaches' => $leaches,
  749. 'size' => $size,
  750. 'url' => $url,
  751. 'source' => 'Z'
  752. );
  753. push(@tors, \%tor);
  754. }
  755. } elsif ($content =~ /Database\s+maintenance/i) {
  756. if ($DEBUG) {
  757. print STDERR "Source down for maintenance\n";
  758. }
  759. } elsif ($content =~ /^\s*$/) {
  760. if ($DEBUG) {
  761. print STDERR "Source returned no content\n";
  762. }
  763. } else {
  764. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  765. }
  766. }
  767. # Handle JSON content
  768. foreach my $content (@json_content) {
  769. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  770. }
  771. # Filter for size/count/etc.
  772. my %tors = ();
  773. my $showRegex = undef();
  774. {
  775. my $showClean = $show;
  776. $showClean =~ s/[\"\']//g;
  777. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  778. $showRegex = qr/^${showClean}[\W_]/i;
  779. }
  780. foreach my $tor (@tors) {
  781. # Extract the BTIH, if available
  782. getHash($tor);
  783. # Skip files that are in the torrent excludes list
  784. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  785. if ($DEBUG) {
  786. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  787. }
  788. next;
  789. }
  790. # Skip files that don't start with our show title
  791. if (!($tor->{'title'} =~ $showRegex)) {
  792. if ($DEBUG) {
  793. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  794. }
  795. next;
  796. # Skip pre-air files
  797. } elsif ($tor->{'title'} =~ /preair/i) {
  798. if ($DEBUG) {
  799. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  800. }
  801. next;
  802. # Skip SWESUB files
  803. } elsif ($tor->{'title'} =~ /swesub/i) {
  804. if ($DEBUG) {
  805. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  806. }
  807. next;
  808. # Skip .rus. files
  809. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  810. if ($DEBUG) {
  811. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  812. }
  813. next;
  814. # Skip German files
  815. } elsif ($tor->{'title'} =~ /german/i) {
  816. if ($DEBUG) {
  817. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  818. }
  819. next;
  820. # Skip French files
  821. } elsif ($tor->{'title'} =~ /french/i) {
  822. if ($DEBUG) {
  823. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  824. }
  825. next;
  826. # Skip unedited files
  827. } elsif ($tor->{'title'} =~ /unedited/i) {
  828. if ($DEBUG) {
  829. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  830. }
  831. next;
  832. }
  833. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  834. if (!$CUSTOM_SEARCH) {
  835. # Skip files that don't contain the right season number
  836. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  837. if ($DEBUG) {
  838. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  839. }
  840. next;
  841. # Skip files that don't contain the episode number, unless MORE_NUMBER_FORMATS is set and NO_SEAONS is not
  842. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })
  843. && !($MORE_NUMBER_FORMATS && $NO_QUALITY_CHECKS && defined($tor->{'episode'}) && $tor->{'episode'} == 0))
  844. {
  845. if ($DEBUG) {
  846. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  847. }
  848. next;
  849. }
  850. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  851. # Skip files that don't match the regex
  852. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  853. if ($DEBUG) {
  854. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  855. }
  856. next;
  857. }
  858. }
  859. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  860. if (!$NO_QUALITY_CHECKS) {
  861. # Skip torrents with too few seeders/leachers
  862. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  863. if ($DEBUG) {
  864. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  865. }
  866. next;
  867. # Skip torrents with unusual seed/leach ratios
  868. } elsif ($tor->{'seeds'} > 1
  869. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  870. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  871. {
  872. if ($DEBUG) {
  873. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  874. }
  875. next;
  876. # Skip torrents that are too small
  877. } elsif ($tor->{'size'} < $MIN_SIZE) {
  878. if ($DEBUG) {
  879. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  880. }
  881. next;
  882. }
  883. }
  884. # Save good torrents
  885. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  886. if ($DEBUG) {
  887. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  888. }
  889. }
  890. # Find the average torrent size for each episode
  891. my %avg = ();
  892. foreach my $episode (keys(%tors)) {
  893. my $count = 0;
  894. $avg{$episode} = 0.001;
  895. foreach my $tor (@{ $tors{$episode} }) {
  896. $avg{$episode} += $tor->{'size'};
  897. $count++;
  898. }
  899. if ($count > 0) {
  900. $avg{$episode} /= $count;
  901. }
  902. if ($DEBUG) {
  903. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  904. }
  905. }
  906. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  907. foreach my $episode (keys(%tors)) {
  908. foreach my $tor (@{ $tors{$episode} }) {
  909. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  910. # Start with the peer count
  911. $tor->{'adj_count'} = $count;
  912. # Adjust based on file size
  913. {
  914. my $size_ratio = $tor->{'size'} / $avg{$episode};
  915. if ($tor->{'size'} >= $avg{$episode}) {
  916. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  917. } else {
  918. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  919. }
  920. }
  921. # Adjust based on title contents
  922. if ($tor->{'title'} =~ /Subtitulado/i) {
  923. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  924. }
  925. # Truncate to an integer
  926. $tor->{'adj_count'} = int($tor->{'adj_count'});
  927. if ($DEBUG) {
  928. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  929. }
  930. }
  931. }
  932. # Pick the best-adjusted-count torrent for each episode
  933. my %urls = ();
  934. foreach my $episode (keys(%tors)) {
  935. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  936. my $max = undef();
  937. foreach my $tor (@sorted) {
  938. if (!defined($max) || $tor->{'adj_count'} > $max) {
  939. if ($urls{$episode} = resolveSecondary($tor)) {
  940. $max = $tor->{'adj_count'};
  941. }
  942. if ($DEBUG) {
  943. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  944. }
  945. } elsif ($DEBUG) {
  946. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  947. }
  948. }
  949. }
  950. # Output
  951. foreach my $episode (keys(%tors)) {
  952. if (defined($urls{$episode})) {
  953. $urls{$episode} = resolveTrackers($urls{$episode});
  954. print $urls{$episode} . "\n";
  955. if ($DEBUG) {
  956. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  957. }
  958. } elsif ($DEBUG) {
  959. print STDERR 'No URL for: ' . $episode . "\n";
  960. }
  961. }
  962. # Cleanup
  963. unlink($cookies);
  964. exit(0);
  965. sub getHash($) {
  966. my ($tor) = @_;
  967. my $url;
  968. # Allow either a URL or a tor hashref
  969. if (ref($tor) eq 'HASH') {
  970. $url = $tor->{'url'};
  971. } else {
  972. $url = $tor;
  973. undef($tor);
  974. }
  975. # Extract the BTIH hash, if available
  976. my $hash = undef();
  977. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  978. $hash = lc($1);
  979. }
  980. # Save back to the tor, if provided
  981. if (defined($tor)) {
  982. $tor->{'hash'} = $hash;
  983. }
  984. # Always return the hash, or undef() if none can be found
  985. return $hash;
  986. }
  987. # Resolve secondary URLs
  988. sub resolveSecondary($) {
  989. my ($tor) = @_;
  990. # Fetch the torrent-specific page and extract the magent link
  991. if ($tor->{'source'} eq 'ISO') {
  992. if ($DEBUG) {
  993. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  994. $fetch->file('/tmp/findTorrent-secondary.html');
  995. }
  996. sleep($DELAY * (rand(2) + 0.5));
  997. $fetch->url($tor->{'url'});
  998. $fetch->fetch();
  999. if ($fetch->status_code() != 200) {
  1000. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1001. goto OUT;
  1002. }
  1003. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1004. if (!defined($magnet) || length($magnet) < 1) {
  1005. if ($DEBUG) {
  1006. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1007. }
  1008. goto OUT;
  1009. }
  1010. $tor->{'url'} = decode_entities($magnet);
  1011. }
  1012. # Extract the hash
  1013. getHash($tor);
  1014. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1015. if ($DEBUG) {
  1016. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1017. }
  1018. goto OUT;
  1019. }
  1020. OUT:
  1021. return $tor->{'url'};
  1022. }
  1023. sub resolveTrackers($) {
  1024. my ($url) = @_;
  1025. # Always append a few static trackers to the URI
  1026. if ($url =~ /^magnet\:/i) {
  1027. foreach my $tracker (@TRACKERS) {
  1028. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1029. my $match = quotemeta($arg);
  1030. if (!($url =~ /${match}/)) {
  1031. $url .= $arg;
  1032. }
  1033. }
  1034. }
  1035. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1036. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1037. my $hash = lc($1);
  1038. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1039. my $hashURL = $baseURL . '/' . $hash;
  1040. if ($DEBUG) {
  1041. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1042. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1043. }
  1044. sleep($DELAY * (rand(2) + 0.5));
  1045. $fetch->url($hashURL);
  1046. $fetch->fetch();
  1047. if ($fetch->status_code() != 200) {
  1048. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1049. return $url;
  1050. }
  1051. # Parse out and fetch the tracker list URL
  1052. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1053. if (!defined($list)) {
  1054. if ($DEBUG) {
  1055. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1056. }
  1057. return $url;
  1058. }
  1059. my $listURL = $baseURL . $list;
  1060. if ($DEBUG) {
  1061. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1062. $fetch->file('/tmp/findTorrent-tracker.html');
  1063. }
  1064. sleep($DELAY * (rand(2) + 0.5));
  1065. $fetch->url($listURL);
  1066. $fetch->fetch();
  1067. if ($fetch->status_code() != 200) {
  1068. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1069. return $url;
  1070. }
  1071. # Parse the tracker list and append our URL
  1072. foreach my $line ($fetch->content()) {
  1073. if ($line =~ /^\s*$/) {
  1074. next;
  1075. }
  1076. $line =~ s/^\s+//;
  1077. $line =~ s/\s+$//;
  1078. if ($line =~ /^(?:http|udp)\:/i) {
  1079. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1080. my $match = quotemeta($arg);
  1081. if (!($url =~ /${match}/)) {
  1082. if ($DEBUG) {
  1083. print STDERR 'Adding tracker: ' . $line . "\n";
  1084. }
  1085. $url .= $arg;
  1086. }
  1087. } else {
  1088. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1089. }
  1090. }
  1091. }
  1092. return $url;
  1093. }
  1094. sub splitTags($$$) {
  1095. my ($content, $tag, $header) = @_;
  1096. # Find each tag element
  1097. my @out = ();
  1098. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1099. foreach my $part (@parts) {
  1100. # Trim trailing tags and skip things that aren't complete tags
  1101. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1102. if ($DEBUG > 1) {
  1103. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1104. }
  1105. next;
  1106. }
  1107. # Skip headers
  1108. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1109. if ($DEBUG > 2) {
  1110. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1111. }
  1112. next;
  1113. }
  1114. # Save good tags
  1115. push(@out, $part);
  1116. }
  1117. return @out;
  1118. }
  1119. # Extract season
  1120. sub findSE($) {
  1121. my ($title) = @_;
  1122. my $season = 0;
  1123. my $episode = 0;
  1124. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  1125. $season = $1;
  1126. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  1127. $season = $1;
  1128. $episode = $2;
  1129. }
  1130. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  1131. $episode = $1;
  1132. }
  1133. $season = int($season);
  1134. $episode = int($episode);
  1135. return ($season, $episode);
  1136. }
  1137. sub initSources() {
  1138. my %sources = ();
  1139. # The Pirate Bay
  1140. if ($ENABLE_SOURCE{'TPB'}) {
  1141. my @proxies = ('thepiratebay.se/search/', 'pirateproxy.se/search/', 'tpb.unblocked.co/search/');
  1142. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1143. if ($source) {
  1144. $source->{'weight'} = 1.00;
  1145. $source->{'quote'} = 0;
  1146. $source->{'search_suffix'} = '/0/7/0';
  1147. $sources{'TPB'} = $source;
  1148. }
  1149. }
  1150. # ISOhunt
  1151. if ($ENABLE_SOURCE{'ISO'}) {
  1152. my @proxies = ('http://isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1153. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1154. if ($source) {
  1155. $source->{'weight'} = 0.25;
  1156. $source->{'quote'} = 1;
  1157. $source->{'search_suffix'} = '';
  1158. $sources{'ISO'} = $source;
  1159. }
  1160. }
  1161. # Kickass
  1162. if ($ENABLE_SOURCE{'KICK'}) {
  1163. my @proxies = ('http://katproxy.com/usearch/', 'kickass.to/usearch/');
  1164. my $source = findProxy(\@proxies, 'torrent name\<\/th\>');
  1165. if ($source) {
  1166. $source->{'weight'} = 0.50;
  1167. $source->{'quote'} = 1;
  1168. $source->{'search_suffix'} = '/';
  1169. $sources{'KICK'} = $source;
  1170. }
  1171. }
  1172. # Torrentz
  1173. if ($ENABLE_SOURCE{'Z'}) {
  1174. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1175. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1176. if ($source) {
  1177. $source->{'weight'} = 0.75;
  1178. $source->{'quote'} = 1;
  1179. $source->{'search_suffix'} = '';
  1180. if (!$NO_QUALITY_CHECKS) {
  1181. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1182. }
  1183. $sources{'Z'} = $source;
  1184. }
  1185. }
  1186. # Sanity check
  1187. if (scalar(keys(%sources)) < 1) {
  1188. die("No sources available\n");
  1189. }
  1190. return \%sources;
  1191. }
  1192. sub findProxy($$) {
  1193. my ($proxies, $match) = @_;
  1194. # Automatically select a proxy
  1195. my $host = '';
  1196. my $protocol = '';
  1197. my $search_url = '';
  1198. foreach my $url (@{$proxies}) {
  1199. my $path;
  1200. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1201. if (!$protocol) {
  1202. $protocol = $PROTOCOL;
  1203. }
  1204. if (!$host) {
  1205. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1206. next;
  1207. }
  1208. $fetch->url($protocol . '://' . $host);
  1209. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1210. $search_url = $protocol . '://' . $host . $path;
  1211. last;
  1212. } elsif ($DEBUG) {
  1213. print STDERR 'Proxy not available: ' . $host . "\n";
  1214. }
  1215. }
  1216. # Return the search data if at least one proxy is up
  1217. if ($search_url) {
  1218. my %tmp = (
  1219. 'protocol' => $protocol,
  1220. 'host' => $host,
  1221. 'search_url' => $search_url,
  1222. );
  1223. return \%tmp;
  1224. }
  1225. # Return undef if we didn't find any working proxies
  1226. return undef();
  1227. }