findTorrent.pl 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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' => 1, 'ISO' => 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. # Sanity check
  132. if (scalar(keys(%SOURCES)) < 1) {
  133. die("No sources available\n");
  134. }
  135. # Environment
  136. #if ($DEBUG) {
  137. # print STDERR `printenv` . "\n";
  138. #}
  139. # Figure out what we're searching for
  140. my $show = '';
  141. my @urls = ();
  142. my $CUSTOM_SEARCH = 0;
  143. my $season = 0;
  144. my @need = ();
  145. my %need = ();
  146. # Clean up the input "directory" path
  147. {
  148. # Allow use of the raw series name
  149. if (!($dir =~ /\//)) {
  150. $show = $dir;
  151. $dir = $TV_DIR . '/' . $dir;
  152. }
  153. # Allow use of relative paths
  154. $dir = File::Spec->rel2abs($dir);
  155. # Sanity check
  156. if (!-d $dir) {
  157. die('Invalid input directory: ' . $dir . "\n");
  158. }
  159. # Isolate the season from the path, if provided
  160. $dir =~ /\/Season\s+(\d+)\/?$/i;
  161. if ($1) {
  162. $season = $1;
  163. $dir = dirname($dir);
  164. }
  165. # If no season is provided find the latest
  166. if (!$season) {
  167. opendir(SERIES, $dir)
  168. or die("Unable to open series directory: ${!}\n");
  169. while (my $file = readdir(SERIES)) {
  170. if ($file =~ /^Season\s+(\d+)$/i) {
  171. if (!$season || $season < $1) {
  172. $season = $1;
  173. }
  174. }
  175. }
  176. closedir(SERIES);
  177. }
  178. # Isolate and clean the series name
  179. if (!$show) {
  180. $show = basename($dir);
  181. }
  182. $show =~ s/[\'\"\.]//g;
  183. if ($DEBUG) {
  184. print STDERR 'Checking directory: ' . $dir . "\n";
  185. }
  186. }
  187. # Allow quality checks to be disabled
  188. if (-e $dir . '/no_quality_checks') {
  189. $NO_QUALITY_CHECKS = 1;
  190. }
  191. # Read the excludes file, if any
  192. my $exclude = '';
  193. if (-e $dir . '/excludes') {
  194. local $/ = undef;
  195. open(EX, $dir . '/excludes')
  196. or die("Unable to open excludes file: ${!}\n");
  197. my $ex = <EX>;
  198. close(EX);
  199. $ex =~ s/^\s+//;
  200. $ex =~ s/^\s+//;
  201. my @excludes = split(/\s*,\s*/, $ex);
  202. foreach my $ex (@excludes) {
  203. if (length($exclude)) {
  204. $exclude .= ' ';
  205. }
  206. $exclude .= '-"' . $ex . '"';
  207. }
  208. $exclude = uri_encode(' ' . $exclude);
  209. }
  210. # Handle custom searches
  211. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  212. # Note the custom search string
  213. $CUSTOM_SEARCH = 1;
  214. if ($DEBUG) {
  215. print STDERR "Custom search\n";
  216. }
  217. # Create the relevent search strings
  218. foreach my $key (keys(%SOURCES)) {
  219. my $source = $SOURCES{$key};
  220. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  221. }
  222. }
  223. # Handle search-by-date series
  224. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  225. # Note the search-by-date status
  226. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  227. $CUSTOM_SEARCH = 1;
  228. if ($DEBUG) {
  229. print STDERR "Find by date\n";
  230. }
  231. # Read the find-by-date string
  232. my $search_by_date = '';
  233. local ($/, *FH);
  234. open(FH, $dir . '/search_by_date')
  235. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  236. my $text = <FH>;
  237. close(FH);
  238. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  239. $search_by_date = $1;
  240. } else {
  241. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  242. }
  243. # Create search strings for each date in the range, unless the related file already exists
  244. my (%years, %months, %days) = ();
  245. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  246. # Calculate the date
  247. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  248. # Format as strings
  249. $year = sprintf('%04d', $year + 1900);
  250. $month = sprintf('%02d', $month + 1);
  251. $day = sprintf('%02d', $day);
  252. # Check for an existing file
  253. my $exists = 0;
  254. {
  255. my $season_dir = $dir . '/Season ' . $year;
  256. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  257. opendir(SEASON, $season_dir)
  258. or die("Unable to open season directory: ${!}\n");
  259. while (my $file = readdir(SEASON)) {
  260. if ($file =~ $prefix) {
  261. $exists = 1;
  262. last;
  263. }
  264. }
  265. closedir(SEASON);
  266. }
  267. if ($exists) {
  268. next;
  269. }
  270. # Save all the date string components
  271. $years{$year} = 1;
  272. $months{$month} = 1;
  273. $days{$day} = 1;
  274. # Create the relevent search strings
  275. my $search_str = $search_by_date;
  276. $search_str =~ s/%Y/${year}/g;
  277. $search_str =~ s/%m/${month}/g;
  278. $search_str =~ s/%d/${day}/g;
  279. foreach my $key (keys(%SOURCES)) {
  280. my $source = $SOURCES{$key};
  281. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  282. }
  283. }
  284. # Build a date string matching regex
  285. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  286. $str .= '.*';
  287. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  288. $str .= '.*';
  289. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  290. $CUSTOM_SEARCH = qr/${str}/;
  291. }
  292. # Handle standard series
  293. if (scalar(@urls) < 1) {
  294. # Allow use of more number formats
  295. if (-e $dir . '/more_number_formats') {
  296. $MORE_NUMBER_FORMATS = 1;
  297. }
  298. # Allow the show name to be overriden
  299. {
  300. my $search_name = $dir . '/search_name';
  301. if (-e $search_name) {
  302. local ($/, *FH);
  303. open(FH, $search_name)
  304. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  305. my $text = <FH>;
  306. close(FH);
  307. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  308. $show = $1;
  309. } else {
  310. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  311. }
  312. }
  313. }
  314. if ($DEBUG) {
  315. print STDERR 'Searching with series title: ' . $show . "\n";
  316. }
  317. # Validate the season number
  318. if (!defined($season) || $season < 1 || $season > 2000) {
  319. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  320. }
  321. # Get the last episode number
  322. my $no_next = 0;
  323. my %episodes = ();
  324. my $highest = 0;
  325. opendir(SEASON, $dir . '/Season ' . $season)
  326. or die("Unable to open season directory: ${!}\n");
  327. while (my $file = readdir(SEASON)) {
  328. # Skip support files
  329. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  330. next;
  331. }
  332. # Check for a season_done file
  333. if ($file eq 'season_done') {
  334. $no_next = 1;
  335. next;
  336. }
  337. # Extract the episode number
  338. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  339. if (defined($num)) {
  340. $num = int($num);
  341. if ($DEBUG) {
  342. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  343. }
  344. # Record it
  345. $episodes{$num} = 1;
  346. # Track the highest episode number
  347. if ($num > $highest) {
  348. $highest = $num;
  349. }
  350. }
  351. }
  352. close(SEASON);
  353. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  354. if (!$no_next) {
  355. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  356. push(@need, $highest + $i);
  357. }
  358. }
  359. # Find any missing episodes
  360. for (my $i = 1 ; $i <= $highest ; $i++) {
  361. if (!$episodes{$i}) {
  362. push(@need, $i);
  363. }
  364. }
  365. if ($DEBUG) {
  366. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  367. }
  368. # Reverse the array for later matching
  369. foreach my $episode (@need) {
  370. $need{$episode} = 1;
  371. }
  372. # Construct a URL-friendly show name
  373. my $safeShow = $show;
  374. $safeShow =~ s/\s+\&\s+/ and /i;
  375. $safeShow =~ s/^\s*The\b//i;
  376. $safeShow =~ s/\s+\-\s+/ /g;
  377. $safeShow =~ s/[\'\:]//g;
  378. $safeShow =~ s/[^\w\"\-]+/ /g;
  379. $safeShow =~ s/^\s+//;
  380. $safeShow =~ s/\s+$//;
  381. $safeShow =~ s/\s\s+/ /g;
  382. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  383. $safeShow =~ s/\%20/\+/g;
  384. # Calculate possible name variations
  385. my @urlShowVarients = ();
  386. {
  387. # Default name
  388. push(@urlShowVarients, $safeShow);
  389. # Search for both "and" and "&"
  390. if ($safeShow =~ /\+and\+/i) {
  391. my $tmp = $safeShow;
  392. $tmp =~ s/\+and\+/\+%26\+/;
  393. push(@urlShowVarients, $tmp);
  394. }
  395. }
  396. # Construct the URL for each title varient of each needed episode
  397. foreach my $urlShow (@urlShowVarients) {
  398. foreach my $episode (@need) {
  399. my $episode_long = sprintf('%02d', $episode);
  400. my $season_long = sprintf('%02d', $season);
  401. foreach my $source (values(%SOURCES)) {
  402. # Use quotes around the show name if the source needs them
  403. my $quote = '%22';
  404. if (!$source->{'quote'}) {
  405. $quote = '';
  406. }
  407. # Calculate the compete search prefix and suffix to simplify later concatenations
  408. my $prefix = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote;
  409. my $suffix = $exclude;
  410. if ($source->{'search_suffix'}) {
  411. $suffix .= $source->{'search_suffix'};
  412. }
  413. # SXXEYY
  414. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  415. push(@urls, $url);
  416. # Extra searches for shows that have lazy/non-standard number formats
  417. if ($MORE_NUMBER_FORMATS) {
  418. # SXEY
  419. if ($season_long ne $season || $episode_long ne $episode) {
  420. $url = $prefix . '+s' . $season . 'e' . $episode . $exclude;
  421. push(@urls, $url);
  422. }
  423. # SXX EYY
  424. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $exclude;
  425. push(@urls, $url);
  426. # Season XX Episode YY
  427. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $exclude;
  428. push(@urls, $url);
  429. # Series X Episode Y
  430. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $exclude;
  431. push(@urls, $url);
  432. # SxEE
  433. $url = $prefix . '+' . $season . 'x' . $episode_long . $exclude;
  434. push(@urls, $url);
  435. }
  436. }
  437. }
  438. }
  439. }
  440. my @html_content = ();
  441. my @json_content = ();
  442. foreach my $url (@urls) {
  443. # Fetch the page
  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();
  451. # Check for errors
  452. if ($fetch->status_code() != 200) {
  453. print STDERR 'Error fetching URL: ' . $url . "\n";
  454. }
  455. # Save the content, discriminating by data type
  456. if ($DEBUG) {
  457. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  458. }
  459. if ($fetch->content() =~ /^\s*{/) {
  460. my $json = eval { decode_json($fetch->content()); };
  461. if (defined($json) && ref($json)) {
  462. push(@json_content, \@{ $json->{'items'}->{'list'} });
  463. } elsif ($DEBUG) {
  464. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  465. }
  466. } else {
  467. push(@html_content, scalar($fetch->content()));
  468. }
  469. }
  470. # We need someplace to store parsed torrent data from the various sources
  471. my @tors = ();
  472. # Handle HTML content
  473. foreach my $content (@html_content) {
  474. if ($content =~ /\<title\>The Pirate Bay/i) {
  475. # Find TR elements from TPB
  476. my @trs = splitTRs($content);
  477. foreach my $tr (@trs) {
  478. # Find the show title
  479. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  480. if (!defined($title) || length($title) < 1) {
  481. if ($DEBUG) {
  482. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  483. }
  484. next;
  485. }
  486. $title =~ s/^\s+//;
  487. # Extract the season and episode numbers
  488. my ($fileSeason, $episode) = findSE($title);
  489. # Extract the URL
  490. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  491. if (!defined($url) || length($url) < 1) {
  492. if ($DEBUG) {
  493. print STDERR "Skipping TR with no magnet URL\n";
  494. }
  495. next;
  496. }
  497. # Count the sum of seeders and leachers
  498. my $seeds = 0;
  499. my $leaches = 0;
  500. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  501. $seeds = $1;
  502. $leaches = $2;
  503. }
  504. # Extract the size (from separate column or inline)
  505. my $size = 0;
  506. my $unit = 'M';
  507. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  508. $size = $1;
  509. $unit = $2;
  510. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  511. $size = $1;
  512. $unit = $2;
  513. }
  514. if ($unit eq 'G') {
  515. $size *= 1024;
  516. }
  517. $size = int($size);
  518. if ($DEBUG) {
  519. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  520. }
  521. # Save the extracted data
  522. my %tor = (
  523. 'title' => $title,
  524. 'season' => $fileSeason,
  525. 'episode' => $episode,
  526. 'seeds' => $seeds,
  527. 'leaches' => $leaches,
  528. 'size' => $size,
  529. 'url' => $url,
  530. 'source' => 'TPB'
  531. );
  532. push(@tors, \%tor);
  533. }
  534. } elsif ($content =~ /Isohunt Torrent Search Engine\<\/title\>/i) {
  535. # Find each TR element from ISOHunt
  536. my @trs = splitTRs($content);
  537. foreach my $tr (@trs) {
  538. # Split each TD element from the row
  539. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  540. if (scalar(@tds) != 10) {
  541. print STDERR 'Invalid ISO TR: ' . $tr . "\n";
  542. next;
  543. }
  544. # Skip sponsored results
  545. if ($tds[1] =~ /Sponsored\<\/td\>/i) {
  546. if ($DEBUG > 1) {
  547. print STDERR "Skipping sponsored result\n";
  548. }
  549. next;
  550. }
  551. # Find the torrent ID and show title
  552. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+)\/[^\"]*\"\>\<span\>([^\>]+)\<\/span\>/i;
  553. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  554. if ($DEBUG) {
  555. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  556. }
  557. next;
  558. }
  559. $title =~ s/^\s+//;
  560. # Extract the season and episode numbers
  561. my ($fileSeason, $episode) = findSE($title);
  562. # Extract the size
  563. my $size = 0;
  564. my $unit = 'M';
  565. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  566. $size = $1;
  567. $unit = $2;
  568. }
  569. if ($unit eq 'G') {
  570. $size *= 1024;
  571. }
  572. $size = int($size);
  573. # Count the sum of seeders and leachers
  574. my $seeds = 0;
  575. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  576. $seeds = $1;
  577. }
  578. my $leaches = 0;
  579. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  580. $leaches = $1;
  581. }
  582. # Fetch the detail page for the URL
  583. my $url = $PROTOCOL . '://' . $SOURCES{'ISO'}->{'host'} . '/torrent_details/' . $id . '/';
  584. if ($DEBUG) {
  585. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  586. }
  587. # Save the extracted data
  588. my %tor = (
  589. 'title' => $title,
  590. 'season' => $fileSeason,
  591. 'episode' => $episode,
  592. 'seeds' => $seeds,
  593. 'leaches' => $leaches,
  594. 'size' => $size,
  595. 'url' => $url,
  596. 'source' => 'ISO'
  597. );
  598. push(@tors, \%tor);
  599. }
  600. } else {
  601. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  602. }
  603. }
  604. # Handle JSON content
  605. foreach my $content (@json_content) {
  606. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  607. }
  608. # Filter for size/count/etc.
  609. my %tors = ();
  610. my $showRegex = undef();
  611. {
  612. my $showClean = $show;
  613. $showClean =~ s/[\"\']//g;
  614. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  615. $showRegex = qr/^${showClean}[\W_]/i;
  616. }
  617. foreach my $tor (@tors) {
  618. # Skip files that don't start with our show title
  619. if (!($tor->{'title'} =~ $showRegex)) {
  620. if ($DEBUG) {
  621. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  622. }
  623. next;
  624. # Skip pre-air files
  625. } elsif ($tor->{'title'} =~ /preair/i) {
  626. if ($DEBUG) {
  627. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  628. }
  629. next;
  630. # Skip SWESUB files
  631. } elsif ($tor->{'title'} =~ /swesub/i) {
  632. if ($DEBUG) {
  633. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  634. }
  635. next;
  636. # Skip .rus. files
  637. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  638. if ($DEBUG) {
  639. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  640. }
  641. next;
  642. # Skip german files
  643. } elsif ($tor->{'title'} =~ /german/i) {
  644. if ($DEBUG) {
  645. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  646. }
  647. next;
  648. # Skip unedited files
  649. } elsif ($tor->{'title'} =~ /unedited/i) {
  650. if ($DEBUG) {
  651. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  652. }
  653. next;
  654. }
  655. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  656. if (!$CUSTOM_SEARCH) {
  657. # Skip files that don't contain the right season number
  658. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  659. if ($DEBUG) {
  660. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  661. }
  662. next;
  663. # Skip files that don't contain the episode number
  664. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })) {
  665. if ($DEBUG) {
  666. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  667. }
  668. next;
  669. }
  670. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  671. # Skip files that don't match the regex
  672. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  673. if ($DEBUG) {
  674. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  675. }
  676. next;
  677. }
  678. }
  679. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  680. if (!$NO_QUALITY_CHECKS) {
  681. # Skip torrents with too few seeders/leachers
  682. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  683. if ($DEBUG) {
  684. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  685. }
  686. next;
  687. # Skip torrents with unusual seed/leach ratios
  688. } elsif ($tor->{'seeds'} > 1
  689. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  690. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  691. {
  692. if ($DEBUG) {
  693. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  694. }
  695. next;
  696. # Skip torrents that are too small
  697. } elsif ($tor->{'size'} < $MIN_SIZE) {
  698. if ($DEBUG) {
  699. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  700. }
  701. next;
  702. }
  703. }
  704. # Save good torrents
  705. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  706. if ($DEBUG) {
  707. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  708. }
  709. }
  710. # Find the average torrent size for each episode
  711. my %avg = ();
  712. foreach my $episode (keys(%tors)) {
  713. my $count = 0;
  714. $avg{$episode} = 0.001;
  715. foreach my $tor (@{ $tors{$episode} }) {
  716. $avg{$episode} += $tor->{'size'};
  717. $count++;
  718. }
  719. if ($count > 0) {
  720. $avg{$episode} /= $count;
  721. }
  722. if ($DEBUG) {
  723. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  724. }
  725. }
  726. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  727. foreach my $episode (keys(%tors)) {
  728. foreach my $tor (@{ $tors{$episode} }) {
  729. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  730. # Start with the peer count
  731. $tor->{'adj_count'} = $count;
  732. # Adjust based on file size
  733. {
  734. my $size_ratio = $tor->{'size'} / $avg{$episode};
  735. if ($tor->{'size'} >= $avg{$episode}) {
  736. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  737. } else {
  738. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  739. }
  740. }
  741. # Adjust based on title contents
  742. if ($tor->{'title'} =~ /Subtitulado/i) {
  743. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  744. }
  745. # Truncate to an integer
  746. $tor->{'adj_count'} = int($tor->{'adj_count'});
  747. if ($DEBUG) {
  748. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  749. }
  750. }
  751. }
  752. # Pick the best-adjusted-count torrent for each episode
  753. my %urls = ();
  754. foreach my $episode (keys(%tors)) {
  755. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  756. my $max = undef();
  757. foreach my $tor (@sorted) {
  758. if (!defined($max) || $tor->{'adj_count'} > $max) {
  759. if ($urls{$episode} = resolveSecondary($tor)) {
  760. $max = $tor->{'adj_count'};
  761. }
  762. if ($DEBUG) {
  763. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  764. }
  765. } elsif ($DEBUG) {
  766. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  767. }
  768. }
  769. }
  770. # Output
  771. foreach my $episode (keys(%tors)) {
  772. if (defined($urls{$episode})) {
  773. print $urls{$episode} . "\n";
  774. if ($DEBUG) {
  775. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  776. }
  777. } elsif ($DEBUG) {
  778. print STDERR 'No URL found for URL: ' . $episode . "\n";
  779. }
  780. }
  781. # Cleanup
  782. unlink($cookies);
  783. exit(0);
  784. # Resolve secondary URLs
  785. sub resolveSecondary($) {
  786. my ($tor) = @_;
  787. my $url = $tor->{'url'};
  788. if ($tor->{'source'} eq 'ISO') {
  789. if ($DEBUG) {
  790. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  791. $fetch->file('/tmp/findTorrent-secondary.html');
  792. }
  793. sleep($DELAY * (rand(2) + 0.5));
  794. $fetch->url($tor->{'url'});
  795. $fetch->fetch();
  796. if ($fetch->status_code() != 200) {
  797. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  798. return undef();
  799. }
  800. ($url) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  801. if (!defined($url) || length($url) < 1) {
  802. if ($DEBUG) {
  803. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  804. }
  805. return undef();
  806. }
  807. }
  808. return $url;
  809. }
  810. sub splitTRs($) {
  811. my ($content) = @_;
  812. # Find each TR element
  813. my @trs = ();
  814. my @rawTRs = split(/\<tr(?:\s+[^\>]*)?\>/i, $content);
  815. foreach my $tr (@rawTRs) {
  816. # Trim trailing tags and skip things that aren't complete TRs
  817. if (!($tr =~ s/\<\/tr\>.*$//is)) {
  818. if ($DEBUG > 1) {
  819. print STDERR 'Skipping non-TR line: ' . $tr . "\n\n";
  820. }
  821. next;
  822. }
  823. # Skip header rows
  824. if ($tr =~ /<th(?:\s+[^\>]*)?\>/i) {
  825. if ($DEBUG > 2) {
  826. print STDERR 'Skipping header TR line: ' . $tr . "\n\n";
  827. }
  828. next;
  829. }
  830. # Save good TRs
  831. push(@trs, $tr);
  832. }
  833. return @trs;
  834. }
  835. # Extract season
  836. sub findSE($) {
  837. my ($title) = @_;
  838. my $season = 0;
  839. my $episode = 0;
  840. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  841. $season = $1;
  842. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  843. $season = $1;
  844. $episode = $2;
  845. }
  846. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  847. $episode = $1;
  848. }
  849. $season = int($season);
  850. $episode = int($episode);
  851. return ($season, $episode);
  852. }