findTorrent.pl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Defaults
  5. my $DEBUG = 0;
  6. my $NO_QUALITY_CHECKS = 0;
  7. my $MORE_NUMBER_FORMATS = 0;
  8. my $MIN_DAYS_BACK = 0;
  9. my $MAX_DAYS_BACK = 3;
  10. # Local config
  11. my $TV_DIR = `~/bin/video/mediaPath` . '/TV';
  12. # Search parameters
  13. my $PROTOCOL = 'https';
  14. my %ENABLE_SOURCE = ('TPB' => 1, 'ISO' => 0);
  15. # Selection parameters
  16. my $MIN_COUNT = 10;
  17. my $MIN_SIZE = 100;
  18. my $SIZE_BONUS = 7;
  19. my $SIZE_PENALTY = $SIZE_BONUS;
  20. my $MAX_SEED_RATIO = .25;
  21. my $SEED_RATIO_COUNT = 10;
  22. # App config
  23. my $DELAY = 4;
  24. my $TIMEOUT = 15;
  25. my $UA = 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_5; en-us) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1';
  26. # Includes
  27. use JSON;
  28. use File::Temp;
  29. use File::Spec;
  30. use File::Basename;
  31. use FindBin qw($Bin);
  32. use lib $Bin;
  33. use Fetch;
  34. # Prototypes
  35. sub findSE($);
  36. # Command line
  37. my ($dir, $search) = @ARGV;
  38. if (!defined($dir)) {
  39. die('Usage: ' . basename($0) . " input_directory [search_string]\n");
  40. }
  41. if ($ENV{'DEBUG'}) {
  42. $DEBUG = 1;
  43. }
  44. if ($ENV{'NO_QUALITY_CHECKS'}) {
  45. $NO_QUALITY_CHECKS = 1;
  46. }
  47. if ($ENV{'MORE_NUMBER_FORMATS'}) {
  48. $MORE_NUMBER_FORMATS = 1;
  49. }
  50. if ($ENV{'MIN_DAYS_BACK'}) {
  51. $MIN_DAYS_BACK = $ENV{'MIN_DAYS_BACK'};
  52. }
  53. if ($ENV{'MAX_DAYS_BACK'}) {
  54. $MAX_DAYS_BACK = $ENV{'MAX_DAYS_BACK'};
  55. }
  56. # New fetch object
  57. my $cookies = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  58. my $fetch = Fetch->new(
  59. 'cookiefile' => $cookies,
  60. 'timeout' => $TIMEOUT,
  61. 'uas' => $UA
  62. );
  63. # Search sources
  64. my %SOURCES = ();
  65. # The Pirate Bay
  66. if ($ENABLE_SOURCE{'TPB'}) {
  67. # Available TPB proxies, in order of preference
  68. my @TPBs = ('thepiratebay.sx/search/', 'tpb.jasohack.com/index.php?loadurl=/search/', 'tpb.allestec.com/index.php?loadurl=/search/');
  69. # Automatically select a TPB proxy that returns a search page
  70. my $search_url = '';
  71. foreach my $url (@TPBs) {
  72. my ($host) = $url =~ /^([^\/]+)/;
  73. $fetch->url($PROTOCOL . '://' . $host);
  74. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /\bSearch\b/i) {
  75. $search_url = $url;
  76. last;
  77. } elsif ($DEBUG) {
  78. print STDERR 'TPB proxy not available: ' . $host . "\n";
  79. }
  80. }
  81. # Only add TPB if one of the proxies is up
  82. if ($search_url) {
  83. my %tmp = (
  84. 'search_url' => $search_url,
  85. 'search_suffix' => '/0/7/0',
  86. 'weight' => 1.5,
  87. 'quote' => '0'
  88. );
  89. $SOURCES{'TPB'} = \%tmp;
  90. }
  91. }
  92. # ISOhunt
  93. if ($ENABLE_SOURCE{'ISO'}) {
  94. # Available ISOhunt proxies, in order of preference
  95. my @ISOs = ('isohunt.com/js/json.php?rows=10&start=1&ihq=');
  96. # Automatically select a TPB proxy that returns the non-US page
  97. my $search_url = '';
  98. foreach my $url (@ISOs) {
  99. my ($host) = $url =~ /^([^\/]+)/;
  100. $fetch->url($PROTOCOL . '://' . $host);
  101. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ /Last\s+\d+\s+files\s+indexed/i) {
  102. $search_url = $url;
  103. last;
  104. } elsif ($DEBUG) {
  105. print STDERR 'ISOhunt proxy not available: ' . $host . "\n";
  106. }
  107. }
  108. # Only add ISOhunt if one of the proxies is up
  109. if ($search_url) {
  110. my %tmp = (
  111. 'search_url' => 'isohunt.com/js/json.php?rows=10&start=1&ihq=',
  112. 'search_suffix' => '',
  113. 'weight' => 0.30,
  114. 'quote' => 1
  115. );
  116. $SOURCES{'ISO'} = \%tmp;
  117. }
  118. }
  119. # Environment
  120. #if ($DEBUG) {
  121. # print STDERR `printenv` . "\n";
  122. #}
  123. # Figure out what we're searching for
  124. my $show = '';
  125. my @urls = ();
  126. my $CUSTOM_SEARCH = 0;
  127. my $season = 0;
  128. my @need = ();
  129. my %need = ();
  130. # Clean up the input "directory" path
  131. {
  132. # Allow use of the raw series name
  133. if (!($dir =~ /\//)) {
  134. $show = $dir;
  135. $dir = $TV_DIR . '/' . $dir;
  136. }
  137. # Allow use of relative paths
  138. $dir = File::Spec->rel2abs($dir);
  139. # Sanity check
  140. if (!-d $dir) {
  141. die('Invalid input directory: ' . $dir . "\n");
  142. }
  143. # Isolate the season from the path, if provided
  144. $dir =~ /\/Season\s+(\d+)\/?$/i;
  145. if ($1) {
  146. $season = $1;
  147. $dir = dirname($dir);
  148. }
  149. # If no season is provided find the latest
  150. if (!$season) {
  151. opendir(SERIES, $dir)
  152. or die("Unable to open series directory: ${!}\n");
  153. while (my $file = readdir(SERIES)) {
  154. if ($file =~ /^Season\s+(\d+)$/i) {
  155. if (!$season || $season < $1) {
  156. $season = $1;
  157. }
  158. }
  159. }
  160. closedir(SERIES);
  161. }
  162. # Isolate and clean the series name
  163. if (!$show) {
  164. $show = basename($dir);
  165. }
  166. $show =~ s/[\'\"\.]//g;
  167. if ($DEBUG) {
  168. print STDERR 'Checking directory: ' . $dir . "\n";
  169. }
  170. }
  171. # Allow quality checks to be disabled
  172. if (-e dirname($dir) . '/no_quality_checks') {
  173. $NO_QUALITY_CHECKS = 1;
  174. }
  175. # Handle custom searches
  176. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  177. # Note the custom search string
  178. $CUSTOM_SEARCH = 1;
  179. if ($DEBUG) {
  180. print STDERR "Custom search\n";
  181. }
  182. # Create the relevent search strings
  183. foreach my $key (keys(%SOURCES)) {
  184. my $source = $SOURCES{$key};
  185. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search . $source->{'search_suffix'});
  186. }
  187. }
  188. # Handle search-by-date series
  189. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  190. # Note the search-by-date status
  191. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  192. $CUSTOM_SEARCH = 1;
  193. if ($DEBUG) {
  194. print STDERR "Find by date\n";
  195. }
  196. # Read the find-by-date string
  197. my $search_by_date = '';
  198. local ($/, *FH);
  199. open(FH, $dir . '/search_by_date')
  200. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  201. my $text = <FH>;
  202. close(FH);
  203. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  204. $search_by_date = $1;
  205. } else {
  206. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  207. }
  208. # Create search strings for each date in the range, unless the related file already exists
  209. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  210. # Calculate the date
  211. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  212. # Format as strings
  213. $year = sprintf('%04d', $year + 1900);
  214. $month = sprintf('%02d', $month + 1);
  215. $day = sprintf('%02d', $day);
  216. # Check for an existing file
  217. my $exists = 0;
  218. {
  219. my $season_dir = $dir . '/Season ' . $year;
  220. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  221. opendir(SEASON, $season_dir)
  222. or die("Unable to open season directory: ${!}\n");
  223. while (my $file = readdir(SEASON)) {
  224. if ($file =~ $prefix) {
  225. $exists = 1;
  226. last;
  227. }
  228. }
  229. closedir(SEASON);
  230. }
  231. if ($exists) {
  232. next;
  233. }
  234. # Create the relevent search strings
  235. my $search_str = $search_by_date;
  236. $search_str =~ s/%Y/${year}/g;
  237. $search_str =~ s/%m/${month}/g;
  238. $search_str =~ s/%d/${day}/g;
  239. foreach my $key (keys(%SOURCES)) {
  240. my $source = $SOURCES{$key};
  241. push(@urls, $PROTOCOL . '://' . $source->{'search_url'} . $search_str . $source->{'search_suffix'});
  242. }
  243. }
  244. }
  245. # Handle standard series
  246. if (scalar(@urls) < 1) {
  247. # Allow use of more number formats
  248. if (-e dirname($dir) . '/more_number_formats') {
  249. $MORE_NUMBER_FORMATS = 1;
  250. }
  251. # Allow the show name to be overriden
  252. {
  253. my $search_name = dirname($dir) . '/search_name';
  254. if (-e $search_name) {
  255. local ($/, *FH);
  256. open(FH, $search_name)
  257. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  258. my $text = <FH>;
  259. close(FH);
  260. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  261. $show = $1;
  262. } else {
  263. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  264. }
  265. }
  266. }
  267. if ($DEBUG) {
  268. print STDERR 'Searching with series title: ' . $show . "\n";
  269. }
  270. # Validate the season number
  271. if (!defined($season) || $season < 1 || $season > 2000) {
  272. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  273. }
  274. # Get the last episode number
  275. my $no_next = 0;
  276. my %episodes = ();
  277. my $highest = 0;
  278. opendir(SEASON, $dir . '/Season ' . $season)
  279. or die("Unable to open season directory: ${!}\n");
  280. while (my $file = readdir(SEASON)) {
  281. # Skip support files
  282. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  283. next;
  284. }
  285. # Check for a season_done file
  286. if ($file eq 'season_done') {
  287. $no_next = 1;
  288. next;
  289. }
  290. # Extract the episode number
  291. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  292. if (defined($num)) {
  293. $num = int($num);
  294. if ($DEBUG) {
  295. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  296. }
  297. # Record it
  298. $episodes{$num} = 1;
  299. # Track the highest episode number
  300. if ($num > $highest) {
  301. $highest = $num;
  302. }
  303. }
  304. }
  305. close(SEASON);
  306. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  307. if (!$no_next) {
  308. @need = ($highest + 1, $highest + 2);
  309. }
  310. # Find any missing episodes
  311. for (my $i = 1 ; $i <= $highest ; $i++) {
  312. if (!$episodes{$i}) {
  313. push(@need, $i);
  314. }
  315. }
  316. if ($DEBUG) {
  317. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  318. }
  319. # Reverse the array for later matching
  320. foreach my $episode (@need) {
  321. $need{$episode} = 1;
  322. }
  323. # Check for URL files
  324. if (-e "${dir}/url") {
  325. open(URL, "${dir}/url")
  326. or die("Unable to open URLs file: ${!}\n");
  327. while (<URL>) {
  328. if (/^\s*[a-z]+(\:\S+)\s*$/) {
  329. push(@urls, $PROTOCOL . $1);
  330. }
  331. }
  332. close(URL);
  333. }
  334. # Construct a URL-friendly show name
  335. my $safeShow = $show;
  336. $safeShow =~ s/\s+\&\s+/ and /i;
  337. $safeShow =~ s/^\s*The\b//i;
  338. $safeShow =~ s/\'//g;
  339. $safeShow =~ s/[^\w\"\-]+/ /g;
  340. $safeShow =~ s/^\s+//;
  341. $safeShow =~ s/\s+$//;
  342. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  343. $safeShow =~ s/\%20/\+/g;
  344. # Calculate possible name variations
  345. my @urlShowVarients = ();
  346. {
  347. # Default name
  348. push(@urlShowVarients, $safeShow);
  349. # Search for both "and" and "&"
  350. if ($safeShow =~ /\+and\+/i) {
  351. my $tmp = $safeShow;
  352. $tmp =~ s/\+and\+/\+%26\+/;
  353. push(@urlShowVarients, $tmp);
  354. }
  355. }
  356. # Construct the URL for each title varient of each needed episode
  357. foreach my $urlShow (@urlShowVarients) {
  358. foreach my $episode (@need) {
  359. my $episode_long = sprintf('%02d', $episode);
  360. my $season_long = sprintf('%02d', $season);
  361. foreach my $source (values(%SOURCES)) {
  362. my $quote = '%22';
  363. if (!$source->{'quote'}) {
  364. $quote = '';
  365. }
  366. # SXXEYY
  367. my $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+s' . $season_long . 'e' . $episode_long;
  368. if ($source->{'search_suffix'}) {
  369. $url .= $source->{'search_suffix'};
  370. }
  371. push(@urls, $url);
  372. # Extra searches for shows that have lazy/non-standard number formats
  373. if ($MORE_NUMBER_FORMATS) {
  374. # SXEY
  375. if ($season_long ne $season || $episode_long ne $episode) {
  376. $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+s' . $season . 'e' . $episode;
  377. if ($source->{'search_suffix'}) {
  378. $url .= $source->{'search_suffix'};
  379. }
  380. }
  381. push(@urls, $url);
  382. # SXX EYY
  383. $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+s' . $season_long . '+e' . $episode_long;
  384. if ($source->{'search_suffix'}) {
  385. $url .= $source->{'search_suffix'};
  386. }
  387. push(@urls, $url);
  388. # Season XX Episode YY
  389. $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+season+' . $season_long . '+episode+' . $episode_long;
  390. if ($source->{'search_suffix'}) {
  391. $url .= $source->{'search_suffix'};
  392. }
  393. push(@urls, $url);
  394. # Series X Episode Y
  395. $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+series+' . $season . '+episode+' . $episode;
  396. if ($source->{'search_suffix'}) {
  397. $url .= $source->{'search_suffix'};
  398. }
  399. push(@urls, $url);
  400. # SxEE
  401. $url = $PROTOCOL . '://' . $source->{'search_url'} . $quote . $urlShow . $quote . '+' . $season . 'x' . $episode_long;
  402. if ($source->{'search_suffix'}) {
  403. $url .= $source->{'search_suffix'};
  404. }
  405. push(@urls, $url);
  406. }
  407. }
  408. }
  409. }
  410. }
  411. my $content = '';
  412. my @json_content = ();
  413. foreach my $url (@urls) {
  414. # Fetch the page
  415. if ($DEBUG) {
  416. print STDERR 'Searching with URL: ' . $url . "\n";
  417. $fetch->file('/tmp/findTorrent-lastPage.html');
  418. }
  419. sleep($DELAY * (rand(2) + 0.5));
  420. $fetch->url($url);
  421. $fetch->fetch();
  422. # Check for errors
  423. if ($fetch->status_code() != 200) {
  424. print STDERR 'Error fetching URL: ' . $url . "\n";
  425. }
  426. # Save and compact the content
  427. if ($DEBUG) {
  428. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  429. }
  430. if ($fetch->content() =~ /^\s*{/) {
  431. my $json = eval { decode_json($fetch->content()); };
  432. if (defined($json) && ref($json)) {
  433. push(@json_content, \@{ $json->{'items'}->{'list'} });
  434. } elsif ($DEBUG) {
  435. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  436. }
  437. } else {
  438. $content .= ' ' . $fetch->content();
  439. $content =~ s/\s+/ /g;
  440. }
  441. }
  442. # Find each TR element in TPB content
  443. my @tors = ();
  444. my @trs = split(/\<tr(?:\s+[^\>]*)?\>/i, $content);
  445. if ($DEBUG) {
  446. print STDERR 'TR count: ' . scalar(@trs) . "\n";
  447. }
  448. foreach my $tr (@trs) {
  449. # Trim trailing tags
  450. if (!($tr =~ s/\<\/tr\>.*$//is)) {
  451. # Skip things that aren't compelete TRs
  452. if ($DEBUG > 1) {
  453. print STDERR 'Skipping non-TR line: ' . $tr . "\n\n";
  454. }
  455. next;
  456. }
  457. # Find the show title
  458. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  459. if (!defined($title) || length($title) < 1) {
  460. if ($DEBUG) {
  461. print STDERR "Unable to find show title in TR\n";
  462. }
  463. next;
  464. }
  465. $title =~ s/^\s+//;
  466. # Extract the season and episode numbers
  467. my ($fileSeason, $episode) = findSE($title);
  468. # Extract the URL
  469. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  470. if (!defined($url) || length($url) < 1) {
  471. if ($DEBUG) {
  472. print STDERR "Skipping TR with no magnet URL\n";
  473. }
  474. next;
  475. }
  476. # Count the sum of seeders and leachers
  477. my $seeds = 0;
  478. my $leaches = 0;
  479. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  480. $seeds = $1;
  481. $leaches = $2;
  482. }
  483. # Extract the size (from separate column or inline)
  484. my $size = 0;
  485. my $unit = 'M';
  486. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  487. $size = $1;
  488. $unit = $2;
  489. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  490. $size = $1;
  491. $unit = $2;
  492. }
  493. if ($unit eq 'G') {
  494. $size *= 1024;
  495. }
  496. $size = int($size);
  497. if ($DEBUG) {
  498. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  499. }
  500. # Save the extracted data
  501. my %tor = (
  502. 'title' => $title,
  503. 'season' => $fileSeason,
  504. 'episode' => $episode,
  505. 'seeds' => $seeds,
  506. 'leaches' => $leaches,
  507. 'size' => $size,
  508. 'url' => $url,
  509. 'source' => 'TPB'
  510. );
  511. push(@tors, \%tor);
  512. }
  513. # Find each discrete torrent from ISOhunt
  514. foreach my $json (@json_content) {
  515. foreach my $tor (@{$json}) {
  516. # Extract the title
  517. my $title = $tor->{'title'};
  518. $title =~ s/\<\/?b\>//gi;
  519. $title =~ s/^\s+//;
  520. # Extract the season and episode numbers
  521. my ($fileSeason, $episode) = findSE($tor->{'title'});
  522. # Count the sum of seeders and leachers
  523. my $seeds = 0;
  524. my $leaches = 0;
  525. if (defined($tor->{'Seeds'}) && length($tor->{'Seeds'}) > 0) {
  526. $seeds = $tor->{'Seeds'};
  527. }
  528. if (defined($tor->{'leechers'}) && length($tor->{'leechers'}) > 0) {
  529. $leaches = $tor->{'leechers'};
  530. }
  531. # Extract the size
  532. my $size = 0;
  533. if (defined($tor->{'length'}) && length($tor->{'length'}) > 0) {
  534. $size = int($tor->{'length'} / 1048576);
  535. }
  536. if ($DEBUG) {
  537. print STDERR 'Found file (' . $title . '): ' . $tor->{'enclosure_url'} . "\n";
  538. }
  539. # Save the extracted data
  540. my %tmp = (
  541. 'title' => $title,
  542. 'season' => $fileSeason,
  543. 'episode' => $episode,
  544. 'seeds' => $seeds,
  545. 'leaches' => $leaches,
  546. 'size' => $size,
  547. 'url' => $tor->{'enclosure_url'},
  548. 'source' => 'ISO'
  549. );
  550. push(@tors, \%tmp);
  551. }
  552. }
  553. # Filter for size/count/etc.
  554. my %tors = ();
  555. my $showRegex = $show;
  556. $showRegex =~ s/[\"\']//g;
  557. $showRegex =~ s/[\W_]+/\[\\W_\].*/g;
  558. foreach my $tor (@tors) {
  559. # Skip files that don't start with our show title
  560. if (!($tor->{'title'} =~ /^${showRegex}[\W_]/i)) {
  561. if ($DEBUG) {
  562. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  563. }
  564. next;
  565. # Skip pre-air files
  566. } elsif ($tor->{'title'} =~ /preair/i) {
  567. if ($DEBUG) {
  568. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  569. }
  570. next;
  571. # Skip SWESUB files
  572. } elsif ($tor->{'title'} =~ /swesub/i) {
  573. if ($DEBUG) {
  574. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  575. }
  576. next;
  577. # Skip .rus. files
  578. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  579. if ($DEBUG) {
  580. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  581. }
  582. next;
  583. # Skip german files
  584. } elsif ($tor->{'title'} =~ /german/i) {
  585. if ($DEBUG) {
  586. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  587. }
  588. next;
  589. }
  590. # Only apply season and episode number matches if CUSTOM_SEARCH is not in effect
  591. if (!$CUSTOM_SEARCH) {
  592. # Skip files that don't contain the right season number
  593. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  594. if ($DEBUG) {
  595. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  596. }
  597. next;
  598. # Skip files that don't contain the episode number
  599. } elsif ((!defined($tor->{'episode'}) || !$need{ $tor->{'episode'} })) {
  600. if ($DEBUG) {
  601. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  602. }
  603. next;
  604. }
  605. }
  606. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  607. if (!$NO_QUALITY_CHECKS) {
  608. # Skip torrents with too few seeders/leachers
  609. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  610. if ($DEBUG) {
  611. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  612. }
  613. next;
  614. # Skip torrents with unusual seed/leach ratios
  615. } elsif ($tor->{'seeds'} > 1
  616. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  617. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  618. {
  619. if ($DEBUG) {
  620. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  621. }
  622. next;
  623. # Skip torrents that are too small
  624. } elsif ($tor->{'size'} < $MIN_SIZE) {
  625. if ($DEBUG) {
  626. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  627. }
  628. next;
  629. }
  630. }
  631. # Save good torrents
  632. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  633. if ($DEBUG) {
  634. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  635. }
  636. }
  637. # Find the average torrent size for each episode
  638. my %avg = ();
  639. foreach my $episode (keys(%tors)) {
  640. my $count = 0;
  641. $avg{$episode} = 0.001;
  642. foreach my $tor (@{ $tors{$episode} }) {
  643. $avg{$episode} += $tor->{'size'};
  644. $count++;
  645. }
  646. if ($count > 0) {
  647. $avg{$episode} /= $count;
  648. }
  649. if ($DEBUG) {
  650. print STDERR 'Episode ' . $episode . ' average size: ' . int($avg{$episode}) . " MiB\n";
  651. }
  652. }
  653. # Calculate an adjusted count based on the original count and the relative file size
  654. foreach my $episode (keys(%tors)) {
  655. foreach my $tor (@{ $tors{$episode} }) {
  656. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  657. if ($tor->{'size'} >= $avg{$episode}) {
  658. $tor->{'adj_count'} = int($count * ($SIZE_BONUS * ($tor->{'size'} / $avg{$episode})));
  659. } else {
  660. $tor->{'adj_count'} = int($count * ((1 / $SIZE_PENALTY) * ($tor->{'size'} / $avg{$episode})));
  661. }
  662. if ($DEBUG) {
  663. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  664. }
  665. }
  666. }
  667. # Pick the best-adjusted-count torrent for each episode
  668. my %urls = ();
  669. foreach my $episode (keys(%tors)) {
  670. my $max = undef();
  671. foreach my $tor (@{ $tors{$episode} }) {
  672. if (!defined($max) || $tor->{'adj_count'} > $max) {
  673. $urls{$episode} = $tor->{'url'};
  674. $max = $tor->{'adj_count'};
  675. if ($DEBUG) {
  676. print STDERR 'New semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  677. }
  678. } elsif ($DEBUG) {
  679. print STDERR 'Skipping for non-max adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  680. }
  681. }
  682. }
  683. # Output
  684. foreach my $episode (keys(%tors)) {
  685. if (defined($urls{$episode})) {
  686. print $urls{$episode} . "\n";
  687. if ($DEBUG) {
  688. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  689. }
  690. } elsif ($DEBUG) {
  691. print STDERR 'No URL found for URL: ' . $episode . "\n";
  692. }
  693. }
  694. # Cleanup
  695. unlink($cookies);
  696. exit(0);
  697. # Extract season
  698. sub findSE($) {
  699. my ($title) = @_;
  700. my $season = 0;
  701. my $episode = 0;
  702. if ($title =~ /[\W_]s(?:eason|eries)?\s*(\d+)/i) {
  703. $season = $1;
  704. } elsif ($title =~ /\b(\d+)x(\d+)\b/i) {
  705. $season = $1;
  706. $episode = $2;
  707. }
  708. if (!$episode && $title =~ /e(?:ipsode)?\s*(\d{1,2})/i) {
  709. $episode = $1;
  710. }
  711. $season = int($season);
  712. $episode = int($episode);
  713. return ($season, $episode);
  714. }