findTorrent.pl 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use URI::Encode qw(uri_encode);
  5. # Defaults
  6. my $DEBUG = 0;
  7. my $NO_QUALITY_CHECKS = 0;
  8. my $MORE_NUMBER_FORMATS = 0;
  9. my $MIN_DAYS_BACK = 0;
  10. my $MAX_DAYS_BACK = 3;
  11. my $NEXT_EPISODES = 3;
  12. # Local config
  13. my $TV_DIR = `~/bin/video/mediaPath` . '/TV';
  14. # Search parameters
  15. my $PROTOCOL = 'http';
  16. my %ENABLE_SOURCE = ('TPB' => 0, 'ISO' => 1, 'KICK' => 1);
  17. # Selection parameters
  18. my $MIN_COUNT = 10;
  19. my $MIN_SIZE = 100;
  20. my $SIZE_BONUS = 7;
  21. my $SIZE_PENALTY = $SIZE_BONUS;
  22. my $TITLE_PENALTY = $SIZE_BONUS / 2;
  23. my $MAX_SEED_RATIO = .25;
  24. my $SEED_RATIO_COUNT = 10;
  25. # App config
  26. my $DELAY = 4;
  27. my $TIMEOUT = 15;
  28. my $UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9) AppleWebKit/537.71 (KHTML, like Gecko) Version/7.0 Safari/537.71';
  29. # Includes
  30. use JSON;
  31. use File::Temp;
  32. use File::Spec;
  33. use File::Basename;
  34. use FindBin qw($Bin);
  35. use lib $Bin;
  36. use Fetch;
  37. # Prototypes
  38. sub resolveSecondary($);
  39. sub splitTRs($);
  40. sub findSE($);
  41. # Command line
  42. my ($dir, $search) = @ARGV;
  43. if (!defined($dir)) {
  44. die('Usage: ' . basename($0) . " input_directory [search_string]\n");
  45. }
  46. if ($ENV{'DEBUG'}) {
  47. $DEBUG = 1;
  48. }
  49. if ($ENV{'NO_QUALITY_CHECKS'}) {
  50. $NO_QUALITY_CHECKS = 1;
  51. }
  52. if ($ENV{'MORE_NUMBER_FORMATS'}) {
  53. $MORE_NUMBER_FORMATS = 1;
  54. }
  55. if (defined($ENV{'MIN_DAYS_BACK'})) {
  56. $MIN_DAYS_BACK = $ENV{'MIN_DAYS_BACK'};
  57. }
  58. if (defined($ENV{'MAX_DAYS_BACK'})) {
  59. $MAX_DAYS_BACK = $ENV{'MAX_DAYS_BACK'};
  60. }
  61. if (defined($ENV{'NEXT_EPISODES'})) {
  62. $NEXT_EPISODES = $ENV{'NEXT_EPISODES'};
  63. }
  64. # New fetch object
  65. my $cookies = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  66. my $fetch = Fetch->new(
  67. 'cookiefile' => $cookies,
  68. 'timeout' => $TIMEOUT,
  69. 'uas' => $UA
  70. );
  71. # Search sources
  72. my %SOURCES = ();
  73. # The Pirate Bay
  74. if ($ENABLE_SOURCE{'TPB'}) {
  75. # Available TPB proxies, in order of preference
  76. my @TPBs = ('thepiratebay.se/search/', 'pirateproxy.se/search/', 'tpb.unblocked.co/search/');
  77. # Automatically select a proxy that returns a search page
  78. my $host = '';
  79. my $search_url = '';
  80. foreach my $url (@TPBs) {
  81. ($host) = $url =~ /^([^\/]+)/;
  82. $fetch->url($PROTOCOL . '://' . $host);
  83. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /\bSearch\b/i) {
  84. $search_url = $url;
  85. last;
  86. } elsif ($DEBUG) {
  87. print STDERR 'TPB proxy not available: ' . $host . "\n";
  88. }
  89. }
  90. # Only add TPB if one of the proxies is up
  91. if ($search_url) {
  92. my %tmp = (
  93. 'host' => $host,
  94. 'search_url' => $search_url,
  95. 'search_suffix' => '/0/7/0',
  96. 'weight' => 1.5,
  97. 'quote' => 0
  98. );
  99. $SOURCES{'TPB'} = \%tmp;
  100. }
  101. }
  102. # ISOhunt
  103. if ($ENABLE_SOURCE{'ISO'}) {
  104. # Available ISOhunt proxies, in order of preference
  105. my @ISOs = ('isohunt.to/torrents/?ihq=', 'isohunters.net/torrents/?ihq=');
  106. # Automatically select a proxy that returns the non-US page
  107. my $host = '';
  108. my $search_url = '';
  109. foreach my $url (@ISOs) {
  110. ($host) = $url =~ /^([^\/]+)/;
  111. $fetch->url($PROTOCOL . '://' . $host);
  112. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /Last\s+\d+\s+files\s+indexed/i) {
  113. $search_url = $url;
  114. last;
  115. } elsif ($DEBUG) {
  116. print STDERR 'ISOhunt proxy not available: ' . $host . "\n";
  117. }
  118. }
  119. # Only add ISOhunt if one of the proxies is up
  120. if ($search_url) {
  121. my %tmp = (
  122. 'host' => $host,
  123. 'search_url' => $search_url,
  124. 'search_suffix' => '',
  125. 'weight' => 0.30,
  126. 'quote' => 1
  127. );
  128. $SOURCES{'ISO'} = \%tmp;
  129. }
  130. }
  131. # Kickass
  132. if ($ENABLE_SOURCE{'KICK'}) {
  133. # Available Kickass proxies, in order of preference
  134. my @KICKs = ('kickass.so/usearch/');
  135. # Automatically select a proxy that returns the non-US page
  136. my $host = '';
  137. my $search_url = '';
  138. foreach my $url (@KICKs) {
  139. ($host) = $url =~ /^([^\/]+)/;
  140. $fetch->url($PROTOCOL . '://' . $host);
  141. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /torrent name\<\/th\>/i) {
  142. $search_url = $url;
  143. last;
  144. } elsif ($DEBUG) {
  145. print STDERR 'Kickass proxy not available: ' . $host . "\n";
  146. }
  147. }
  148. # Only add Kickass if one of the proxies is up
  149. if ($search_url) {
  150. my %tmp = (
  151. 'host' => $host,
  152. 'search_url' => $search_url,
  153. 'search_suffix' => '/',
  154. 'weight' => 0.30,
  155. 'quote' => 1
  156. );
  157. $SOURCES{'KICK'} = \%tmp;
  158. }
  159. }
  160. # Sanity check
  161. if (scalar(keys(%SOURCES)) < 1) {
  162. die("No sources available\n");
  163. }
  164. # Environment
  165. #if ($DEBUG) {
  166. # print STDERR `printenv` . "\n";
  167. #}
  168. # Figure out what we're searching for
  169. my $show = '';
  170. my @urls = ();
  171. my $CUSTOM_SEARCH = 0;
  172. my $season = 0;
  173. my @need = ();
  174. my %need = ();
  175. # Clean up the input "directory" path
  176. {
  177. # Allow use of the raw series name
  178. if (!($dir =~ /\//)) {
  179. $show = $dir;
  180. $dir = $TV_DIR . '/' . $dir;
  181. }
  182. # Allow use of relative paths
  183. $dir = File::Spec->rel2abs($dir);
  184. # Sanity check
  185. if (!-d $dir) {
  186. die('Invalid input directory: ' . $dir . "\n");
  187. }
  188. # Isolate the season from the path, if provided
  189. $dir =~ /\/Season\s+(\d+)\/?$/i;
  190. if ($1) {
  191. $season = $1;
  192. $dir = dirname($dir);
  193. }
  194. # If no season is provided find the latest
  195. if (!$season) {
  196. opendir(SERIES, $dir)
  197. or die("Unable to open series directory: ${!}\n");
  198. while (my $file = readdir(SERIES)) {
  199. if ($file =~ /^Season\s+(\d+)$/i) {
  200. if (!$season || $season < $1) {
  201. $season = $1;
  202. }
  203. }
  204. }
  205. closedir(SERIES);
  206. }
  207. # Isolate and clean the series name
  208. if (!$show) {
  209. $show = basename($dir);
  210. }
  211. $show =~ s/[\'\"\.]//g;
  212. if ($DEBUG) {
  213. print STDERR 'Checking directory: ' . $dir . "\n";
  214. }
  215. }
  216. # Allow quality checks to be disabled
  217. if (-e $dir . '/no_quality_checks') {
  218. $NO_QUALITY_CHECKS = 1;
  219. }
  220. # Read the excludes file, if any
  221. my $exclude = '';
  222. if (-e $dir . '/excludes') {
  223. local $/ = undef;
  224. open(EX, $dir . '/excludes')
  225. or die("Unable to open excludes file: ${!}\n");
  226. my $ex = <EX>;
  227. close(EX);
  228. $ex =~ s/^\s+//;
  229. $ex =~ s/^\s+//;
  230. my @excludes = split(/\s*,\s*/, $ex);
  231. foreach my $ex (@excludes) {
  232. if (length($exclude)) {
  233. $exclude .= ' ';
  234. }
  235. $exclude .= '-"' . $ex . '"';
  236. }
  237. $exclude = uri_encode(' ' . $exclude);
  238. }
  239. # Handle custom searches
  240. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  241. # Note the custom search string
  242. $CUSTOM_SEARCH = 1;
  243. if ($DEBUG) {
  244. print STDERR "Custom search\n";
  245. }
  246. # Create the relevent search strings
  247. foreach my $key (keys(%SOURCES)) {
  248. my $source = $SOURCES{$key};
  249. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  250. }
  251. }
  252. # Handle search-by-date series
  253. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  254. # Note the search-by-date status
  255. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  256. $CUSTOM_SEARCH = 1;
  257. if ($DEBUG) {
  258. print STDERR "Find by date\n";
  259. }
  260. # Read the find-by-date string
  261. my $search_by_date = '';
  262. local ($/, *FH);
  263. open(FH, $dir . '/search_by_date')
  264. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  265. my $text = <FH>;
  266. close(FH);
  267. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  268. $search_by_date = $1;
  269. } else {
  270. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  271. }
  272. # Create search strings for each date in the range, unless the related file already exists
  273. my (%years, %months, %days) = ();
  274. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  275. # Calculate the date
  276. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  277. # Format as strings
  278. $year = sprintf('%04d', $year + 1900);
  279. $month = sprintf('%02d', $month + 1);
  280. $day = sprintf('%02d', $day);
  281. # Check for an existing file
  282. my $exists = 0;
  283. {
  284. my $season_dir = $dir . '/Season ' . $year;
  285. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  286. opendir(SEASON, $season_dir)
  287. or die("Unable to open season directory: ${!}\n");
  288. while (my $file = readdir(SEASON)) {
  289. if ($file =~ $prefix) {
  290. $exists = 1;
  291. last;
  292. }
  293. }
  294. closedir(SEASON);
  295. }
  296. if ($exists) {
  297. next;
  298. }
  299. # Save all the date string components
  300. $years{$year} = 1;
  301. $months{$month} = 1;
  302. $days{$day} = 1;
  303. # Create the relevent search strings
  304. my $search_str = $search_by_date;
  305. $search_str =~ s/%Y/${year}/g;
  306. $search_str =~ s/%m/${month}/g;
  307. $search_str =~ s/%d/${day}/g;
  308. foreach my $key (keys(%SOURCES)) {
  309. my $source = $SOURCES{$key};
  310. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  311. }
  312. }
  313. # Build a date string matching regex
  314. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  315. $str .= '.*';
  316. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  317. $str .= '.*';
  318. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  319. $CUSTOM_SEARCH = qr/${str}/;
  320. }
  321. # Handle standard series
  322. if (scalar(@urls) < 1) {
  323. # Allow use of more number formats
  324. if (-e $dir . '/more_number_formats') {
  325. $MORE_NUMBER_FORMATS = 1;
  326. }
  327. # Allow the show name to be overriden
  328. {
  329. my $search_name = $dir . '/search_name';
  330. if (-e $search_name) {
  331. local ($/, *FH);
  332. open(FH, $search_name)
  333. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  334. my $text = <FH>;
  335. close(FH);
  336. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  337. $show = $1;
  338. } else {
  339. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  340. }
  341. }
  342. }
  343. if ($DEBUG) {
  344. print STDERR 'Searching with series title: ' . $show . "\n";
  345. }
  346. # Validate the season number
  347. if (!defined($season) || $season < 1 || $season > 2000) {
  348. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  349. }
  350. # Get the last episode number
  351. my $no_next = 0;
  352. my %episodes = ();
  353. my $highest = 0;
  354. opendir(SEASON, $dir . '/Season ' . $season)
  355. or die("Unable to open season directory: ${!}\n");
  356. while (my $file = readdir(SEASON)) {
  357. # Skip support files
  358. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  359. next;
  360. }
  361. # Check for a season_done file
  362. if ($file eq 'season_done') {
  363. $no_next = 1;
  364. next;
  365. }
  366. # Extract the episode number
  367. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  368. if (defined($num)) {
  369. $num = int($num);
  370. if ($DEBUG) {
  371. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  372. }
  373. # Record it
  374. $episodes{$num} = 1;
  375. # Track the highest episode number
  376. if ($num > $highest) {
  377. $highest = $num;
  378. }
  379. }
  380. }
  381. close(SEASON);
  382. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  383. if (!$no_next) {
  384. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  385. push(@need, $highest + $i);
  386. }
  387. }
  388. # Find any missing episodes
  389. for (my $i = 1 ; $i <= $highest ; $i++) {
  390. if (!$episodes{$i}) {
  391. push(@need, $i);
  392. }
  393. }
  394. if ($DEBUG) {
  395. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  396. }
  397. # Reverse the array for later matching
  398. foreach my $episode (@need) {
  399. $need{$episode} = 1;
  400. }
  401. # Construct a URL-friendly show name
  402. my $safeShow = $show;
  403. $safeShow =~ s/\s+\&\s+/ and /i;
  404. $safeShow =~ s/^\s*The\b//i;
  405. $safeShow =~ s/\s+\-\s+/ /g;
  406. $safeShow =~ s/[\'\:]//g;
  407. $safeShow =~ s/[^\w\"\-]+/ /g;
  408. $safeShow =~ s/^\s+//;
  409. $safeShow =~ s/\s+$//;
  410. $safeShow =~ s/\s\s+/ /g;
  411. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  412. $safeShow =~ s/\%20/\+/g;
  413. # Calculate possible name variations
  414. my @urlShowVarients = ();
  415. {
  416. # Default name
  417. push(@urlShowVarients, $safeShow);
  418. # Search for both "and" and "&"
  419. if ($safeShow =~ /\+and\+/i) {
  420. my $tmp = $safeShow;
  421. $tmp =~ s/\+and\+/\+%26\+/;
  422. push(@urlShowVarients, $tmp);
  423. }
  424. }
  425. # Construct the URL for each title varient of each needed episode
  426. foreach my $urlShow (@urlShowVarients) {
  427. foreach my $episode (@need) {
  428. my $episode_long = sprintf('%02d', $episode);
  429. my $season_long = sprintf('%02d', $season);
  430. foreach my $source (values(%SOURCES)) {
  431. # Use quotes around the show name if the source needs them
  432. my $quote = '%22';
  433. if (!$source->{'quote'}) {
  434. $quote = '';
  435. }
  436. # Calculate the compete search prefix and suffix to simplify later concatenations
  437. my $prefix = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote;
  438. my $suffix = $exclude;
  439. if ($source->{'search_suffix'}) {
  440. $suffix .= $source->{'search_suffix'};
  441. }
  442. # SXXEYY
  443. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  444. push(@urls, $url);
  445. # Extra searches for shows that have lazy/non-standard number formats
  446. if ($MORE_NUMBER_FORMATS) {
  447. # SXEY
  448. if ($season_long ne $season || $episode_long ne $episode) {
  449. $url = $prefix . '+s' . $season . 'e' . $episode . $exclude;
  450. push(@urls, $url);
  451. }
  452. # SXX EYY
  453. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $exclude;
  454. push(@urls, $url);
  455. # Season XX Episode YY
  456. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $exclude;
  457. push(@urls, $url);
  458. # Series X Episode Y
  459. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $exclude;
  460. push(@urls, $url);
  461. # SxEE
  462. $url = $prefix . '+' . $season . 'x' . $episode_long . $exclude;
  463. push(@urls, $url);
  464. }
  465. }
  466. }
  467. }
  468. }
  469. my @html_content = ();
  470. my @json_content = ();
  471. foreach my $url (@urls) {
  472. # Fetch the page
  473. if ($DEBUG) {
  474. print STDERR 'Searching with URL: ' . $url . "\n";
  475. $fetch->file('/tmp/findTorrent-lastPage.html');
  476. }
  477. sleep($DELAY * (rand(2) + 0.5));
  478. $fetch->url($url);
  479. $fetch->fetch();
  480. # Check for errors
  481. if ($fetch->status_code() != 200) {
  482. print STDERR 'Error fetching URL: ' . $url . "\n";
  483. }
  484. # Save the content, discriminating by data type
  485. if ($DEBUG) {
  486. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  487. }
  488. if ($fetch->content() =~ /^\s*{/) {
  489. my $json = eval { decode_json($fetch->content()); };
  490. if (defined($json) && ref($json)) {
  491. push(@json_content, \@{ $json->{'items'}->{'list'} });
  492. } elsif ($DEBUG) {
  493. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  494. }
  495. } else {
  496. push(@html_content, scalar($fetch->content()));
  497. }
  498. }
  499. # We need someplace to store parsed torrent data from the various sources
  500. my @tors = ();
  501. # Handle HTML content
  502. foreach my $content (@html_content) {
  503. if ($content =~ /\<title\>The Pirate Bay/i) {
  504. # Find TR elements from TPB
  505. my @trs = splitTRs($content);
  506. foreach my $tr (@trs) {
  507. # Find the show title
  508. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  509. if (!defined($title) || length($title) < 1) {
  510. if ($DEBUG) {
  511. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  512. }
  513. next;
  514. }
  515. $title =~ s/^\s+//;
  516. # Extract the season and episode numbers
  517. my ($fileSeason, $episode) = findSE($title);
  518. # Extract the URL
  519. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  520. if (!defined($url) || length($url) < 1) {
  521. if ($DEBUG) {
  522. print STDERR "Skipping TR with no magnet URL\n";
  523. }
  524. next;
  525. }
  526. # Count the sum of seeders and leachers
  527. my $seeds = 0;
  528. my $leaches = 0;
  529. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  530. $seeds = $1;
  531. $leaches = $2;
  532. }
  533. # Extract the size (from separate column or inline)
  534. my $size = 0;
  535. my $unit = 'M';
  536. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  537. $size = $1;
  538. $unit = $2;
  539. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  540. $size = $1;
  541. $unit = $2;
  542. }
  543. if ($unit eq 'G') {
  544. $size *= 1024;
  545. }
  546. $size = int($size);
  547. if ($DEBUG) {
  548. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  549. }
  550. # Save the extracted data
  551. my %tor = (
  552. 'title' => $title,
  553. 'season' => $fileSeason,
  554. 'episode' => $episode,
  555. 'seeds' => $seeds,
  556. 'leaches' => $leaches,
  557. 'size' => $size,
  558. 'url' => $url,
  559. 'source' => 'TPB'
  560. );
  561. push(@tors, \%tor);
  562. }
  563. } elsif ($content =~ /Isohunt Torrent Search Engine\<\/title\>/i) {
  564. # Find each TR element from ISOHunt
  565. my @trs = splitTRs($content);
  566. foreach my $tr (@trs) {
  567. # Split each TD element from the row
  568. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  569. my $numCols = scalar(@tds) - 1;
  570. if ($numCols > 9 && $numCols < 8) {
  571. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  572. next;
  573. }
  574. # Skip sponsored results
  575. if ($tds[1] =~ /Sponsored\<\/td\>/i) {
  576. if ($DEBUG > 1) {
  577. print STDERR "Skipping sponsored result\n";
  578. }
  579. next;
  580. }
  581. # Find the torrent ID and show title
  582. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+)\/[^\"]*\"\>\<span\>([^\>]+)\<\/span\>/i;
  583. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  584. if ($DEBUG) {
  585. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  586. }
  587. next;
  588. }
  589. $title =~ s/^\s+//;
  590. # Extract the season and episode numbers
  591. my ($fileSeason, $episode) = findSE($title);
  592. # Extract the size
  593. my $size = 0;
  594. my $unit = 'M';
  595. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  596. $size = $1;
  597. $unit = $2;
  598. }
  599. if ($unit eq 'G') {
  600. $size *= 1024;
  601. }
  602. $size = int($size);
  603. # Count the sum of seeders and leachers
  604. my $seeds = 0;
  605. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  606. $seeds = $1;
  607. }
  608. my $leaches = 0;
  609. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  610. $leaches = $1;
  611. }
  612. # Fetch the detail page for the URL
  613. my $url = $PROTOCOL . '://' . $SOURCES{'ISO'}->{'host'} . '/torrent_details/' . $id . '/';
  614. if ($DEBUG) {
  615. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  616. }
  617. # Save the extracted data
  618. my %tor = (
  619. 'title' => $title,
  620. 'season' => $fileSeason,
  621. 'episode' => $episode,
  622. 'seeds' => $seeds,
  623. 'leaches' => $leaches,
  624. 'size' => $size,
  625. 'url' => $url,
  626. 'source' => 'ISO'
  627. );
  628. push(@tors, \%tor);
  629. }
  630. } elsif ($content =~ /KickassTorrents\<\/title\>/i) {
  631. # Find each TR element from Kickass
  632. my @trs = splitTRs($content);
  633. foreach my $tr (@trs) {
  634. # Split each TD element from the row
  635. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  636. my $numCols = scalar(@tds) - 1;
  637. if ($numCols > 9 && $numCols < 8) {
  638. print STDERR 'Invalid KICK TR: ' . $tr . "\n";
  639. next;
  640. }
  641. # Find the torrent title
  642. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  643. if (!defined($title) || length($title) < 1) {
  644. if ($DEBUG) {
  645. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  646. }
  647. next;
  648. }
  649. $title =~ s/^\s+//;
  650. # Find the torrent URL
  651. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  652. if (!defined($url) || length($url) < 1) {
  653. if ($DEBUG) {
  654. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  655. }
  656. next;
  657. }
  658. # Extract the season and episode numbers
  659. my ($fileSeason, $episode) = findSE($title);
  660. # Extract the size
  661. my $size = 0;
  662. my $unit = 'M';
  663. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  664. $size = $1;
  665. $unit = $2;
  666. }
  667. if ($unit eq 'G') {
  668. $size *= 1024;
  669. }
  670. $size = int($size);
  671. # Count the sum of seeders and leachers
  672. my $seeds = 0;
  673. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  674. $seeds = $1;
  675. }
  676. my $leaches = 0;
  677. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  678. $leaches = $1;
  679. }
  680. if ($DEBUG) {
  681. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  682. }
  683. # Save the extracted data
  684. my %tor = (
  685. 'title' => $title,
  686. 'season' => $fileSeason,
  687. 'episode' => $episode,
  688. 'seeds' => $seeds,
  689. 'leaches' => $leaches,
  690. 'size' => $size,
  691. 'url' => $url,
  692. 'source' => 'KICK'
  693. );
  694. push(@tors, \%tor);
  695. }
  696. } else {
  697. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  698. }
  699. }
  700. # Handle JSON content
  701. foreach my $content (@json_content) {
  702. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  703. }
  704. # Filter for size/count/etc.
  705. my %tors = ();
  706. my $showRegex = undef();
  707. {
  708. my $showClean = $show;
  709. $showClean =~ s/[\"\']//g;
  710. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  711. $showRegex = qr/^${showClean}[\W_]/i;
  712. }
  713. foreach my $tor (@tors) {
  714. # Skip files that don't start with our show title
  715. if (!($tor->{'title'} =~ $showRegex)) {
  716. if ($DEBUG) {
  717. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  718. }
  719. next;
  720. # Skip pre-air files
  721. } elsif ($tor->{'title'} =~ /preair/i) {
  722. if ($DEBUG) {
  723. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  724. }
  725. next;
  726. # Skip SWESUB files
  727. } elsif ($tor->{'title'} =~ /swesub/i) {
  728. if ($DEBUG) {
  729. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  730. }
  731. next;
  732. # Skip .rus. files
  733. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  734. if ($DEBUG) {
  735. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  736. }
  737. next;
  738. # Skip german files
  739. } elsif ($tor->{'title'} =~ /german/i) {
  740. if ($DEBUG) {
  741. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  742. }
  743. next;
  744. # Skip unedited files
  745. } elsif ($tor->{'title'} =~ /unedited/i) {
  746. if ($DEBUG) {
  747. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  748. }
  749. next;
  750. }
  751. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  752. if (!$CUSTOM_SEARCH) {
  753. # Skip files that don't contain the right season number
  754. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  755. if ($DEBUG) {
  756. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  757. }
  758. next;
  759. # Skip files that don't contain the episode number
  760. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })) {
  761. if ($DEBUG) {
  762. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  763. }
  764. next;
  765. }
  766. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  767. # Skip files that don't match the regex
  768. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  769. if ($DEBUG) {
  770. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  771. }
  772. next;
  773. }
  774. }
  775. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  776. if (!$NO_QUALITY_CHECKS) {
  777. # Skip torrents with too few seeders/leachers
  778. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  779. if ($DEBUG) {
  780. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  781. }
  782. next;
  783. # Skip torrents with unusual seed/leach ratios
  784. } elsif ($tor->{'seeds'} > 1
  785. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  786. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  787. {
  788. if ($DEBUG) {
  789. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  790. }
  791. next;
  792. # Skip torrents that are too small
  793. } elsif ($tor->{'size'} < $MIN_SIZE) {
  794. if ($DEBUG) {
  795. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  796. }
  797. next;
  798. }
  799. }
  800. # Save good torrents
  801. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  802. if ($DEBUG) {
  803. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  804. }
  805. }
  806. # Find the average torrent size for each episode
  807. my %avg = ();
  808. foreach my $episode (keys(%tors)) {
  809. my $count = 0;
  810. $avg{$episode} = 0.001;
  811. foreach my $tor (@{ $tors{$episode} }) {
  812. $avg{$episode} += $tor->{'size'};
  813. $count++;
  814. }
  815. if ($count > 0) {
  816. $avg{$episode} /= $count;
  817. }
  818. if ($DEBUG) {
  819. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  820. }
  821. }
  822. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  823. foreach my $episode (keys(%tors)) {
  824. foreach my $tor (@{ $tors{$episode} }) {
  825. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  826. # Start with the peer count
  827. $tor->{'adj_count'} = $count;
  828. # Adjust based on file size
  829. {
  830. my $size_ratio = $tor->{'size'} / $avg{$episode};
  831. if ($tor->{'size'} >= $avg{$episode}) {
  832. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  833. } else {
  834. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  835. }
  836. }
  837. # Adjust based on title contents
  838. if ($tor->{'title'} =~ /Subtitulado/i) {
  839. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  840. }
  841. # Truncate to an integer
  842. $tor->{'adj_count'} = int($tor->{'adj_count'});
  843. if ($DEBUG) {
  844. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  845. }
  846. }
  847. }
  848. # Pick the best-adjusted-count torrent for each episode
  849. my %urls = ();
  850. foreach my $episode (keys(%tors)) {
  851. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  852. my $max = undef();
  853. foreach my $tor (@sorted) {
  854. if (!defined($max) || $tor->{'adj_count'} > $max) {
  855. if ($urls{$episode} = resolveSecondary($tor)) {
  856. $max = $tor->{'adj_count'};
  857. }
  858. if ($DEBUG) {
  859. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  860. }
  861. } elsif ($DEBUG) {
  862. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  863. }
  864. }
  865. }
  866. # Output
  867. foreach my $episode (keys(%tors)) {
  868. if (defined($urls{$episode})) {
  869. print $urls{$episode} . "\n";
  870. if ($DEBUG) {
  871. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  872. }
  873. } elsif ($DEBUG) {
  874. print STDERR 'No URL found for URL: ' . $episode . "\n";
  875. }
  876. }
  877. # Cleanup
  878. unlink($cookies);
  879. exit(0);
  880. # Resolve secondary URLs
  881. sub resolveSecondary($) {
  882. my ($tor) = @_;
  883. my $url = $tor->{'url'};
  884. if ($tor->{'source'} eq 'ISO') {
  885. if ($DEBUG) {
  886. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  887. $fetch->file('/tmp/findTorrent-secondary.html');
  888. }
  889. sleep($DELAY * (rand(2) + 0.5));
  890. $fetch->url($tor->{'url'});
  891. $fetch->fetch();
  892. if ($fetch->status_code() != 200) {
  893. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  894. return undef();
  895. }
  896. ($url) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  897. if (!defined($url) || length($url) < 1) {
  898. if ($DEBUG) {
  899. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  900. }
  901. return undef();
  902. }
  903. }
  904. return $url;
  905. }
  906. sub splitTRs($) {
  907. my ($content) = @_;
  908. # Find each TR element
  909. my @trs = ();
  910. my @rawTRs = split(/\<tr(?:\s+[^\>]*)?\>/i, $content);
  911. foreach my $tr (@rawTRs) {
  912. # Trim trailing tags and skip things that aren't complete TRs
  913. if (!($tr =~ s/\<\/tr\>.*$//is)) {
  914. if ($DEBUG > 1) {
  915. print STDERR 'Skipping non-TR line: ' . $tr . "\n\n";
  916. }
  917. next;
  918. }
  919. # Skip header rows
  920. if ($tr =~ /<th(?:\s+[^\>]*)?\>/i) {
  921. if ($DEBUG > 2) {
  922. print STDERR 'Skipping header TR line: ' . $tr . "\n\n";
  923. }
  924. next;
  925. }
  926. # Save good TRs
  927. push(@trs, $tr);
  928. }
  929. return @trs;
  930. }
  931. # Extract season
  932. sub findSE($) {
  933. my ($title) = @_;
  934. my $season = 0;
  935. my $episode = 0;
  936. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  937. $season = $1;
  938. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  939. $season = $1;
  940. $episode = $2;
  941. }
  942. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  943. $episode = $1;
  944. }
  945. $season = int($season);
  946. $episode = int($episode);
  947. return ($season, $episode);
  948. }