findTorrent.pl 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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' => 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. if ($tds[1] =~ /No results found/) {
  583. next;
  584. }
  585. print STDERR 'Skipping invalid ISO TR: ' . $tr . "\n";
  586. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  587. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  588. }
  589. next;
  590. }
  591. # Skip sponsored results
  592. if ($tds[1] =~ /\bSponsored\b/i) {
  593. if ($DEBUG > 1) {
  594. print STDERR "Skipping sponsored result\n";
  595. }
  596. next;
  597. }
  598. # Find the torrent ID and show title
  599. my ($id, $title) = $tds[2] =~ /\<a(?:\s+[^\>]*)?href=\"\/torrent_details\/(\d+\/[^\"]+)\"\>\<span\>([^\>]+)\<\/span\>/i;
  600. if (!defined($id) || length($id) < 1 || !defined($title) || length($title) < 1) {
  601. if ($DEBUG > 1) {
  602. print STDERR "Unable to find show ID or title in TD:\n\t" . $tds[2] . "\n";
  603. }
  604. next;
  605. }
  606. $title =~ s/^\s+//;
  607. # Extract the season and episode numbers
  608. my ($fileSeason, $episode) = findSE($title);
  609. # Extract the size
  610. my $size = 0;
  611. my $unit = 'M';
  612. if ($tds[6] =~ m/(\d+(?:\.\d+)?) (G|M)B<\/td\>/i) {
  613. $size = $1;
  614. $unit = $2;
  615. }
  616. if ($unit eq 'G') {
  617. $size *= 1024;
  618. }
  619. $size = int($size);
  620. # Count the sum of seeders and leachers
  621. my $seeds = 0;
  622. if ($tds[7] =~ /(\d+)\<\/td\>/i) {
  623. $seeds = $1;
  624. }
  625. my $leaches = 0;
  626. if ($tds[8] =~ /(\d+)\<\/td\>/i) {
  627. $leaches = $1;
  628. }
  629. # Build the detail page URL
  630. my $url = $SOURCES->{'ISO'}->{'protocol'} . '://' . $SOURCES->{'ISO'}->{'host'} . '/torrent_details/' . $id;
  631. if ($DEBUG) {
  632. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  633. }
  634. # Save the extracted data
  635. my %tor = (
  636. 'title' => $title,
  637. 'season' => $fileSeason,
  638. 'episode' => $episode,
  639. 'seeds' => $seeds,
  640. 'leaches' => $leaches,
  641. 'size' => $size,
  642. 'url' => $url,
  643. 'source' => 'ISO'
  644. );
  645. push(@tors, \%tor);
  646. }
  647. } elsif ($content =~ /Kickass\s*Torrents\<\/title\>/i) {
  648. # Find each TR element from Kickass
  649. my @trs = splitTags($content, 'TR', 'TH', undef());
  650. foreach my $tr (@trs) {
  651. # Split each TD element from the row
  652. my @tds = split(/\<td(?:\s+[^\>]*)?\>/i, $tr);
  653. if (scalar(@tds) != 6) {
  654. print STDERR "Invalid KICK TR:\n";
  655. for (my $i = 0 ; $i < scalar(@tds) ; $i++) {
  656. print STDERR 'TD' . $i . ': ' . $tds[$i] . "\n";
  657. }
  658. next;
  659. }
  660. # Skip empty results
  661. if ( $tds[1] =~ /\<h2\>Nothing found\!\<\/h2\>/i
  662. || $tds[1] =~ /\<p\>\<strong\>Page not found\<\/strong\>\<\/p\>/i)
  663. {
  664. if ($DEBUG) {
  665. print STDERR "Skipping empty TD\n";
  666. }
  667. next;
  668. }
  669. # Find the torrent title
  670. my ($title) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href\=\"[^\"]+\?title\=\[[^\]\"]+\]([^\"]+)\"/i;
  671. if (!defined($title) || length($title) < 1) {
  672. if ($DEBUG) {
  673. print STDERR "Unable to find torrent title in TD:\n\t" . $tds[1] . "\n";
  674. }
  675. next;
  676. }
  677. $title =~ s/^\s+//;
  678. # Find the torrent URL
  679. my ($url) = $tds[1] =~ /\<a(?:\s+[^\>]*)?href=\"(magnet:[^\"]+)\"/i;
  680. if (!defined($url) || length($url) < 1) {
  681. if ($DEBUG) {
  682. print STDERR "Unable to find torrent URL in TD:\n\t" . $tds[1] . "\n";
  683. }
  684. next;
  685. }
  686. $url = decode_entities($url);
  687. # Extract the season and episode numbers
  688. my ($fileSeason, $episode) = findSE($title);
  689. # Extract the size
  690. my $size = 0;
  691. my $unit = 'M';
  692. if ($tds[2] =~ m/(\d+(?:\.\d+)?)\s+\<span\>(G|M)B\<\/span\>\<\/td\>/i) {
  693. $size = $1;
  694. $unit = $2;
  695. }
  696. if ($unit eq 'G') {
  697. $size *= 1024;
  698. }
  699. $size = int($size);
  700. # Count the sum of seeders and leachers
  701. my $seeds = 0;
  702. if ($tds[4] =~ /(\d+)\<\/td\>/i) {
  703. $seeds = $1;
  704. }
  705. my $leaches = 0;
  706. if ($tds[5] =~ /(\d+)\<\/td\>/i) {
  707. $leaches = $1;
  708. }
  709. if ($DEBUG) {
  710. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  711. }
  712. # Save the extracted data
  713. my %tor = (
  714. 'title' => $title,
  715. 'season' => $fileSeason,
  716. 'episode' => $episode,
  717. 'seeds' => $seeds,
  718. 'leaches' => $leaches,
  719. 'size' => $size,
  720. 'url' => $url,
  721. 'source' => 'KICK'
  722. );
  723. push(@tors, \%tor);
  724. }
  725. } elsif ($content =~ /\<a(?:\s+[^\>]*)?\>Torrentz\<\/a\>/i) {
  726. # We'll need to strip HTML
  727. my $hs = HTML::Strip->new();
  728. # Find each DL element from Torrentz
  729. my @dls = splitTags($content, 'DL', undef(), undef());
  730. foreach my $dl (@dls) {
  731. # Skip ads
  732. if ($dl =~ /\s+rel\=\"nofollow/i) {
  733. next;
  734. }
  735. # Find the torrent title
  736. my ($hash, $title) = $dl =~ /\<a href\=\"\/(\w+)\">(.*)\<\/a\>/i;
  737. if (!defined($hash) || length($hash) < 1 || !defined($title) || length($title) < 1) {
  738. if ($DEBUG) {
  739. print STDERR "Unable to find torrent title in DL:\n\t" . $dl . "\n";
  740. }
  741. next;
  742. }
  743. $hash = lc($hash);
  744. $title = $hs->parse($title);
  745. $hs->eof;
  746. $title =~ s/^\s+//;
  747. # Extract the season and episode numbers
  748. my ($fileSeason, $episode) = findSE($title);
  749. # Extract the size
  750. my $size = 0;
  751. if ($dl =~ /\<span class\=\"s\">(\d+(?:\.\d+)?) (G|M)B\<\/span\>/i) {
  752. $size = $1;
  753. if ($2 eq 'G') {
  754. $size *= 1024;
  755. }
  756. $size = int($size);
  757. }
  758. # Count the sum of seeders and leachers
  759. my $seeds = 0;
  760. if ($dl =~ /<span class\=\"u\">(\d+)\<\/span\>/i) {
  761. $seeds = $1;
  762. }
  763. my $leaches = 0;
  764. if ($dl =~ /<span class\=\"d\">(\d+)\<\/span\>/i) {
  765. $leaches = $1;
  766. }
  767. # Construct a magnet URL from the hash
  768. # Assume the seconary lookup will append a list of trackers
  769. my $url = 'magnet:?xt=urn:btih:' . $hash . '&dn=' . uri_encode($title, { 'encode_reserved' => 1 });
  770. if ($DEBUG) {
  771. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  772. }
  773. # Save the extracted data
  774. my %tor = (
  775. 'title' => $title,
  776. 'season' => $fileSeason,
  777. 'episode' => $episode,
  778. 'seeds' => $seeds,
  779. 'leaches' => $leaches,
  780. 'size' => $size,
  781. 'url' => $url,
  782. 'source' => 'Z'
  783. );
  784. push(@tors, \%tor);
  785. }
  786. } elsif ($content =~ /ExtraTorrent\.cc The World\'s Largest BitTorrent System\<\/title\>/i) {
  787. # Find TR elements from ET
  788. my @trs = splitTags($content, 'TR', undef(), '\/torrent\/');
  789. foreach my $tr (@trs) {
  790. # Find the show title
  791. my ($title) = $tr =~ /title\=\"Download\s+([^\"]*)\s+torrent\"/i;
  792. if (!defined($title) || length($title) < 1) {
  793. if ($DEBUG) {
  794. print STDERR "Unable to find show title in TR\n\t" . $tr . "\n";
  795. }
  796. next;
  797. }
  798. $title =~ s/^\s+//;
  799. # Extract the season and episode numbers
  800. my ($fileSeason, $episode) = findSE($title);
  801. # Extract the ID
  802. my ($id) = $tr =~ /\<a\s+href\=\"\/torrent\/(\d+)\/[^\"]*\"/i;
  803. if (!defined($id) || length($id) < 1) {
  804. if ($DEBUG) {
  805. print STDERR "Skipping TR with no ID\n";
  806. }
  807. next;
  808. }
  809. # Count the sum of seeders and leachers
  810. my $seeds = 0;
  811. my $leaches = 0;
  812. if ($tr =~ /\<td\s+class=\"sy\">(\d+)\<\/td\>/) {
  813. $seeds = $1;
  814. }
  815. if ($tr =~ /\<td\s+class=\"ly\">(\d+)\<\/td\>/) {
  816. $leaches = $1;
  817. }
  818. # Extract the size (from separate column or inline)
  819. my $size = 0;
  820. my $unit = 'M';
  821. if ($tr =~ /\<td\>(\d+(?:\.\d+)?)\&nbsp\;(G|M)B\<\/td\>/) {
  822. $size = $1;
  823. $unit = $2;
  824. }
  825. if ($unit eq 'G') {
  826. $size *= 1024;
  827. }
  828. $size = int($size);
  829. # Build the detail page URL
  830. my $url = $SOURCES->{'ET'}->{'protocol'} . '://' . $SOURCES->{'ET'}->{'host'} . '/torrent/' . $id . '/';
  831. if ($DEBUG) {
  832. print STDERR 'Found file (' . $title . '): ' . $url . "\n";
  833. }
  834. # Save the extracted data
  835. my %tor = (
  836. 'title' => $title,
  837. 'season' => $fileSeason,
  838. 'episode' => $episode,
  839. 'seeds' => $seeds,
  840. 'leaches' => $leaches,
  841. 'size' => $size,
  842. 'url' => $url,
  843. 'source' => 'ET'
  844. );
  845. push(@tors, \%tor);
  846. }
  847. } elsif ($content =~ /Database\s+maintenance/i) {
  848. if ($DEBUG) {
  849. print STDERR "Source down for maintenance\n";
  850. }
  851. } elsif ($content =~ /^\s*$/) {
  852. if ($DEBUG) {
  853. print STDERR "Source returned no content\n";
  854. }
  855. } else {
  856. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  857. }
  858. }
  859. # Handle JSON content
  860. foreach my $content (@json_content) {
  861. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  862. }
  863. # Filter for size/count/etc.
  864. my %tors = ();
  865. my $showRegex = undef();
  866. {
  867. my $showClean = $show;
  868. $showClean =~ s/[\"\']//g;
  869. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  870. $showRegex = qr/^${showClean}[\W_]/i;
  871. }
  872. foreach my $tor (@tors) {
  873. # Extract the BTIH, if available
  874. getHash($tor);
  875. # Skip files that are in the torrent excludes list
  876. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  877. if ($DEBUG) {
  878. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  879. }
  880. next;
  881. }
  882. # Skip files that don't start with our show title
  883. if (!($tor->{'title'} =~ $showRegex)) {
  884. if ($DEBUG) {
  885. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  886. }
  887. next;
  888. # Skip pre-air files
  889. } elsif ($tor->{'title'} =~ /preair/i) {
  890. if ($DEBUG) {
  891. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  892. }
  893. next;
  894. # Skip SWESUB files
  895. } elsif ($tor->{'title'} =~ /swesub/i) {
  896. if ($DEBUG) {
  897. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  898. }
  899. next;
  900. # Skip .rus. files
  901. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  902. if ($DEBUG) {
  903. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  904. }
  905. next;
  906. # Skip German files
  907. } elsif ($tor->{'title'} =~ /german/i) {
  908. if ($DEBUG) {
  909. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  910. }
  911. next;
  912. # Skip French files
  913. } elsif ($tor->{'title'} =~ /french/i) {
  914. if ($DEBUG) {
  915. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  916. }
  917. next;
  918. # Skip Spanish files
  919. } elsif ($tor->{'title'} =~ /Español/i) {
  920. if ($DEBUG) {
  921. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  922. }
  923. next;
  924. # Skip Castellano files
  925. } elsif ($tor->{'title'} =~ /Castellano/i) {
  926. if ($DEBUG) {
  927. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  928. }
  929. next;
  930. # Skip unedited files
  931. } elsif ($tor->{'title'} =~ /unedited/i) {
  932. if ($DEBUG) {
  933. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  934. }
  935. next;
  936. }
  937. # Skip files that contain a word from the series exclude list
  938. my $exclude = undef();
  939. foreach my $ex (keys(%TITLE_EXCLUDES)) {
  940. $ex = quotemeta($ex);
  941. if ($tor->{'title'} =~ m/${ex}/i) {
  942. $exclude = $ex;
  943. last;
  944. }
  945. }
  946. if (defined($exclude)) {
  947. if ($DEBUG) {
  948. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  949. }
  950. next;
  951. }
  952. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  953. if (!$CUSTOM_SEARCH) {
  954. # Skip files that don't contain the right season number
  955. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  956. if ($DEBUG) {
  957. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  958. }
  959. next;
  960. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  961. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} }) || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS)) {
  962. if ($DEBUG) {
  963. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  964. }
  965. next;
  966. }
  967. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  968. # Skip files that don't match the regex
  969. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  970. if ($DEBUG) {
  971. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  972. }
  973. next;
  974. }
  975. }
  976. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  977. if (!$NO_QUALITY_CHECKS) {
  978. # Skip torrents with too few seeders/leachers
  979. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  980. if ($DEBUG) {
  981. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  982. }
  983. next;
  984. # Skip torrents with unusual seed/leach ratios
  985. } elsif ($tor->{'seeds'} > 1
  986. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  987. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  988. {
  989. if ($DEBUG) {
  990. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  991. }
  992. next;
  993. # Skip torrents that are too small
  994. } elsif ($tor->{'size'} < $MIN_SIZE) {
  995. if ($DEBUG) {
  996. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  997. }
  998. next;
  999. }
  1000. }
  1001. # Save good torrents
  1002. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  1003. if ($DEBUG) {
  1004. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1005. }
  1006. }
  1007. # Find the average torrent size for each episode
  1008. my %size = ();
  1009. {
  1010. my %max = ();
  1011. my %avg = ();
  1012. foreach my $episode (keys(%tors)) {
  1013. my $count = 0;
  1014. $avg{$episode} = 0.001;
  1015. $max{$episode} = 0.001;
  1016. foreach my $tor (@{ $tors{$episode} }) {
  1017. $count++;
  1018. $avg{$episode} += $tor->{'size'};
  1019. if ($tor->{'size'} > $max{$episode}) {
  1020. $max{$episode} = $tor->{'size'};
  1021. }
  1022. }
  1023. if ($count > 0) {
  1024. $avg{$episode} /= $count;
  1025. }
  1026. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1027. if ($DEBUG) {
  1028. print STDERR 'Episode ' . $episode . ' max/avg/cmp size: ' . int($max{$episode}) . '/' . int($avg{$episode}) . '/' . int($size{$episode}) . " MiB\n";
  1029. }
  1030. }
  1031. }
  1032. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1033. foreach my $episode (keys(%tors)) {
  1034. foreach my $tor (@{ $tors{$episode} }) {
  1035. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1036. # Start with the peer count
  1037. $tor->{'adj_count'} = $count;
  1038. # Adjust based on file size
  1039. {
  1040. my $size_ratio = $tor->{'size'} / $size{$episode};
  1041. if ($tor->{'size'} >= $size{$episode}) {
  1042. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  1043. } else {
  1044. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  1045. }
  1046. }
  1047. # Adjust based on title contents
  1048. if ($tor->{'title'} =~ /Subtitulado/i) {
  1049. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  1050. }
  1051. # Truncate to an integer
  1052. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1053. if ($DEBUG) {
  1054. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1055. }
  1056. }
  1057. }
  1058. # Pick the best-adjusted-count torrent for each episode
  1059. my %urls = ();
  1060. foreach my $episode (keys(%tors)) {
  1061. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  1062. my $max = undef();
  1063. foreach my $tor (@sorted) {
  1064. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1065. if ($urls{$episode} = resolveSecondary($tor)) {
  1066. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1067. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1068. next;
  1069. }
  1070. $max = $tor->{'adj_count'};
  1071. }
  1072. if ($DEBUG) {
  1073. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1074. }
  1075. } elsif ($DEBUG) {
  1076. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1077. }
  1078. }
  1079. }
  1080. # Output
  1081. foreach my $episode (keys(%tors)) {
  1082. if (defined($urls{$episode})) {
  1083. $urls{$episode} = resolveTrackers($urls{$episode});
  1084. print $urls{$episode} . "\n";
  1085. if ($SYSLOG) {
  1086. syslog(LOG_NOTICE, $show . ': ' . getHash($urls{$episode}));
  1087. }
  1088. if ($DEBUG) {
  1089. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1090. }
  1091. } elsif ($DEBUG) {
  1092. print STDERR 'No URL for: ' . $episode . "\n";
  1093. }
  1094. }
  1095. # Cleanup
  1096. unlink($cookies);
  1097. if ($SYSLOG) {
  1098. closelog();
  1099. }
  1100. exit(0);
  1101. sub getHash($) {
  1102. my ($tor) = @_;
  1103. my $url;
  1104. # Allow either a URL or a tor hashref
  1105. if (ref($tor) eq 'HASH') {
  1106. $url = $tor->{'url'};
  1107. } else {
  1108. $url = $tor;
  1109. undef($tor);
  1110. }
  1111. # Extract the BTIH hash, if available
  1112. my $hash = undef();
  1113. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1114. $hash = lc($1);
  1115. }
  1116. # Save back to the tor, if provided
  1117. if (defined($tor)) {
  1118. $tor->{'hash'} = lc($hash);
  1119. }
  1120. # Always return the hash, or undef() if none can be found
  1121. return $hash;
  1122. }
  1123. # Resolve secondary URLs
  1124. sub resolveSecondary($) {
  1125. my ($tor) = @_;
  1126. # Fetch the torrent-specific page and extract the magent link
  1127. if ($tor->{'source'} eq 'ISO' || $tor->{'source'} eq 'ET') {
  1128. if ($DEBUG) {
  1129. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  1130. $fetch->file('/tmp/findTorrent-secondary.html');
  1131. }
  1132. sleep($DELAY * (rand(2) + 0.5));
  1133. $fetch->url($tor->{'url'});
  1134. $fetch->fetch();
  1135. if ($fetch->status_code() != 200) {
  1136. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1137. goto OUT;
  1138. }
  1139. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1140. if (!defined($magnet) || length($magnet) < 1) {
  1141. if ($DEBUG) {
  1142. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1143. }
  1144. goto OUT;
  1145. }
  1146. $tor->{'url'} = decode_entities($magnet);
  1147. }
  1148. # Extract the hash
  1149. getHash($tor);
  1150. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1151. if ($DEBUG) {
  1152. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1153. }
  1154. goto OUT;
  1155. }
  1156. OUT:
  1157. return $tor->{'url'};
  1158. }
  1159. sub resolveTrackers($) {
  1160. my ($url) = @_;
  1161. # Always append a few static trackers to the URI
  1162. if ($url =~ /^magnet\:/i) {
  1163. foreach my $tracker (@TRACKERS) {
  1164. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1165. my $match = quotemeta($arg);
  1166. if (!($url =~ /${match}/)) {
  1167. $url .= $arg;
  1168. }
  1169. }
  1170. }
  1171. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1172. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1173. my $hash = lc($1);
  1174. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1175. my $hashURL = $baseURL . '/' . $hash;
  1176. if ($DEBUG) {
  1177. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1178. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1179. }
  1180. sleep($DELAY * (rand(2) + 0.5));
  1181. $fetch->url($hashURL);
  1182. $fetch->fetch();
  1183. if ($fetch->status_code() != 200) {
  1184. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1185. return $url;
  1186. }
  1187. # Parse out and fetch the tracker list URL
  1188. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1189. if (!defined($list)) {
  1190. if ($DEBUG) {
  1191. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1192. }
  1193. return $url;
  1194. }
  1195. my $listURL = $baseURL . $list;
  1196. if ($DEBUG) {
  1197. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1198. $fetch->file('/tmp/findTorrent-tracker.html');
  1199. }
  1200. sleep($DELAY * (rand(2) + 0.5));
  1201. $fetch->url($listURL);
  1202. $fetch->fetch();
  1203. if ($fetch->status_code() != 200) {
  1204. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1205. return $url;
  1206. }
  1207. # Parse the tracker list and append our URL
  1208. foreach my $line ($fetch->content()) {
  1209. if ($line =~ /^\s*$/) {
  1210. next;
  1211. }
  1212. $line =~ s/^\s+//;
  1213. $line =~ s/\s+$//;
  1214. if ($line =~ /^(?:http|udp)\:/i) {
  1215. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1216. my $match = quotemeta($arg);
  1217. if (!($url =~ /${match}/)) {
  1218. if ($DEBUG) {
  1219. print STDERR 'Adding tracker: ' . $line . "\n";
  1220. }
  1221. $url .= $arg;
  1222. }
  1223. } else {
  1224. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1225. }
  1226. }
  1227. }
  1228. return $url;
  1229. }
  1230. sub splitTags($$$$) {
  1231. my ($content, $tag, $header, $match) = @_;
  1232. # Find each tag element
  1233. my @out = ();
  1234. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1235. foreach my $part (@parts) {
  1236. # Trim trailing tags and skip things that aren't complete tags
  1237. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1238. if ($DEBUG > 1) {
  1239. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1240. }
  1241. next;
  1242. }
  1243. # Skip headers
  1244. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1245. if ($DEBUG > 2) {
  1246. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1247. }
  1248. next;
  1249. }
  1250. # Skip non-matches
  1251. if (defined($match) && !($part =~ m/${match}/i)) {
  1252. if ($DEBUG > 2) {
  1253. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1254. }
  1255. next;
  1256. }
  1257. # Save good tags
  1258. push(@out, $part);
  1259. }
  1260. return @out;
  1261. }
  1262. # Extract season
  1263. sub findSE($) {
  1264. my ($name) = @_;
  1265. my $season = 0;
  1266. my $episode = 0;
  1267. my $seasonBlock = '';
  1268. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1269. $seasonBlock = $1;
  1270. my ($month, $day);
  1271. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1272. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1273. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1274. $seasonBlock = $1;
  1275. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1276. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1277. $seasonBlock = $1;
  1278. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1279. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1280. $seasonBlock = $1;
  1281. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1282. }
  1283. # Return something valid and INTy or UNDEF
  1284. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1285. if ($DEBUG) {
  1286. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1287. }
  1288. $season = undef();
  1289. $episode = undef();
  1290. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1291. # Episode-by-date
  1292. $season = int($season);
  1293. } else {
  1294. # Catchall
  1295. # This will warn and return undef() (which is valid) on error
  1296. $season = int($season);
  1297. $episode = int($episode);
  1298. }
  1299. return ($season, $episode);
  1300. }
  1301. sub initSources() {
  1302. my %sources = ();
  1303. # The Pirate Bay
  1304. if ($ENABLE_SOURCE{'TPB'}) {
  1305. my @proxies = ('thepiratebay.org/search/', 'pirateproxy.la/search/', 'tpb.unblocked.co/search/');
  1306. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1307. if ($source) {
  1308. $source->{'weight'} = 1.00;
  1309. $source->{'quote'} = 0;
  1310. $source->{'search_exclude'} = 1;
  1311. $source->{'search_suffix'} = '/0/7/0';
  1312. $sources{'TPB'} = $source;
  1313. }
  1314. }
  1315. # ISOhunt
  1316. if ($ENABLE_SOURCE{'ISO'}) {
  1317. my @proxies = ('isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1318. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1319. if ($source) {
  1320. $source->{'weight'} = 0.25;
  1321. $source->{'quote'} = 1;
  1322. $source->{'search_exclude'} = 1;
  1323. $source->{'search_suffix'} = '';
  1324. $sources{'ISO'} = $source;
  1325. }
  1326. }
  1327. # Kickass
  1328. if ($ENABLE_SOURCE{'KICK'}) {
  1329. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1330. my $source = findProxy(\@proxies, '/search.php');
  1331. if ($source) {
  1332. $source->{'weight'} = 1.00;
  1333. $source->{'quote'} = 1;
  1334. $source->{'search_exclude'} = 1;
  1335. $source->{'search_suffix'} = '/';
  1336. $sources{'KICK'} = $source;
  1337. }
  1338. }
  1339. # Torrentz
  1340. if ($ENABLE_SOURCE{'Z'}) {
  1341. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1342. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1343. if ($source) {
  1344. $source->{'weight'} = 1.00;
  1345. $source->{'quote'} = 1;
  1346. $source->{'search_exclude'} = 1;
  1347. $source->{'search_suffix'} = '';
  1348. if (!$NO_QUALITY_CHECKS) {
  1349. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1350. }
  1351. $sources{'Z'} = $source;
  1352. }
  1353. }
  1354. # ExtraTorrent
  1355. if ($ENABLE_SOURCE{'ET'}) {
  1356. my @proxies = ('extratorrent.cc/search/?search=', 'etmirror.com/search/?search=', 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search=');
  1357. my $source = findProxy(\@proxies, '/search/');
  1358. if ($source) {
  1359. $source->{'weight'} = 1.00;
  1360. $source->{'quote'} = 1;
  1361. $source->{'search_exclude'} = 0;
  1362. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1363. $sources{'ET'} = $source;
  1364. }
  1365. }
  1366. # Sanity check
  1367. if (scalar(keys(%sources)) < 1) {
  1368. die("No sources available\n");
  1369. }
  1370. return \%sources;
  1371. }
  1372. sub findProxy($$) {
  1373. my ($proxies, $match) = @_;
  1374. # Automatically select a proxy
  1375. my $host = '';
  1376. my $protocol = '';
  1377. my $search_url = '';
  1378. foreach my $url (@{$proxies}) {
  1379. my $path;
  1380. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1381. if (!$protocol) {
  1382. $protocol = $PROTOCOL;
  1383. }
  1384. if (!$host) {
  1385. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1386. next;
  1387. }
  1388. $fetch->url($protocol . '://' . $host);
  1389. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1390. $search_url = $protocol . '://' . $host . $path;
  1391. last;
  1392. } elsif ($DEBUG) {
  1393. print STDERR 'Proxy not available: ' . $host . "\n";
  1394. if ($DEBUG > 1) {
  1395. print STDERR $fetch->content() . "\n";
  1396. }
  1397. }
  1398. }
  1399. # Return the search data if at least one proxy is up
  1400. if ($search_url) {
  1401. my %tmp = (
  1402. 'protocol' => $protocol,
  1403. 'host' => $host,
  1404. 'search_url' => $search_url,
  1405. );
  1406. return \%tmp;
  1407. }
  1408. # Return undef if we didn't find any working proxies
  1409. return undef();
  1410. }