findTorrent.pl 17 KB

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