findTorrent.pl 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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' => 0);
  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 = 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');
  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');
  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. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  567. next;
  568. }
  569. # Skip sponsored results
  570. if ($tds[1] =~ /\bSponsored\b/i) {
  571. if ($DEBUG > 1) {
  572. print STDERR "Skipping sponsored result\n";
  573. }
  574. next;
  575. }
  576. # Find the torrent ID and show title
  577. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+\/[^\"]+)\"\>\<span\>([^\>]+)\<\/span\>/i;
  578. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  579. if ($DEBUG) {
  580. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  581. }
  582. next;
  583. }
  584. $title =~ s/^\s+//;
  585. # Extract the season and episode numbers
  586. my ($fileSeason, $episode) = findSE($title);
  587. # Extract the size
  588. my $size = 0;
  589. my $unit = 'M';
  590. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  591. $size = $1;
  592. $unit = $2;
  593. }
  594. if ($unit eq 'G') {
  595. $size *= 1024;
  596. }
  597. $size = int($size);
  598. # Count the sum of seeders and leachers
  599. my $seeds = 0;
  600. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  601. $seeds = $1;
  602. }
  603. my $leaches = 0;
  604. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  605. $leaches = $1;
  606. }
  607. # Fetch the detail page for the URL
  608. my $url = $SOURCES->{'ISO'}->{'protocol'} . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id;
  609. if ($DEBUG) {
  610. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  611. }
  612. # Save the extracted data
  613. my %tor = (
  614. 'title' => $title,
  615. 'season' => $fileSeason,
  616. 'episode' => $episode,
  617. 'seeds' => $seeds,
  618. 'leaches' => $leaches,
  619. 'size' => $size,
  620. 'url' => $url,
  621. 'source' => 'ISO'
  622. );
  623. push(@tors, \%tor);
  624. }
  625. } elsif ($content =~ /Kickass\s*Torrents\<\/title\>/i) {
  626. # Find each TR element from Kickass
  627. my @trs = splitTags($content, 'TR', 'TH');
  628. foreach my $tr (@trs) {
  629. # Split each TD element from the row
  630. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  631. my $numCols = scalar(@tds) - 1;
  632. if ($numCols > 9 && $numCols < 8) {
  633. print STDERR 'Invalid KICK TR: ' . $tr . "\n";
  634. next;
  635. }
  636. # Skip empty results
  637. if ( $tds[1] =~ /\<h2\>Nothing found\!\<\/h2\>/i
  638. || $tds[1] =~ /\<p\>\<strong\>Page not found\<\/strong\>\<\/p\>/i)
  639. {
  640. if ($DEBUG) {
  641. print STDERR "Skipping empty TD\n";
  642. }
  643. next;
  644. }
  645. # Find the torrent title
  646. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  647. if (!defined($title) || length($title) < 1) {
  648. if ($DEBUG) {
  649. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  650. }
  651. next;
  652. }
  653. $title =~ s/^\s+//;
  654. # Find the torrent URL
  655. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  656. if (!defined($url) || length($url) < 1) {
  657. if ($DEBUG) {
  658. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  659. }
  660. next;
  661. }
  662. $url = decode_entities($url);
  663. # Extract the season and episode numbers
  664. my ($fileSeason, $episode) = findSE($title);
  665. # Extract the size
  666. my $size = 0;
  667. my $unit = 'M';
  668. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  669. $size = $1;
  670. $unit = $2;
  671. }
  672. if ($unit eq 'G') {
  673. $size *= 1024;
  674. }
  675. $size = int($size);
  676. # Count the sum of seeders and leachers
  677. my $seeds = 0;
  678. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  679. $seeds = $1;
  680. }
  681. my $leaches = 0;
  682. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  683. $leaches = $1;
  684. }
  685. if ($DEBUG) {
  686. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  687. }
  688. # Save the extracted data
  689. my %tor = (
  690. 'title' => $title,
  691. 'season' => $fileSeason,
  692. 'episode' => $episode,
  693. 'seeds' => $seeds,
  694. 'leaches' => $leaches,
  695. 'size' => $size,
  696. 'url' => $url,
  697. 'source' => 'KICK'
  698. );
  699. push(@tors, \%tor);
  700. }
  701. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  702. # We'll need to strip HTML
  703. my $hs = HTML::Strip->new();
  704. # Find each DL element from Torrentz
  705. my @dls = splitTags($content, 'DL', undef());
  706. foreach my $dl (@dls) {
  707. # Skip ads
  708. if ($dl =~ /\s+rel\=\"nofollow/i) {
  709. next;
  710. }
  711. # Find the torrent title
  712. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  713. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  714. if ($DEBUG) {
  715. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  716. }
  717. next;
  718. }
  719. $hash = lc($hash);
  720. $title = $hs->parse($title);
  721. $hs->eof;
  722. $title =~ s/^\s+//;
  723. # Extract the season and episode numbers
  724. my ($fileSeason, $episode) = findSE($title);
  725. # Extract the size
  726. my $size = 0;
  727. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  728. $size = $1;
  729. if ($2 eq 'G') {
  730. $size *= 1024;
  731. }
  732. $size = int($size);
  733. }
  734. # Count the sum of seeders and leachers
  735. my $seeds = 0;
  736. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  737. $seeds = $1;
  738. }
  739. my $leaches = 0;
  740. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  741. $leaches = $1;
  742. }
  743. # Construct a magnet URL from the hash
  744. # Assume the seconary lookup will append a list of trackers
  745. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  746. if ($DEBUG) {
  747. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  748. }
  749. # Save the extracted data
  750. my %tor = (
  751. 'title' => $title,
  752. 'season' => $fileSeason,
  753. 'episode' => $episode,
  754. 'seeds' => $seeds,
  755. 'leaches' => $leaches,
  756. 'size' => $size,
  757. 'url' => $url,
  758. 'source' => 'Z'
  759. );
  760. push(@tors, \%tor);
  761. }
  762. } elsif ($content =~ /Database\s+maintenance/i) {
  763. if ($DEBUG) {
  764. print STDERR "Source down for maintenance\n";
  765. }
  766. } elsif ($content =~ /^\s*$/) {
  767. if ($DEBUG) {
  768. print STDERR "Source returned no content\n";
  769. }
  770. } else {
  771. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  772. }
  773. }
  774. # Handle JSON content
  775. foreach my $content (@json_content) {
  776. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  777. }
  778. # Filter for size/count/etc.
  779. my %tors = ();
  780. my $showRegex = undef();
  781. {
  782. my $showClean = $show;
  783. $showClean =~ s/[\"\']//g;
  784. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  785. $showRegex = qr/^${showClean}[\W_]/i;
  786. }
  787. foreach my $tor (@tors) {
  788. # Extract the BTIH, if available
  789. getHash($tor);
  790. # Skip files that are in the torrent excludes list
  791. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  792. if ($DEBUG) {
  793. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  794. }
  795. next;
  796. }
  797. # Skip files that don't start with our show title
  798. if (!($tor->{'title'} =~ $showRegex)) {
  799. if ($DEBUG) {
  800. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  801. }
  802. next;
  803. # Skip pre-air files
  804. } elsif ($tor->{'title'} =~ /preair/i) {
  805. if ($DEBUG) {
  806. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  807. }
  808. next;
  809. # Skip SWESUB files
  810. } elsif ($tor->{'title'} =~ /swesub/i) {
  811. if ($DEBUG) {
  812. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  813. }
  814. next;
  815. # Skip .rus. files
  816. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  817. if ($DEBUG) {
  818. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  819. }
  820. next;
  821. # Skip German files
  822. } elsif ($tor->{'title'} =~ /german/i) {
  823. if ($DEBUG) {
  824. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  825. }
  826. next;
  827. # Skip French files
  828. } elsif ($tor->{'title'} =~ /french/i) {
  829. if ($DEBUG) {
  830. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  831. }
  832. next;
  833. # Skip unedited files
  834. } elsif ($tor->{'title'} =~ /unedited/i) {
  835. if ($DEBUG) {
  836. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  837. }
  838. next;
  839. }
  840. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  841. if (!$CUSTOM_SEARCH) {
  842. # Skip files that don't contain the right season number
  843. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  844. if ($DEBUG) {
  845. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  846. }
  847. next;
  848. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  849. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} }) || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS)) {
  850. if ($DEBUG) {
  851. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  852. }
  853. next;
  854. }
  855. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  856. # Skip files that don't match the regex
  857. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  858. if ($DEBUG) {
  859. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  860. }
  861. next;
  862. }
  863. }
  864. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  865. if (!$NO_QUALITY_CHECKS) {
  866. # Skip torrents with too few seeders/leachers
  867. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  868. if ($DEBUG) {
  869. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  870. }
  871. next;
  872. # Skip torrents with unusual seed/leach ratios
  873. } elsif ($tor->{'seeds'} > 1
  874. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  875. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  876. {
  877. if ($DEBUG) {
  878. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  879. }
  880. next;
  881. # Skip torrents that are too small
  882. } elsif ($tor->{'size'} < $MIN_SIZE) {
  883. if ($DEBUG) {
  884. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  885. }
  886. next;
  887. }
  888. }
  889. # Save good torrents
  890. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  891. if ($DEBUG) {
  892. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  893. }
  894. }
  895. # Find the average torrent size for each episode
  896. my %avg = ();
  897. foreach my $episode (keys(%tors)) {
  898. my $count = 0;
  899. $avg{$episode} = 0.001;
  900. foreach my $tor (@{ $tors{$episode} }) {
  901. $avg{$episode} += $tor->{'size'};
  902. $count++;
  903. }
  904. if ($count > 0) {
  905. $avg{$episode} /= $count;
  906. }
  907. if ($DEBUG) {
  908. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  909. }
  910. }
  911. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  912. foreach my $episode (keys(%tors)) {
  913. foreach my $tor (@{ $tors{$episode} }) {
  914. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  915. # Start with the peer count
  916. $tor->{'adj_count'} = $count;
  917. # Adjust based on file size
  918. {
  919. my $size_ratio = $tor->{'size'} / $avg{$episode};
  920. if ($tor->{'size'} >= $avg{$episode}) {
  921. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  922. } else {
  923. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  924. }
  925. }
  926. # Adjust based on title contents
  927. if ($tor->{'title'} =~ /Subtitulado/i) {
  928. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  929. }
  930. # Truncate to an integer
  931. $tor->{'adj_count'} = int($tor->{'adj_count'});
  932. if ($DEBUG) {
  933. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  934. }
  935. }
  936. }
  937. # Pick the best-adjusted-count torrent for each episode
  938. my %urls = ();
  939. foreach my $episode (keys(%tors)) {
  940. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  941. my $max = undef();
  942. foreach my $tor (@sorted) {
  943. if (!defined($max) || $tor->{'adj_count'} > $max) {
  944. if ($urls{$episode} = resolveSecondary($tor)) {
  945. $max = $tor->{'adj_count'};
  946. }
  947. if ($DEBUG) {
  948. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  949. }
  950. } elsif ($DEBUG) {
  951. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  952. }
  953. }
  954. }
  955. # Output
  956. foreach my $episode (keys(%tors)) {
  957. if (defined($urls{$episode})) {
  958. $urls{$episode} = resolveTrackers($urls{$episode});
  959. print $urls{$episode} . "\n";
  960. if ($DEBUG) {
  961. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  962. }
  963. } elsif ($DEBUG) {
  964. print STDERR 'No URL for: ' . $episode . "\n";
  965. }
  966. }
  967. # Cleanup
  968. unlink($cookies);
  969. exit(0);
  970. sub getHash($) {
  971. my ($tor) = @_;
  972. my $url;
  973. # Allow either a URL or a tor hashref
  974. if (ref($tor) eq 'HASH') {
  975. $url = $tor->{'url'};
  976. } else {
  977. $url = $tor;
  978. undef($tor);
  979. }
  980. # Extract the BTIH hash, if available
  981. my $hash = undef();
  982. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  983. $hash = lc($1);
  984. }
  985. # Save back to the tor, if provided
  986. if (defined($tor)) {
  987. $tor->{'hash'} = $hash;
  988. }
  989. # Always return the hash, or undef() if none can be found
  990. return $hash;
  991. }
  992. # Resolve secondary URLs
  993. sub resolveSecondary($) {
  994. my ($tor) = @_;
  995. # Fetch the torrent-specific page and extract the magent link
  996. if ($tor->{'source'} eq 'ISO') {
  997. if ($DEBUG) {
  998. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  999. $fetch->file('/tmp/findTorrent-secondary.html');
  1000. }
  1001. sleep($DELAY * (rand(2) + 0.5));
  1002. $fetch->url($tor->{'url'});
  1003. $fetch->fetch();
  1004. if ($fetch->status_code() != 200) {
  1005. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1006. goto OUT;
  1007. }
  1008. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1009. if (!defined($magnet) || length($magnet) < 1) {
  1010. if ($DEBUG) {
  1011. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1012. }
  1013. goto OUT;
  1014. }
  1015. $tor->{'url'} = decode_entities($magnet);
  1016. }
  1017. # Extract the hash
  1018. getHash($tor);
  1019. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1020. if ($DEBUG) {
  1021. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1022. }
  1023. goto OUT;
  1024. }
  1025. OUT:
  1026. return $tor->{'url'};
  1027. }
  1028. sub resolveTrackers($) {
  1029. my ($url) = @_;
  1030. # Always append a few static trackers to the URI
  1031. if ($url =~ /^magnet\:/i) {
  1032. foreach my $tracker (@TRACKERS) {
  1033. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1034. my $match = quotemeta($arg);
  1035. if (!($url =~ /${match}/)) {
  1036. $url .= $arg;
  1037. }
  1038. }
  1039. }
  1040. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1041. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1042. my $hash = lc($1);
  1043. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1044. my $hashURL = $baseURL . '/' . $hash;
  1045. if ($DEBUG) {
  1046. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1047. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1048. }
  1049. sleep($DELAY * (rand(2) + 0.5));
  1050. $fetch->url($hashURL);
  1051. $fetch->fetch();
  1052. if ($fetch->status_code() != 200) {
  1053. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1054. return $url;
  1055. }
  1056. # Parse out and fetch the tracker list URL
  1057. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1058. if (!defined($list)) {
  1059. if ($DEBUG) {
  1060. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1061. }
  1062. return $url;
  1063. }
  1064. my $listURL = $baseURL . $list;
  1065. if ($DEBUG) {
  1066. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1067. $fetch->file('/tmp/findTorrent-tracker.html');
  1068. }
  1069. sleep($DELAY * (rand(2) + 0.5));
  1070. $fetch->url($listURL);
  1071. $fetch->fetch();
  1072. if ($fetch->status_code() != 200) {
  1073. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1074. return $url;
  1075. }
  1076. # Parse the tracker list and append our URL
  1077. foreach my $line ($fetch->content()) {
  1078. if ($line =~ /^\s*$/) {
  1079. next;
  1080. }
  1081. $line =~ s/^\s+//;
  1082. $line =~ s/\s+$//;
  1083. if ($line =~ /^(?:http|udp)\:/i) {
  1084. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1085. my $match = quotemeta($arg);
  1086. if (!($url =~ /${match}/)) {
  1087. if ($DEBUG) {
  1088. print STDERR 'Adding tracker: ' . $line . "\n";
  1089. }
  1090. $url .= $arg;
  1091. }
  1092. } else {
  1093. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1094. }
  1095. }
  1096. }
  1097. return $url;
  1098. }
  1099. sub splitTags($$$) {
  1100. my ($content, $tag, $header) = @_;
  1101. # Find each tag element
  1102. my @out = ();
  1103. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1104. foreach my $part (@parts) {
  1105. # Trim trailing tags and skip things that aren't complete tags
  1106. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1107. if ($DEBUG > 1) {
  1108. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1109. }
  1110. next;
  1111. }
  1112. # Skip headers
  1113. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1114. if ($DEBUG > 2) {
  1115. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1116. }
  1117. next;
  1118. }
  1119. # Save good tags
  1120. push(@out, $part);
  1121. }
  1122. return @out;
  1123. }
  1124. # Extract season
  1125. sub findSE($) {
  1126. my ($name) = @_;
  1127. my $season = 0;
  1128. my $episode = 0;
  1129. my $seasonBlock = '';
  1130. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1131. $seasonBlock = $1;
  1132. my ($month, $day);
  1133. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1134. $season = int($season);
  1135. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1136. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1137. $seasonBlock = $1;
  1138. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1139. $season = int($season);
  1140. $episode = sprintf('%02d', int($episode));
  1141. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1142. $seasonBlock = $1;
  1143. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1144. $season = int($season);
  1145. $episode = sprintf('%02d', int($episode));
  1146. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1147. $seasonBlock = $1;
  1148. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1149. $season = int($season);
  1150. $episode = sprintf('%02d', int($episode));
  1151. }
  1152. # Return something valid and INTy or UNDEF
  1153. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1154. if ($DEBUG) {
  1155. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1156. }
  1157. $season = undef();
  1158. $episode = undef();
  1159. } else {
  1160. $episode = int($episode);
  1161. }
  1162. return ($season, $episode);
  1163. }
  1164. sub initSources() {
  1165. my %sources = ();
  1166. # The Pirate Bay
  1167. if ($ENABLE_SOURCE{'TPB'}) {
  1168. my @proxies = ('thepiratebay.se/search/', 'pirateproxy.se/search/', 'tpb.unblocked.co/search/');
  1169. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1170. if ($source) {
  1171. $source->{'weight'} = 1.00;
  1172. $source->{'quote'} = 0;
  1173. $source->{'search_suffix'} = '/0/7/0';
  1174. $sources{'TPB'} = $source;
  1175. }
  1176. }
  1177. # ISOhunt
  1178. if ($ENABLE_SOURCE{'ISO'}) {
  1179. my @proxies = ('http://isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1180. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1181. if ($source) {
  1182. $source->{'weight'} = 0.25;
  1183. $source->{'quote'} = 1;
  1184. $source->{'search_suffix'} = '';
  1185. $sources{'ISO'} = $source;
  1186. }
  1187. }
  1188. # Kickass
  1189. if ($ENABLE_SOURCE{'KICK'}) {
  1190. my @proxies = ('kat.cr/usearch/', 'kickass.unblocked.pw/usearch/', 'kickass.to/usearch/');
  1191. my $source = findProxy(\@proxies, '/usearch/');
  1192. if ($source) {
  1193. $source->{'weight'} = 0.50;
  1194. $source->{'quote'} = 1;
  1195. $source->{'search_suffix'} = '/';
  1196. $sources{'KICK'} = $source;
  1197. }
  1198. }
  1199. # Torrentz
  1200. if ($ENABLE_SOURCE{'Z'}) {
  1201. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1202. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1203. if ($source) {
  1204. $source->{'weight'} = 0.75;
  1205. $source->{'quote'} = 1;
  1206. $source->{'search_suffix'} = '';
  1207. if (!$NO_QUALITY_CHECKS) {
  1208. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1209. }
  1210. $sources{'Z'} = $source;
  1211. }
  1212. }
  1213. # Sanity check
  1214. if (scalar(keys(%sources)) < 1) {
  1215. die("No sources available\n");
  1216. }
  1217. return \%sources;
  1218. }
  1219. sub findProxy($$) {
  1220. my ($proxies, $match) = @_;
  1221. # Automatically select a proxy
  1222. my $host = '';
  1223. my $protocol = '';
  1224. my $search_url = '';
  1225. foreach my $url (@{$proxies}) {
  1226. my $path;
  1227. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1228. if (!$protocol) {
  1229. $protocol = $PROTOCOL;
  1230. }
  1231. if (!$host) {
  1232. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1233. next;
  1234. }
  1235. $fetch->url($protocol . '://' . $host);
  1236. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1237. $search_url = $protocol . '://' . $host . $path;
  1238. last;
  1239. } elsif ($DEBUG) {
  1240. print STDERR 'Proxy not available: ' . $host . "\n";
  1241. if ($DEBUG > 1) {
  1242. print STDERR $fetch->content() . "\n";
  1243. }
  1244. }
  1245. }
  1246. # Return the search data if at least one proxy is up
  1247. if ($search_url) {
  1248. my %tmp = (
  1249. 'protocol' => $protocol,
  1250. 'host' => $host,
  1251. 'search_url' => $search_url,
  1252. );
  1253. return \%tmp;
  1254. }
  1255. # Return undef if we didn't find any working proxies
  1256. return undef();
  1257. }