findTorrent.pl 16 KB

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