findTorrent.pl 24 KB

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