findTorrent.pl 22 KB

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