findTorrent.pl 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A';
  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('nocheck' => 1);
  480. # Check for useful errors
  481. if ($fetch->status_code() == 404) {
  482. if ($DEBUG) {
  483. print STDERR "Skipping content from 404 response\n";
  484. }
  485. next;
  486. }
  487. # Check for errors
  488. if ($fetch->status_code() != 200) {
  489. print STDERR 'Error fetching URL: ' . $url . "\n";
  490. next;
  491. }
  492. # Save the content, discriminating by data type
  493. if ($DEBUG) {
  494. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  495. }
  496. if ($fetch->content() =~ /^\s*{/) {
  497. my $json = eval { decode_json($fetch->content()); };
  498. if (defined($json) && ref($json)) {
  499. push(@json_content, \@{ $json->{'items'}->{'list'} });
  500. } elsif ($DEBUG) {
  501. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  502. }
  503. } else {
  504. push(@html_content, scalar($fetch->content()));
  505. }
  506. }
  507. # We need someplace to store parsed torrent data from the various sources
  508. my @tors = ();
  509. # Handle HTML content
  510. foreach my $content (@html_content) {
  511. if ($content =~ /\<title\>The Pirate Bay/i) {
  512. # Find TR elements from TPB
  513. my @trs = splitTRs($content);
  514. foreach my $tr (@trs) {
  515. # Find the show title
  516. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  517. if (!defined($title) || length($title) < 1) {
  518. if ($DEBUG) {
  519. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  520. }
  521. next;
  522. }
  523. $title =~ s/^\s+//;
  524. # Extract the season and episode numbers
  525. my ($fileSeason, $episode) = findSE($title);
  526. # Extract the URL
  527. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  528. if (!defined($url) || length($url) < 1) {
  529. if ($DEBUG) {
  530. print STDERR "Skipping TR with no magnet URL\n";
  531. }
  532. next;
  533. }
  534. # Count the sum of seeders and leachers
  535. my $seeds = 0;
  536. my $leaches = 0;
  537. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  538. $seeds = $1;
  539. $leaches = $2;
  540. }
  541. # Extract the size (from separate column or inline)
  542. my $size = 0;
  543. my $unit = 'M';
  544. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  545. $size = $1;
  546. $unit = $2;
  547. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  548. $size = $1;
  549. $unit = $2;
  550. }
  551. if ($unit eq 'G') {
  552. $size *= 1024;
  553. }
  554. $size = int($size);
  555. if ($DEBUG) {
  556. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  557. }
  558. # Save the extracted data
  559. my %tor = (
  560. 'title' => $title,
  561. 'season' => $fileSeason,
  562. 'episode' => $episode,
  563. 'seeds' => $seeds,
  564. 'leaches' => $leaches,
  565. 'size' => $size,
  566. 'url' => $url,
  567. 'source' => 'TPB'
  568. );
  569. push(@tors, \%tor);
  570. }
  571. } elsif ($content =~ /Isohunt Torrent Search Engine\<\/title\>/i) {
  572. # Find each TR element from ISOHunt
  573. my @trs = splitTRs($content);
  574. foreach my $tr (@trs) {
  575. # Split each TD element from the row
  576. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  577. my $numCols = scalar(@tds) - 1;
  578. if ($numCols > 9 && $numCols < 8) {
  579. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  580. next;
  581. }
  582. # Skip sponsored results
  583. if ($tds[1] =~ /Sponsored\<\/td\>/i) {
  584. if ($DEBUG > 1) {
  585. print STDERR "Skipping sponsored result\n";
  586. }
  587. next;
  588. }
  589. # Find the torrent ID and show title
  590. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+)\/[^\"]*\"\>\<span\>([^\>]+)\<\/span\>/i;
  591. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  592. if ($DEBUG) {
  593. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  594. }
  595. next;
  596. }
  597. $title =~ s/^\s+//;
  598. # Extract the season and episode numbers
  599. my ($fileSeason, $episode) = findSE($title);
  600. # Extract the size
  601. my $size = 0;
  602. my $unit = 'M';
  603. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  604. $size = $1;
  605. $unit = $2;
  606. }
  607. if ($unit eq 'G') {
  608. $size *= 1024;
  609. }
  610. $size = int($size);
  611. # Count the sum of seeders and leachers
  612. my $seeds = 0;
  613. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  614. $seeds = $1;
  615. }
  616. my $leaches = 0;
  617. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  618. $leaches = $1;
  619. }
  620. # Fetch the detail page for the URL
  621. my $url = $PROTOCOL . '://' . $SOURCES{'ISO'}->{'host'} . '/torrent_details/' . $id . '/';
  622. if ($DEBUG) {
  623. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  624. }
  625. # Save the extracted data
  626. my %tor = (
  627. 'title' => $title,
  628. 'season' => $fileSeason,
  629. 'episode' => $episode,
  630. 'seeds' => $seeds,
  631. 'leaches' => $leaches,
  632. 'size' => $size,
  633. 'url' => $url,
  634. 'source' => 'ISO'
  635. );
  636. push(@tors, \%tor);
  637. }
  638. } elsif ($content =~ /KickassTorrents\<\/title\>/i) {
  639. # Find each TR element from Kickass
  640. my @trs = splitTRs($content);
  641. foreach my $tr (@trs) {
  642. # Split each TD element from the row
  643. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  644. my $numCols = scalar(@tds) - 1;
  645. if ($numCols > 9 && $numCols < 8) {
  646. print STDERR 'Invalid KICK TR: ' . $tr . "\n";
  647. next;
  648. }
  649. # Find the torrent title
  650. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  651. if (!defined($title) || length($title) < 1) {
  652. if ($DEBUG) {
  653. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  654. }
  655. next;
  656. }
  657. $title =~ s/^\s+//;
  658. # Find the torrent URL
  659. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  660. if (!defined($url) || length($url) < 1) {
  661. if ($DEBUG) {
  662. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  663. }
  664. next;
  665. }
  666. # Extract the season and episode numbers
  667. my ($fileSeason, $episode) = findSE($title);
  668. # Extract the size
  669. my $size = 0;
  670. my $unit = 'M';
  671. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  672. $size = $1;
  673. $unit = $2;
  674. }
  675. if ($unit eq 'G') {
  676. $size *= 1024;
  677. }
  678. $size = int($size);
  679. # Count the sum of seeders and leachers
  680. my $seeds = 0;
  681. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  682. $seeds = $1;
  683. }
  684. my $leaches = 0;
  685. if ($tds[6] =~ /(\d+)\<\/td\>/i) {
  686. $leaches = $1;
  687. }
  688. if ($DEBUG) {
  689. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  690. }
  691. # Save the extracted data
  692. my %tor = (
  693. 'title' => $title,
  694. 'season' => $fileSeason,
  695. 'episode' => $episode,
  696. 'seeds' => $seeds,
  697. 'leaches' => $leaches,
  698. 'size' => $size,
  699. 'url' => $url,
  700. 'source' => 'KICK'
  701. );
  702. push(@tors, \%tor);
  703. }
  704. } else {
  705. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  706. }
  707. }
  708. # Handle JSON content
  709. foreach my $content (@json_content) {
  710. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  711. }
  712. # Filter for size/count/etc.
  713. my %tors = ();
  714. my $showRegex = undef();
  715. {
  716. my $showClean = $show;
  717. $showClean =~ s/[\"\']//g;
  718. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  719. $showRegex = qr/^${showClean}[\W_]/i;
  720. }
  721. foreach my $tor (@tors) {
  722. # Skip files that don't start with our show title
  723. if (!($tor->{'title'} =~ $showRegex)) {
  724. if ($DEBUG) {
  725. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  726. }
  727. next;
  728. # Skip pre-air files
  729. } elsif ($tor->{'title'} =~ /preair/i) {
  730. if ($DEBUG) {
  731. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  732. }
  733. next;
  734. # Skip SWESUB files
  735. } elsif ($tor->{'title'} =~ /swesub/i) {
  736. if ($DEBUG) {
  737. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  738. }
  739. next;
  740. # Skip .rus. files
  741. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  742. if ($DEBUG) {
  743. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  744. }
  745. next;
  746. # Skip German files
  747. } elsif ($tor->{'title'} =~ /german/i) {
  748. if ($DEBUG) {
  749. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  750. }
  751. next;
  752. # Skip French files
  753. } elsif ($tor->{'title'} =~ /french/i) {
  754. if ($DEBUG) {
  755. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  756. }
  757. next;
  758. # Skip unedited files
  759. } elsif ($tor->{'title'} =~ /unedited/i) {
  760. if ($DEBUG) {
  761. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  762. }
  763. next;
  764. }
  765. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  766. if (!$CUSTOM_SEARCH) {
  767. # Skip files that don't contain the right season number
  768. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  769. if ($DEBUG) {
  770. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  771. }
  772. next;
  773. # Skip files that don't contain the episode number
  774. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })) {
  775. if ($DEBUG) {
  776. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  777. }
  778. next;
  779. }
  780. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  781. # Skip files that don't match the regex
  782. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  783. if ($DEBUG) {
  784. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  785. }
  786. next;
  787. }
  788. }
  789. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  790. if (!$NO_QUALITY_CHECKS) {
  791. # Skip torrents with too few seeders/leachers
  792. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  793. if ($DEBUG) {
  794. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  795. }
  796. next;
  797. # Skip torrents with unusual seed/leach ratios
  798. } elsif ($tor->{'seeds'} > 1
  799. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  800. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  801. {
  802. if ($DEBUG) {
  803. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  804. }
  805. next;
  806. # Skip torrents that are too small
  807. } elsif ($tor->{'size'} < $MIN_SIZE) {
  808. if ($DEBUG) {
  809. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  810. }
  811. next;
  812. }
  813. }
  814. # Save good torrents
  815. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  816. if ($DEBUG) {
  817. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  818. }
  819. }
  820. # Find the average torrent size for each episode
  821. my %avg = ();
  822. foreach my $episode (keys(%tors)) {
  823. my $count = 0;
  824. $avg{$episode} = 0.001;
  825. foreach my $tor (@{ $tors{$episode} }) {
  826. $avg{$episode} += $tor->{'size'};
  827. $count++;
  828. }
  829. if ($count > 0) {
  830. $avg{$episode} /= $count;
  831. }
  832. if ($DEBUG) {
  833. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  834. }
  835. }
  836. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  837. foreach my $episode (keys(%tors)) {
  838. foreach my $tor (@{ $tors{$episode} }) {
  839. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  840. # Start with the peer count
  841. $tor->{'adj_count'} = $count;
  842. # Adjust based on file size
  843. {
  844. my $size_ratio = $tor->{'size'} / $avg{$episode};
  845. if ($tor->{'size'} >= $avg{$episode}) {
  846. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  847. } else {
  848. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  849. }
  850. }
  851. # Adjust based on title contents
  852. if ($tor->{'title'} =~ /Subtitulado/i) {
  853. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  854. }
  855. # Truncate to an integer
  856. $tor->{'adj_count'} = int($tor->{'adj_count'});
  857. if ($DEBUG) {
  858. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  859. }
  860. }
  861. }
  862. # Pick the best-adjusted-count torrent for each episode
  863. my %urls = ();
  864. foreach my $episode (keys(%tors)) {
  865. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  866. my $max = undef();
  867. foreach my $tor (@sorted) {
  868. if (!defined($max) || $tor->{'adj_count'} > $max) {
  869. if ($urls{$episode} = resolveSecondary($tor)) {
  870. $max = $tor->{'adj_count'};
  871. }
  872. if ($DEBUG) {
  873. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  874. }
  875. } elsif ($DEBUG) {
  876. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  877. }
  878. }
  879. }
  880. # Output
  881. foreach my $episode (keys(%tors)) {
  882. if (defined($urls{$episode})) {
  883. print $urls{$episode} . "\n";
  884. if ($DEBUG) {
  885. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  886. }
  887. } elsif ($DEBUG) {
  888. print STDERR 'No URL found for URL: ' . $episode . "\n";
  889. }
  890. }
  891. # Cleanup
  892. unlink($cookies);
  893. exit(0);
  894. # Resolve secondary URLs
  895. sub resolveSecondary($) {
  896. my ($tor) = @_;
  897. my $url = $tor->{'url'};
  898. if ($tor->{'source'} eq 'ISO') {
  899. if ($DEBUG) {
  900. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  901. $fetch->file('/tmp/findTorrent-secondary.html');
  902. }
  903. sleep($DELAY * (rand(2) + 0.5));
  904. $fetch->url($tor->{'url'});
  905. $fetch->fetch();
  906. if ($fetch->status_code() != 200) {
  907. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  908. return undef();
  909. }
  910. ($url) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  911. if (!defined($url) || length($url) < 1) {
  912. if ($DEBUG) {
  913. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  914. }
  915. return undef();
  916. }
  917. }
  918. return $url;
  919. }
  920. sub splitTRs($) {
  921. my ($content) = @_;
  922. # Find each TR element
  923. my @trs = ();
  924. my @rawTRs = split(/\<tr(?:\s+[^\>]*)?\>/i, $content);
  925. foreach my $tr (@rawTRs) {
  926. # Trim trailing tags and skip things that aren't complete TRs
  927. if (!($tr =~ s/\<\/tr\>.*$//is)) {
  928. if ($DEBUG > 1) {
  929. print STDERR 'Skipping non-TR line: ' . $tr . "\n\n";
  930. }
  931. next;
  932. }
  933. # Skip header rows
  934. if ($tr =~ /<th(?:\s+[^\>]*)?\>/i) {
  935. if ($DEBUG > 2) {
  936. print STDERR 'Skipping header TR line: ' . $tr . "\n\n";
  937. }
  938. next;
  939. }
  940. # Save good TRs
  941. push(@trs, $tr);
  942. }
  943. return @trs;
  944. }
  945. # Extract season
  946. sub findSE($) {
  947. my ($title) = @_;
  948. my $season = 0;
  949. my $episode = 0;
  950. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  951. $season = $1;
  952. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  953. $season = $1;
  954. $episode = $2;
  955. }
  956. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  957. $episode = $1;
  958. }
  959. $season = int($season);
  960. $episode = int($episode);
  961. return ($season, $episode);
  962. }