findTorrent.pl 41 KB

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