findTorrent.pl 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Defaults
  5. my $DEBUG = 0;
  6. my $SYSLOG = 1;
  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 = 'https';
  16. my %ENABLE_SOURCE = ('TPB' => 1, 'ISO' => 1, 'KICK' => 1, 'Z' => 0, 'ET' => 1);
  17. # Selection parameters
  18. my $MIN_COUNT = 10;
  19. my $MIN_SIZE = 100;
  20. my $SIZE_BONUS = 5;
  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. my $TRACKER_LOOKUP = 1;
  26. # App config
  27. my $DELAY = 10;
  28. my $TIMEOUT = 15;
  29. my $ERR_DELAY = $TIMEOUT * 2;
  30. my $ERR_RETRIES = 3;
  31. my $UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/538.39.41 (KHTML, like Gecko) Version/8.0 Safari/538.39.41';
  32. my $EXCLUDES_FILE = $ENV{'HOME'} . '/.findTorrent.exclude';
  33. # Static tracker list, appended to all magnet URIs
  34. my @TRACKERS = ('udp://open.demonii.com:1337/announce', 'udp://tracker.publicbt.com:80/announce', 'udp://tracker.openbittorrent.com:80/announce', 'udp://9.rarbg.com:2710/announce');
  35. # Includes
  36. use URI::Encode qw(uri_encode);
  37. use HTML::Entities;
  38. use HTML::Strip;
  39. use JSON;
  40. use Sys::Syslog qw(:standard :macros);
  41. use File::Temp;
  42. use File::Spec;
  43. use File::Basename;
  44. use FindBin qw($Bin);
  45. use lib $Bin;
  46. use Fetch;
  47. # Prototypes
  48. sub getHash($);
  49. sub resolveSecondary($);
  50. sub resolveTrackers($);
  51. sub splitTags($$$$);
  52. sub findSE($);
  53. sub initSources();
  54. sub findProxy($$);
  55. # Command line
  56. my ($dir, $search) = @ARGV;
  57. if (!defined($dir)) {
  58. die('Usage: ' . basename($0) . " input_directory [search_string]\n");
  59. }
  60. # Fetch object
  61. my $cookies = mktemp('/tmp/findTorrent.cookies.XXXXXXXX');
  62. my $fetch = Fetch->new(
  63. 'cookiefile' => $cookies,
  64. 'timeout' => $TIMEOUT,
  65. 'uas' => $UA
  66. );
  67. # Environment
  68. if ($ENV{'DEBUG'}) {
  69. if ($ENV{'DEBUG'} =~ /(\d+)/) {
  70. $DEBUG = $1;
  71. } else {
  72. $DEBUG = 1;
  73. }
  74. }
  75. if (exists($ENV{'EXCLUDES_FILE'})) {
  76. $EXCLUDES_FILE = $ENV{'EXCLUDES_FILE'};
  77. }
  78. if ($ENV{'NO_QUALITY_CHECKS'}) {
  79. $NO_QUALITY_CHECKS = 1;
  80. }
  81. if ($ENV{'MORE_NUMBER_FORMATS'}) {
  82. $MORE_NUMBER_FORMATS = 1;
  83. }
  84. if (defined($ENV{'MIN_DAYS_BACK'})) {
  85. $MIN_DAYS_BACK = $ENV{'MIN_DAYS_BACK'};
  86. }
  87. if (defined($ENV{'MAX_DAYS_BACK'})) {
  88. $MAX_DAYS_BACK = $ENV{'MAX_DAYS_BACK'};
  89. }
  90. if (defined($ENV{'NEXT_EPISODES'})) {
  91. $NEXT_EPISODES = $ENV{'NEXT_EPISODES'};
  92. }
  93. if (defined($ENV{'SYSLOG'})) {
  94. $SYSLOG = $ENV{'SYSLOG'};
  95. }
  96. # Open the log if enabled
  97. if ($SYSLOG) {
  98. openlog(basename($0), '', LOG_DAEMON);
  99. }
  100. # Read the torrent excludes list
  101. my %EXCLUDES = ();
  102. if ($EXCLUDES_FILE && -r $EXCLUDES_FILE) {
  103. my $fh;
  104. open($fh, '<', $EXCLUDES_FILE)
  105. or die('Unable to open excludes file: ' . $EXCLUDES_FILE . ': ' . $! . "\n");
  106. while (<$fh>) {
  107. # Skip blank lines and comments
  108. if (/^\s*$/ || /^\s*#/) {
  109. next;
  110. }
  111. # Assume everything else is one BT hash per line
  112. if (/^\s*(\w+)\s*$/) {
  113. my $hash = lc($1);
  114. if ($DEBUG > 1) {
  115. print STDERR 'Excluding hash: ' . $hash . "\n";
  116. }
  117. $EXCLUDES{$hash} = 1;
  118. } else {
  119. die('Invalid exclude line: ' . $_ . "\n");
  120. }
  121. }
  122. close($fh);
  123. } elsif ($DEBUG) {
  124. print STDERR 'No excludes file available';
  125. if ($EXCLUDES_FILE) {
  126. print STDERR ': ' . $EXCLUDES_FILE;
  127. }
  128. print STDERR "\n";
  129. }
  130. # Figure out what we're searching for
  131. my $show = '';
  132. my @urls = ();
  133. my $CUSTOM_SEARCH = 0;
  134. my $season = 0;
  135. my @need = ();
  136. my %need = ();
  137. # Clean up the input "directory" path
  138. {
  139. # Allow use of the raw series name
  140. if (!($dir =~ /\//)) {
  141. $show = $dir;
  142. $dir = $TV_DIR . '/' . $dir;
  143. }
  144. # Allow use of relative paths
  145. $dir = File::Spec->rel2abs($dir);
  146. # Sanity check
  147. if (!-d $dir) {
  148. die('Invalid input directory: ' . $dir . "\n");
  149. }
  150. # Isolate the season from the path, if provided
  151. $dir =~ /\/Season\s+(\d+)\/?$/i;
  152. if ($1) {
  153. $season = $1;
  154. $dir = dirname($dir);
  155. }
  156. # If no season is provided find the latest
  157. if (!$season) {
  158. opendir(SERIES, $dir)
  159. or die("Unable to open series directory: ${!}\n");
  160. while (my $file = readdir(SERIES)) {
  161. if ($file =~ /^Season\s+(\d+)$/i) {
  162. if (!$season || $season < $1) {
  163. $season = $1;
  164. }
  165. }
  166. }
  167. closedir(SERIES);
  168. }
  169. # Isolate and clean the series name
  170. if (!$show) {
  171. $show = basename($dir);
  172. }
  173. $show =~ s/[\'\"\.]//g;
  174. if ($DEBUG) {
  175. print STDERR 'Checking directory: ' . $dir . "\n";
  176. }
  177. if ($SYSLOG) {
  178. syslog(LOG_NOTICE, $show);
  179. }
  180. }
  181. # Allow the show name to be overriden
  182. {
  183. my $search_name = $dir . '/search_name';
  184. if (-e $search_name) {
  185. local ($/, *FH);
  186. open(FH, $search_name)
  187. or die('Unable to read search_name for show: ' . $show . ': ' . $! . "\n");
  188. my $text = <FH>;
  189. close(FH);
  190. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  191. $show = $1;
  192. } else {
  193. print STDERR 'Skipping invalid search_name for show: ' . $show . ': ' . $text . "\n";
  194. }
  195. }
  196. if ($DEBUG) {
  197. print STDERR 'Searching with series title: ' . $show . "\n";
  198. }
  199. }
  200. # Allow quality checks to be disabled
  201. if (-e $dir . '/no_quality_checks') {
  202. $NO_QUALITY_CHECKS = 1;
  203. if ($DEBUG) {
  204. print STDERR 'Searching with no quality checks: ' . $show . "\n";
  205. }
  206. }
  207. # Allow use of more number formats
  208. if (-e $dir . '/more_number_formats') {
  209. $MORE_NUMBER_FORMATS = 1;
  210. if ($DEBUG) {
  211. print STDERR 'Searching with more number formats: ' . $show . "\n";
  212. }
  213. }
  214. # Read the search excludes file, if any
  215. my $exclude = '';
  216. my %TITLE_EXCLUDES = ();
  217. if (-e $dir . '/excludes') {
  218. local $/ = undef;
  219. open(EX, $dir . '/excludes')
  220. or die("Unable to open series excludes file: ${!}\n");
  221. my $ex = <EX>;
  222. close(EX);
  223. $ex =~ s/^\s+//;
  224. $ex =~ s/\s+$//;
  225. my @excludes = split(/\s*,\s*/, $ex);
  226. foreach my $ex (@excludes) {
  227. $TITLE_EXCLUDES{$ex} = 1;
  228. if (length($exclude)) {
  229. $exclude .= ' ';
  230. }
  231. $exclude .= '-"' . $ex . '"';
  232. }
  233. $exclude = uri_encode(' ' . $exclude);
  234. }
  235. # Setup our sources
  236. my $SOURCES = initSources();
  237. # Adjust the inter-page delay with respect to the number of unique sources
  238. $DELAY /= scalar(keys(%{$SOURCES})) / 2;
  239. # Handle custom searches
  240. if ((scalar(@urls) < 1) && defined($search) && length($search) > 0) {
  241. # Note the custom search string
  242. $CUSTOM_SEARCH = 1;
  243. if ($DEBUG) {
  244. print STDERR "Custom search\n";
  245. }
  246. # Create the relevent search strings
  247. foreach my $key (keys(%{$SOURCES})) {
  248. my $source = $SOURCES->{$key};
  249. push(@urls, $source->{'search_url'} . $search . $exclude . $source->{'search_suffix'});
  250. }
  251. }
  252. # Handle search-by-date series
  253. if ((scalar(@urls) < 1) && -e $dir . '/search_by_date') {
  254. # Note the search-by-date status
  255. # Set the CUSTOM_SERACH flag to skip season/epsiode matching
  256. $CUSTOM_SEARCH = 1;
  257. # Read the find-by-date string
  258. my $search_by_date = '';
  259. local ($/, *FH);
  260. open(FH, $dir . '/search_by_date')
  261. or die('Unable to read search_by_date for show: ' . $show . ': ' . $! . "\n");
  262. my $text = <FH>;
  263. close(FH);
  264. if ($text =~ /^\s*(\S.*\S)\s*$/) {
  265. $search_by_date = $1;
  266. } else {
  267. die('Skipping invalid search_by_date for show: ' . $show . ': ' . $text . "\n");
  268. }
  269. # Create search strings for each date in the range, unless the related file already exists
  270. my (%years, %months, %days) = ();
  271. for (my $days_back = $MIN_DAYS_BACK ; $days_back <= $MAX_DAYS_BACK ; $days_back++) {
  272. # Calculate the date
  273. my (undef(), undef(), undef(), $day, $month, $year) = localtime(time() - (86400 * $days_back));
  274. # Format as strings
  275. $year = sprintf('%04d', $year + 1900);
  276. $month = sprintf('%02d', $month + 1);
  277. $day = sprintf('%02d', $day);
  278. # Check for an existing file
  279. my $exists = 0;
  280. {
  281. my $season_dir = $dir . '/Season ' . $year;
  282. my $prefix = qr/${year}\-${month}\-${day}\s*\-\s*/;
  283. opendir(SEASON, $season_dir)
  284. or die('Unable to open season directory (' . $season_dir . '): ' . $! . "\n");
  285. while (my $file = readdir(SEASON)) {
  286. if ($file =~ $prefix) {
  287. $exists = 1;
  288. last;
  289. }
  290. }
  291. closedir(SEASON);
  292. }
  293. if ($exists) {
  294. next;
  295. }
  296. # Save all the date string components
  297. $years{$year} = 1;
  298. $months{$month} = 1;
  299. $days{$day} = 1;
  300. # Create the relevent search strings
  301. my $search_str = $search_by_date;
  302. $search_str =~ s/%Y/${year}/g;
  303. $search_str =~ s/%m/${month}/g;
  304. $search_str =~ s/%d/${day}/g;
  305. foreach my $key (keys(%{$SOURCES})) {
  306. my $source = $SOURCES->{$key};
  307. push(@urls, $source->{'search_url'} . $search_str . $exclude . $source->{'search_suffix'});
  308. }
  309. }
  310. # Build a date string matching regex
  311. my $str = '\b(?:' . join('|', keys(%years)) . ')\b';
  312. $str .= '.*';
  313. $str .= '\b(?:' . join('|', keys(%months)) . ')\b';
  314. $str .= '.*';
  315. $str .= '\b(?:' . join('|', keys(%days)) . ')\b';
  316. $CUSTOM_SEARCH = qr/${str}/;
  317. # Debug
  318. if ($DEBUG) {
  319. print STDERR 'Seaching with date template: ' . $str . "\n";
  320. }
  321. }
  322. # Handle standard series
  323. if (scalar(@urls) < 1) {
  324. # Validate the season number
  325. if (!defined($season) || $season < 1 || $season > 2000) {
  326. die('Invalid season number: ' . $show . ' => ' . $season . "\n");
  327. }
  328. # Get the last episode number
  329. my $no_next = 0;
  330. my %episodes = ();
  331. my $highest = 0;
  332. opendir(SEASON, $dir . '/Season ' . $season)
  333. or die("Unable to open season directory: ${!}\n");
  334. while (my $file = readdir(SEASON)) {
  335. # Skip support files
  336. if ($file =~ /\.(?:png|xml|jpg|gif|tbn|txt|nfo|torrent)\s*$/i) {
  337. next;
  338. }
  339. # Check for a season_done file
  340. if ($file eq 'season_done') {
  341. $no_next = 1;
  342. next;
  343. }
  344. # Extract the episode number
  345. my ($num) = $file =~ /^\s*\.?(\d+)\s*\-\s*/i;
  346. if (defined($num)) {
  347. $num = int($num);
  348. if ($DEBUG) {
  349. print STDERR 'Found episode number: ' . $num . ' in file: ' . $file . "\n";
  350. }
  351. # Record it
  352. $episodes{$num} = 1;
  353. # Track the highest episode number
  354. if ($num > $highest) {
  355. $highest = $num;
  356. }
  357. }
  358. }
  359. close(SEASON);
  360. # Assume we need the next 2 episodes, unless no_next is set (i.e. season_done)
  361. if (!$no_next) {
  362. for (my $i = 1 ; $i <= $NEXT_EPISODES ; $i++) {
  363. push(@need, $highest + $i);
  364. }
  365. }
  366. # Find any missing episodes
  367. for (my $i = 1 ; $i <= $highest ; $i++) {
  368. if (!$episodes{$i}) {
  369. push(@need, $i);
  370. }
  371. }
  372. if ($DEBUG) {
  373. print STDERR 'Needed episodes: ' . join(', ', @need) . "\n";
  374. }
  375. # Reverse the array for later matching
  376. foreach my $episode (@need) {
  377. $need{$episode} = 1;
  378. }
  379. # Construct a URL-friendly show name
  380. my $safeShow = $show;
  381. $safeShow =~ s/\s+\&\s+/ and /i;
  382. $safeShow =~ s/^\s*The\b//i;
  383. $safeShow =~ s/\s+\-\s+/ /g;
  384. $safeShow =~ s/[\'\:]//g;
  385. $safeShow =~ s/[^\w\"\-]+/ /g;
  386. $safeShow =~ s/^\s+//;
  387. $safeShow =~ s/\s+$//;
  388. $safeShow =~ s/\s\s+/ /g;
  389. $safeShow =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  390. $safeShow =~ s/\%20/\+/g;
  391. # Calculate possible name variations
  392. my @urlShowVarients = ();
  393. {
  394. # Default name
  395. push(@urlShowVarients, $safeShow);
  396. # Search for both "and" and "&"
  397. if ($safeShow =~ /\+and\+/i) {
  398. my $tmp = $safeShow;
  399. $tmp =~ s/\+and\+/\+%26\+/;
  400. push(@urlShowVarients, $tmp);
  401. }
  402. }
  403. # Construct the URL for each title varient of each needed episode
  404. foreach my $urlShow (@urlShowVarients) {
  405. foreach my $episode (@need) {
  406. my $episode_long = sprintf('%02d', $episode);
  407. my $season_long = sprintf('%02d', $season);
  408. foreach my $source (values(%{$SOURCES})) {
  409. # Use quotes around the show name if the source needs them
  410. my $quote = '%22';
  411. if (!$source->{'quote'}) {
  412. $quote = '';
  413. }
  414. # Calculate the compete search prefix and suffix to simplify later concatenations
  415. my $prefix = $source->{'search_url'} . $quote . $urlShow . $quote;
  416. my $suffix = '';
  417. if ($source->{'search_exclude'}) {
  418. $suffix .= $exclude;
  419. }
  420. if ($source->{'search_suffix'}) {
  421. $suffix .= $source->{'search_suffix'};
  422. }
  423. # SXXEYY
  424. my $url = $prefix . '+s' . $season_long . 'e' . $episode_long . $suffix;
  425. push(@urls, $url);
  426. # Extra searches for shows that have lazy/non-standard number formats
  427. if ($MORE_NUMBER_FORMATS) {
  428. # SXEY
  429. if ($season_long ne $season || $episode_long ne $episode) {
  430. $url = $prefix . '+s' . $season . 'e' . $episode . $suffix;
  431. push(@urls, $url);
  432. }
  433. # SXX EYY
  434. $url = $prefix . '+s' . $season_long . '+e' . $episode_long . $suffix;
  435. push(@urls, $url);
  436. # Season XX Episode YY
  437. $url = $prefix . '+season+' . $season_long . '+episode+' . $episode_long . $suffix;
  438. push(@urls, $url);
  439. # Series X Episode Y
  440. $url = $prefix . '+series+' . $season . '+episode+' . $episode . $suffix;
  441. push(@urls, $url);
  442. # SxEE
  443. $url = $prefix . '+' . $season . 'x' . $episode_long . $suffix;
  444. push(@urls, $url);
  445. # Season X
  446. if ($NO_QUALITY_CHECKS) {
  447. $url = $prefix . '+Season+' . $season . $suffix;
  448. push(@urls, $url);
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. my @html_content = ();
  456. my @json_content = ();
  457. foreach my $url (@urls) {
  458. # Fetch the page
  459. my $errCount = 0;
  460. HTTP_ERR_LOOP: {
  461. if ($DEBUG) {
  462. print STDERR 'Searching with URL: ' . $url . "\n";
  463. $fetch->file('/tmp/findTorrent-lastPage.html');
  464. }
  465. sleep($DELAY * (rand(2) + 0.5));
  466. $fetch->url($url);
  467. $fetch->fetch('nocheck' => 1);
  468. # Check for useful errors
  469. if ($fetch->status_code() == 404) {
  470. if ($DEBUG) {
  471. print STDERR "Skipping content from 404 response\n";
  472. }
  473. next;
  474. }
  475. # Check for errors
  476. if ($fetch->status_code() != 200) {
  477. if ($fetch->status_code() >= 500 && $fetch->status_code() <= 599) {
  478. if ($errCount > $ERR_RETRIES) {
  479. print STDERR 'Unable to fetch URL: ' . $url . "\n";
  480. $errCount = 0;
  481. next;
  482. }
  483. if ($DEBUG) {
  484. print STDERR 'Retrying URL (' . $fetch->status_code() . '): ' . $url . "\n";
  485. }
  486. $errCount++;
  487. sleep($ERR_DELAY);
  488. redo HTTP_ERR_LOOP;
  489. } else {
  490. print STDERR 'Error fetching URL (' . $fetch->status_code() . '): ' . $url . "\n";
  491. }
  492. next;
  493. }
  494. }
  495. # Save the content, discriminating by data type
  496. if ($DEBUG) {
  497. print STDERR 'Fetched ' . length($fetch->content()) . " bytes\n";
  498. }
  499. if ($fetch->content() =~ /^\s*{/) {
  500. my $json = eval { decode_json($fetch->content()); };
  501. if (defined($json) && ref($json)) {
  502. push(@json_content, \@{ $json->{'items'}->{'list'} });
  503. } elsif ($DEBUG) {
  504. print STDERR 'JSON parsing failure on: ' . $fetch->content() . "\n";
  505. }
  506. } else {
  507. push(@html_content, scalar($fetch->content()));
  508. }
  509. }
  510. # We need someplace to store parsed torrent data from the various sources
  511. my @tors = ();
  512. # Handle HTML content
  513. foreach my $content (@html_content) {
  514. if ($content =~ /\<title\>The Pirate Bay/i) {
  515. # Find TR elements from TPB
  516. my @trs = splitTags($content, 'TR', 'TH', undef());
  517. foreach my $tr (@trs) {
  518. # Find the show title
  519. my ($title) = $tr =~ /title\=\"Details\s+for\s+([^\"]*)\"/i;
  520. if (!defined($title) || length($title) < 1) {
  521. if ($DEBUG) {
  522. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  523. }
  524. next;
  525. }
  526. $title =~ s/^\s+//;
  527. # Extract the season and episode numbers
  528. my ($fileSeason, $episode) = findSE($title);
  529. # Extract the URL
  530. my ($url) = $tr =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  531. if (!defined($url) || length($url) < 1) {
  532. if ($DEBUG) {
  533. print STDERR "Skipping TR with no magnet URL\n";
  534. }
  535. next;
  536. }
  537. $url = decode_entities($url);
  538. # Count the sum of seeders and leachers
  539. my $seeds = 0;
  540. my $leaches = 0;
  541. if ($tr =~ /\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*\<td(?:\s+[^\>]*)?\>(\d+)\<\/td\>\s*$/i) {
  542. $seeds = $1;
  543. $leaches = $2;
  544. }
  545. # Extract the size (from separate column or inline)
  546. my $size = 0;
  547. my $unit = 'M';
  548. if ($tr =~ m/Size (\d+(?:\.\d+)?)\&nbsp\;(G|M)iB/) {
  549. $size = $1;
  550. $unit = $2;
  551. } elsif ($tr =~ m/(\d+(?:\.\d+)?)\&nbsp\;(G|M)iB\<\/[tT][dD]\>/) {
  552. $size = $1;
  553. $unit = $2;
  554. }
  555. if ($unit eq 'G') {
  556. $size *= 1024;
  557. }
  558. $size = int($size);
  559. if ($DEBUG) {
  560. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  561. }
  562. # Save the extracted data
  563. my %tor = (
  564. 'title' => $title,
  565. 'season' => $fileSeason,
  566. 'episode' => $episode,
  567. 'seeds' => $seeds,
  568. 'leaches' => $leaches,
  569. 'size' => $size,
  570. 'url' => $url,
  571. 'source' => 'TPB'
  572. );
  573. push(@tors, \%tor);
  574. }
  575. } elsif ($content =~ /\<title\>[^\<\>]*\bisoHunt\b[^\<\>]*\<\/title\>/i) {
  576. # Find each TR element from ISOHunt
  577. my @trs = splitTags($content, 'TR', 'TH', undef());
  578. foreach my $tr (@trs) {
  579. # Split each TD element from the row
  580. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  581. if (scalar(@tds) > 10 || scalar(@tds) < 9) {
  582. print STDERR 'Skipping invalid ISO TR: ' . $tr . "\n";
  583. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  584. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  585. }
  586. next;
  587. }
  588. # Skip sponsored results
  589. if ($tds[1] =~ /\bSponsored\b/i) {
  590. if ($DEBUG > 1) {
  591. print STDERR "Skipping sponsored result\n";
  592. }
  593. next;
  594. }
  595. # Find the torrent ID and show title
  596. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+\/[^\"]+)\"\>\<span\>([^\>]+)\<\/span\>/i;
  597. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  598. if ($DEBUG > 1) {
  599. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  600. }
  601. next;
  602. }
  603. $title =~ s/^\s+//;
  604. # Extract the season and episode numbers
  605. my ($fileSeason, $episode) = findSE($title);
  606. # Extract the size
  607. my $size = 0;
  608. my $unit = 'M';
  609. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  610. $size = $1;
  611. $unit = $2;
  612. }
  613. if ($unit eq 'G') {
  614. $size *= 1024;
  615. }
  616. $size = int($size);
  617. # Count the sum of seeders and leachers
  618. my $seeds = 0;
  619. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  620. $seeds = $1;
  621. }
  622. my $leaches = 0;
  623. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  624. $leaches = $1;
  625. }
  626. # Build the detail page URL
  627. my $url = $SOURCES->{'ISO'}->{'protocol'} . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id;
  628. if ($DEBUG) {
  629. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  630. }
  631. # Save the extracted data
  632. my %tor = (
  633. 'title' => $title,
  634. 'season' => $fileSeason,
  635. 'episode' => $episode,
  636. 'seeds' => $seeds,
  637. 'leaches' => $leaches,
  638. 'size' => $size,
  639. 'url' => $url,
  640. 'source' => 'ISO'
  641. );
  642. push(@tors, \%tor);
  643. }
  644. } elsif ($content =~ /Kickass\s*Torrents\<\/title\>/i) {
  645. # Find each TR element from Kickass
  646. my @trs = splitTags($content, 'TR', 'TH', undef());
  647. foreach my $tr (@trs) {
  648. # Split each TD element from the row
  649. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  650. if (scalar(@tds) != 6) {
  651. print STDERR "Invalid KICK TR:\n";
  652. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  653. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  654. }
  655. next;
  656. }
  657. # Skip empty results
  658. if ( $tds[1] =~ /\<h2\>Nothing found\!\<\/h2\>/i
  659. || $tds[1] =~ /\<p\>\<strong\>Page not found\<\/strong\>\<\/p\>/i)
  660. {
  661. if ($DEBUG) {
  662. print STDERR "Skipping empty TD\n";
  663. }
  664. next;
  665. }
  666. # Find the torrent title
  667. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  668. if (!defined($title) || length($title) < 1) {
  669. if ($DEBUG) {
  670. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  671. }
  672. next;
  673. }
  674. $title =~ s/^\s+//;
  675. # Find the torrent URL
  676. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  677. if (!defined($url) || length($url) < 1) {
  678. if ($DEBUG) {
  679. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  680. }
  681. next;
  682. }
  683. $url = decode_entities($url);
  684. # Extract the season and episode numbers
  685. my ($fileSeason, $episode) = findSE($title);
  686. # Extract the size
  687. my $size = 0;
  688. my $unit = 'M';
  689. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  690. $size = $1;
  691. $unit = $2;
  692. }
  693. if ($unit eq 'G') {
  694. $size *= 1024;
  695. }
  696. $size = int($size);
  697. # Count the sum of seeders and leachers
  698. my $seeds = 0;
  699. if ($tds[4] =~ /(\d+)\<\/td\>/i) {
  700. $seeds = $1;
  701. }
  702. my $leaches = 0;
  703. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  704. $leaches = $1;
  705. }
  706. if ($DEBUG) {
  707. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  708. }
  709. # Save the extracted data
  710. my %tor = (
  711. 'title' => $title,
  712. 'season' => $fileSeason,
  713. 'episode' => $episode,
  714. 'seeds' => $seeds,
  715. 'leaches' => $leaches,
  716. 'size' => $size,
  717. 'url' => $url,
  718. 'source' => 'KICK'
  719. );
  720. push(@tors, \%tor);
  721. }
  722. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  723. # We'll need to strip HTML
  724. my $hs = HTML::Strip->new();
  725. # Find each DL element from Torrentz
  726. my @dls = splitTags($content, 'DL', undef(), undef());
  727. foreach my $dl (@dls) {
  728. # Skip ads
  729. if ($dl =~ /\s+rel\=\"nofollow/i) {
  730. next;
  731. }
  732. # Find the torrent title
  733. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  734. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  735. if ($DEBUG) {
  736. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  737. }
  738. next;
  739. }
  740. $hash = lc($hash);
  741. $title = $hs->parse($title);
  742. $hs->eof;
  743. $title =~ s/^\s+//;
  744. # Extract the season and episode numbers
  745. my ($fileSeason, $episode) = findSE($title);
  746. # Extract the size
  747. my $size = 0;
  748. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  749. $size = $1;
  750. if ($2 eq 'G') {
  751. $size *= 1024;
  752. }
  753. $size = int($size);
  754. }
  755. # Count the sum of seeders and leachers
  756. my $seeds = 0;
  757. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  758. $seeds = $1;
  759. }
  760. my $leaches = 0;
  761. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  762. $leaches = $1;
  763. }
  764. # Construct a magnet URL from the hash
  765. # Assume the seconary lookup will append a list of trackers
  766. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  767. if ($DEBUG) {
  768. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  769. }
  770. # Save the extracted data
  771. my %tor = (
  772. 'title' => $title,
  773. 'season' => $fileSeason,
  774. 'episode' => $episode,
  775. 'seeds' => $seeds,
  776. 'leaches' => $leaches,
  777. 'size' => $size,
  778. 'url' => $url,
  779. 'source' => 'Z'
  780. );
  781. push(@tors, \%tor);
  782. }
  783. } elsif ($content =~ /ExtraTorrent\.cc The World\'s Largest BitTorrent System\<\/title\>/i) {
  784. # Find TR elements from ET
  785. my @trs = splitTags($content, 'TR', undef(), '\/torrent\/');
  786. foreach my $tr (@trs) {
  787. # Find the show title
  788. my ($title) = $tr =~ /title\=\"Download\s+([^\"]*)\s+torrent\"/i;
  789. if (!defined($title) || length($title) < 1) {
  790. if ($DEBUG) {
  791. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  792. }
  793. next;
  794. }
  795. $title =~ s/^\s+//;
  796. # Extract the season and episode numbers
  797. my ($fileSeason, $episode) = findSE($title);
  798. # Extract the ID
  799. my ($id) = $tr =~ /\<a\s+href\=\"\/torrent\/(\d+)\/[^\"]*\"/i;
  800. if (!defined($id) || length($id) < 1) {
  801. if ($DEBUG) {
  802. print STDERR "Skipping TR with no ID\n";
  803. }
  804. next;
  805. }
  806. # Count the sum of seeders and leachers
  807. my $seeds = 0;
  808. my $leaches = 0;
  809. if ($tr =~ /\<td\s+class=\"sy\">(\d+)\<\/td\>/) {
  810. $seeds = $1;
  811. }
  812. if ($tr =~ /\<td\s+class=\"ly\">(\d+)\<\/td\>/) {
  813. $leaches = $1;
  814. }
  815. # Extract the size (from separate column or inline)
  816. my $size = 0;
  817. my $unit = 'M';
  818. if ($tr =~ /\<td\>(\d+(?:\.\d+)?)\&nbsp\;(G|M)B\<\/td\>/) {
  819. $size = $1;
  820. $unit = $2;
  821. }
  822. if ($unit eq 'G') {
  823. $size *= 1024;
  824. }
  825. $size = int($size);
  826. # Build the detail page URL
  827. my $url = $SOURCES->{'ET'}->{'protocol'} . '://' . $SOURCES->{'ET'}->{'host'} . '/torrent/' . $id . '/';
  828. if ($DEBUG) {
  829. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  830. }
  831. # Save the extracted data
  832. my %tor = (
  833. 'title' => $title,
  834. 'season' => $fileSeason,
  835. 'episode' => $episode,
  836. 'seeds' => $seeds,
  837. 'leaches' => $leaches,
  838. 'size' => $size,
  839. 'url' => $url,
  840. 'source' => 'ET'
  841. );
  842. push(@tors, \%tor);
  843. }
  844. } elsif ($content =~ /Database\s+maintenance/i) {
  845. if ($DEBUG) {
  846. print STDERR "Source down for maintenance\n";
  847. }
  848. } elsif ($content =~ /^\s*$/) {
  849. if ($DEBUG) {
  850. print STDERR "Source returned no content\n";
  851. }
  852. } else {
  853. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  854. }
  855. }
  856. # Handle JSON content
  857. foreach my $content (@json_content) {
  858. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  859. }
  860. # Filter for size/count/etc.
  861. my %tors = ();
  862. my $showRegex = undef();
  863. {
  864. my $showClean = $show;
  865. $showClean =~ s/[\"\']//g;
  866. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  867. $showRegex = qr/^${showClean}[\W_]/i;
  868. }
  869. foreach my $tor (@tors) {
  870. # Extract the BTIH, if available
  871. getHash($tor);
  872. # Skip files that are in the torrent excludes list
  873. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  874. if ($DEBUG) {
  875. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  876. }
  877. next;
  878. }
  879. # Skip files that don't start with our show title
  880. if (!($tor->{'title'} =~ $showRegex)) {
  881. if ($DEBUG) {
  882. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  883. }
  884. next;
  885. # Skip pre-air files
  886. } elsif ($tor->{'title'} =~ /preair/i) {
  887. if ($DEBUG) {
  888. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  889. }
  890. next;
  891. # Skip SWESUB files
  892. } elsif ($tor->{'title'} =~ /swesub/i) {
  893. if ($DEBUG) {
  894. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  895. }
  896. next;
  897. # Skip .rus. files
  898. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  899. if ($DEBUG) {
  900. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  901. }
  902. next;
  903. # Skip German files
  904. } elsif ($tor->{'title'} =~ /german/i) {
  905. if ($DEBUG) {
  906. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  907. }
  908. next;
  909. # Skip French files
  910. } elsif ($tor->{'title'} =~ /french/i) {
  911. if ($DEBUG) {
  912. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  913. }
  914. next;
  915. # Skip Spanish files
  916. } elsif ($tor->{'title'} =~ /Español/i) {
  917. if ($DEBUG) {
  918. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  919. }
  920. next;
  921. # Skip Castellano files
  922. } elsif ($tor->{'title'} =~ /Castellano/i) {
  923. if ($DEBUG) {
  924. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  925. }
  926. next;
  927. # Skip unedited files
  928. } elsif ($tor->{'title'} =~ /unedited/i) {
  929. if ($DEBUG) {
  930. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  931. }
  932. next;
  933. }
  934. # Skip files that contain a word from the series exclude list
  935. my $exclude = undef();
  936. foreach my $ex (keys(%TITLE_EXCLUDES)) {
  937. $ex = quotemeta($ex);
  938. if ($tor->{'title'} =~ m/${ex}/i) {
  939. $exclude = $ex;
  940. last;
  941. }
  942. }
  943. if (defined($exclude)) {
  944. if ($DEBUG) {
  945. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  946. }
  947. next;
  948. }
  949. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  950. if (!$CUSTOM_SEARCH) {
  951. # Skip files that don't contain the right season number
  952. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  953. if ($DEBUG) {
  954. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  955. }
  956. next;
  957. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  958. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} }) || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS)) {
  959. if ($DEBUG) {
  960. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  961. }
  962. next;
  963. }
  964. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  965. # Skip files that don't match the regex
  966. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  967. if ($DEBUG) {
  968. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  969. }
  970. next;
  971. }
  972. }
  973. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  974. if (!$NO_QUALITY_CHECKS) {
  975. # Skip torrents with too few seeders/leachers
  976. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  977. if ($DEBUG) {
  978. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  979. }
  980. next;
  981. # Skip torrents with unusual seed/leach ratios
  982. } elsif ($tor->{'seeds'} > 1
  983. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  984. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  985. {
  986. if ($DEBUG) {
  987. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  988. }
  989. next;
  990. # Skip torrents that are too small
  991. } elsif ($tor->{'size'} < $MIN_SIZE) {
  992. if ($DEBUG) {
  993. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  994. }
  995. next;
  996. }
  997. }
  998. # Save good torrents
  999. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  1000. if ($DEBUG) {
  1001. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1002. }
  1003. }
  1004. # Find the average torrent size for each episode
  1005. my %size = ();
  1006. {
  1007. my %max = ();
  1008. my %avg = ();
  1009. foreach my $episode (keys(%tors)) {
  1010. my $count = 0;
  1011. $avg{$episode} = 0.001;
  1012. $max{$episode} = 0.001;
  1013. foreach my $tor (@{ $tors{$episode} }) {
  1014. $count++;
  1015. $avg{$episode} += $tor->{'size'};
  1016. if ($tor->{'size'} > $max{$episode}) {
  1017. $max{$episode} = $tor->{'size'};
  1018. }
  1019. }
  1020. if ($count > 0) {
  1021. $avg{$episode} /= $count;
  1022. }
  1023. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1024. if ($DEBUG) {
  1025. print STDERR 'Episode ' . $episode . ' max/avg/cmp size: ' . int($max{$episode}) . '/' . int($avg{$episode}) . '/' . int($size{$episode}) . " MiB\n";
  1026. }
  1027. }
  1028. }
  1029. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1030. foreach my $episode (keys(%tors)) {
  1031. foreach my $tor (@{ $tors{$episode} }) {
  1032. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1033. # Start with the peer count
  1034. $tor->{'adj_count'} = $count;
  1035. # Adjust based on file size
  1036. {
  1037. my $size_ratio = $tor->{'size'} / $size{$episode};
  1038. if ($tor->{'size'} >= $size{$episode}) {
  1039. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  1040. } else {
  1041. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  1042. }
  1043. }
  1044. # Adjust based on title contents
  1045. if ($tor->{'title'} =~ /Subtitulado/i) {
  1046. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  1047. }
  1048. # Truncate to an integer
  1049. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1050. if ($DEBUG) {
  1051. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1052. }
  1053. }
  1054. }
  1055. # Pick the best-adjusted-count torrent for each episode
  1056. my %urls = ();
  1057. foreach my $episode (keys(%tors)) {
  1058. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  1059. my $max = undef();
  1060. foreach my $tor (@sorted) {
  1061. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1062. if ($urls{$episode} = resolveSecondary($tor)) {
  1063. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1064. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1065. next;
  1066. }
  1067. $max = $tor->{'adj_count'};
  1068. }
  1069. if ($DEBUG) {
  1070. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1071. }
  1072. } elsif ($DEBUG) {
  1073. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1074. }
  1075. }
  1076. }
  1077. # Output
  1078. foreach my $episode (keys(%tors)) {
  1079. if (defined($urls{$episode})) {
  1080. $urls{$episode} = resolveTrackers($urls{$episode});
  1081. print $urls{$episode} . "\n";
  1082. if ($SYSLOG) {
  1083. syslog(LOG_NOTICE, $show . ': ' . getHash($urls{$episode}));
  1084. }
  1085. if ($DEBUG) {
  1086. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1087. }
  1088. } elsif ($DEBUG) {
  1089. print STDERR 'No URL for: ' . $episode . "\n";
  1090. }
  1091. }
  1092. # Cleanup
  1093. unlink($cookies);
  1094. if ($SYSLOG) {
  1095. closelog();
  1096. }
  1097. exit(0);
  1098. sub getHash($) {
  1099. my ($tor) = @_;
  1100. my $url;
  1101. # Allow either a URL or a tor hashref
  1102. if (ref($tor) eq 'HASH') {
  1103. $url = $tor->{'url'};
  1104. } else {
  1105. $url = $tor;
  1106. undef($tor);
  1107. }
  1108. # Extract the BTIH hash, if available
  1109. my $hash = undef();
  1110. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1111. $hash = lc($1);
  1112. }
  1113. # Save back to the tor, if provided
  1114. if (defined($tor)) {
  1115. $tor->{'hash'} = lc($hash);
  1116. }
  1117. # Always return the hash, or undef() if none can be found
  1118. return $hash;
  1119. }
  1120. # Resolve secondary URLs
  1121. sub resolveSecondary($) {
  1122. my ($tor) = @_;
  1123. # Fetch the torrent-specific page and extract the magent link
  1124. if ($tor->{'source'} eq 'ISO' || $tor->{'source'} eq 'ET') {
  1125. if ($DEBUG) {
  1126. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  1127. $fetch->file('/tmp/findTorrent-secondary.html');
  1128. }
  1129. sleep($DELAY * (rand(2) + 0.5));
  1130. $fetch->url($tor->{'url'});
  1131. $fetch->fetch();
  1132. if ($fetch->status_code() != 200) {
  1133. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1134. goto OUT;
  1135. }
  1136. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1137. if (!defined($magnet) || length($magnet) < 1) {
  1138. if ($DEBUG) {
  1139. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1140. }
  1141. goto OUT;
  1142. }
  1143. $tor->{'url'} = decode_entities($magnet);
  1144. }
  1145. # Extract the hash
  1146. getHash($tor);
  1147. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1148. if ($DEBUG) {
  1149. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1150. }
  1151. goto OUT;
  1152. }
  1153. OUT:
  1154. return $tor->{'url'};
  1155. }
  1156. sub resolveTrackers($) {
  1157. my ($url) = @_;
  1158. # Always append a few static trackers to the URI
  1159. if ($url =~ /^magnet\:/i) {
  1160. foreach my $tracker (@TRACKERS) {
  1161. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1162. my $match = quotemeta($arg);
  1163. if (!($url =~ /${match}/)) {
  1164. $url .= $arg;
  1165. }
  1166. }
  1167. }
  1168. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1169. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1170. my $hash = lc($1);
  1171. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1172. my $hashURL = $baseURL . '/' . $hash;
  1173. if ($DEBUG) {
  1174. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1175. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1176. }
  1177. sleep($DELAY * (rand(2) + 0.5));
  1178. $fetch->url($hashURL);
  1179. $fetch->fetch();
  1180. if ($fetch->status_code() != 200) {
  1181. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1182. return $url;
  1183. }
  1184. # Parse out and fetch the tracker list URL
  1185. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1186. if (!defined($list)) {
  1187. if ($DEBUG) {
  1188. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1189. }
  1190. return $url;
  1191. }
  1192. my $listURL = $baseURL . $list;
  1193. if ($DEBUG) {
  1194. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1195. $fetch->file('/tmp/findTorrent-tracker.html');
  1196. }
  1197. sleep($DELAY * (rand(2) + 0.5));
  1198. $fetch->url($listURL);
  1199. $fetch->fetch();
  1200. if ($fetch->status_code() != 200) {
  1201. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1202. return $url;
  1203. }
  1204. # Parse the tracker list and append our URL
  1205. foreach my $line ($fetch->content()) {
  1206. if ($line =~ /^\s*$/) {
  1207. next;
  1208. }
  1209. $line =~ s/^\s+//;
  1210. $line =~ s/\s+$//;
  1211. if ($line =~ /^(?:http|udp)\:/i) {
  1212. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1213. my $match = quotemeta($arg);
  1214. if (!($url =~ /${match}/)) {
  1215. if ($DEBUG) {
  1216. print STDERR 'Adding tracker: ' . $line . "\n";
  1217. }
  1218. $url .= $arg;
  1219. }
  1220. } else {
  1221. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1222. }
  1223. }
  1224. }
  1225. return $url;
  1226. }
  1227. sub splitTags($$$$) {
  1228. my ($content, $tag, $header, $match) = @_;
  1229. # Find each tag element
  1230. my @out = ();
  1231. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1232. foreach my $part (@parts) {
  1233. # Trim trailing tags and skip things that aren't complete tags
  1234. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1235. if ($DEBUG > 1) {
  1236. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1237. }
  1238. next;
  1239. }
  1240. # Skip headers
  1241. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1242. if ($DEBUG > 2) {
  1243. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1244. }
  1245. next;
  1246. }
  1247. # Skip non-matches
  1248. if (defined($match) && !($part =~ m/${match}/i)) {
  1249. if ($DEBUG > 2) {
  1250. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1251. }
  1252. next;
  1253. }
  1254. # Save good tags
  1255. push(@out, $part);
  1256. }
  1257. return @out;
  1258. }
  1259. # Extract season
  1260. sub findSE($) {
  1261. my ($name) = @_;
  1262. my $season = 0;
  1263. my $episode = 0;
  1264. my $seasonBlock = '';
  1265. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1266. $seasonBlock = $1;
  1267. my ($month, $day);
  1268. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1269. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1270. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1271. $seasonBlock = $1;
  1272. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1273. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1274. $seasonBlock = $1;
  1275. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1276. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1277. $seasonBlock = $1;
  1278. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1279. }
  1280. # Return something valid and INTy or UNDEF
  1281. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1282. if ($DEBUG) {
  1283. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1284. }
  1285. $season = undef();
  1286. $episode = undef();
  1287. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1288. # Episode-by-date
  1289. $season = int($season);
  1290. } else {
  1291. # Catchall
  1292. # This will warn and return undef() (which is valid) on error
  1293. $season = int($season);
  1294. $episode = int($episode);
  1295. }
  1296. return ($season, $episode);
  1297. }
  1298. sub initSources() {
  1299. my %sources = ();
  1300. # The Pirate Bay
  1301. if ($ENABLE_SOURCE{'TPB'}) {
  1302. my @proxies = ('thepiratebay.org/search/', 'pirateproxy.la/search/', 'tpb.unblocked.co/search/');
  1303. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1304. if ($source) {
  1305. $source->{'weight'} = 1.00;
  1306. $source->{'quote'} = 0;
  1307. $source->{'search_exclude'} = 1;
  1308. $source->{'search_suffix'} = '/0/7/0';
  1309. $sources{'TPB'} = $source;
  1310. }
  1311. }
  1312. # ISOhunt
  1313. if ($ENABLE_SOURCE{'ISO'}) {
  1314. my @proxies = ('isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1315. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1316. if ($source) {
  1317. $source->{'weight'} = 0.25;
  1318. $source->{'quote'} = 1;
  1319. $source->{'search_exclude'} = 1;
  1320. $source->{'search_suffix'} = '';
  1321. $sources{'ISO'} = $source;
  1322. }
  1323. }
  1324. # Kickass
  1325. if ($ENABLE_SOURCE{'KICK'}) {
  1326. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1327. my $source = findProxy(\@proxies, '/search.php');
  1328. if ($source) {
  1329. $source->{'weight'} = 1.00;
  1330. $source->{'quote'} = 1;
  1331. $source->{'search_exclude'} = 1;
  1332. $source->{'search_suffix'} = '/';
  1333. $sources{'KICK'} = $source;
  1334. }
  1335. }
  1336. # Torrentz
  1337. if ($ENABLE_SOURCE{'Z'}) {
  1338. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1339. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1340. if ($source) {
  1341. $source->{'weight'} = 1.00;
  1342. $source->{'quote'} = 1;
  1343. $source->{'search_exclude'} = 1;
  1344. $source->{'search_suffix'} = '';
  1345. if (!$NO_QUALITY_CHECKS) {
  1346. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1347. }
  1348. $sources{'Z'} = $source;
  1349. }
  1350. }
  1351. # ExtraTorrent
  1352. if ($ENABLE_SOURCE{'ET'}) {
  1353. my @proxies = ('extratorrent.cc/search/?search=', 'etmirror.com/search/?search=', 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search=');
  1354. my $source = findProxy(\@proxies, '/search/');
  1355. if ($source) {
  1356. $source->{'weight'} = 1.00;
  1357. $source->{'quote'} = 1;
  1358. $source->{'search_exclude'} = 0;
  1359. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1360. $sources{'ET'} = $source;
  1361. }
  1362. }
  1363. # Sanity check
  1364. if (scalar(keys(%sources)) < 1) {
  1365. die("No sources available\n");
  1366. }
  1367. return \%sources;
  1368. }
  1369. sub findProxy($$) {
  1370. my ($proxies, $match) = @_;
  1371. # Automatically select a proxy
  1372. my $host = '';
  1373. my $protocol = '';
  1374. my $search_url = '';
  1375. foreach my $url (@{$proxies}) {
  1376. my $path;
  1377. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1378. if (!$protocol) {
  1379. $protocol = $PROTOCOL;
  1380. }
  1381. if (!$host) {
  1382. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1383. next;
  1384. }
  1385. $fetch->url($protocol . '://' . $host);
  1386. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1387. $search_url = $protocol . '://' . $host . $path;
  1388. last;
  1389. } elsif ($DEBUG) {
  1390. print STDERR 'Proxy not available: ' . $host . "\n";
  1391. if ($DEBUG > 1) {
  1392. print STDERR $fetch->content() . "\n";
  1393. }
  1394. }
  1395. }
  1396. # Return the search data if at least one proxy is up
  1397. if ($search_url) {
  1398. my %tmp = (
  1399. 'protocol' => $protocol,
  1400. 'host' => $host,
  1401. 'search_url' => $search_url,
  1402. );
  1403. return \%tmp;
  1404. }
  1405. # Return undef if we didn't find any working proxies
  1406. return undef();
  1407. }