findTorrent.pl 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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 =~ /\<title\>Sorry/) {
  848. if ($DEBUG) {
  849. print STDERR "ISO offline\n";
  850. }
  851. } elsif ($content =~ /Database\s+maintenance/i) {
  852. if ($DEBUG) {
  853. print STDERR "TPB offline\n";
  854. }
  855. } elsif ($content =~ /^\s*$/) {
  856. if ($DEBUG) {
  857. print STDERR "Source returned no content\n";
  858. }
  859. } else {
  860. print STDERR "Unknown HTML content:\n" . $content . "\n\n";
  861. }
  862. }
  863. # Handle JSON content
  864. foreach my $content (@json_content) {
  865. print STDERR "Unknown JSON content:\n" . $content . "\n\n";
  866. }
  867. # Filter for size/count/etc.
  868. my %tors = ();
  869. my $showRegex = undef();
  870. {
  871. my $showClean = $show;
  872. $showClean =~ s/[\"\']//g;
  873. $showClean =~ s/[\W_]+/\[\\W_\].*/g;
  874. $showRegex = qr/^${showClean}[\W_]/i;
  875. }
  876. foreach my $tor (@tors) {
  877. # Extract the BTIH, if available
  878. getHash($tor);
  879. # Skip files that are in the torrent excludes list
  880. if ($tor->{'hash'} && $EXCLUDES{ $tor->{'hash'} }) {
  881. if ($DEBUG) {
  882. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  883. }
  884. next;
  885. }
  886. # Skip files that don't start with our show title
  887. if (!($tor->{'title'} =~ $showRegex)) {
  888. if ($DEBUG) {
  889. print STDERR 'Skipping file: Title does not match (' . $showRegex . '): ' . $tor->{'title'} . "\n";
  890. }
  891. next;
  892. # Skip pre-air files
  893. } elsif ($tor->{'title'} =~ /preair/i) {
  894. if ($DEBUG) {
  895. print STDERR 'Skipping file: Title contains "preair": ' . $tor->{'title'} . "\n";
  896. }
  897. next;
  898. # Skip SWESUB files
  899. } elsif ($tor->{'title'} =~ /swesub/i) {
  900. if ($DEBUG) {
  901. print STDERR 'Skipping file: Title contains "SWESUB": ' . $tor->{'title'} . "\n";
  902. }
  903. next;
  904. # Skip .rus. files
  905. } elsif ($tor->{'title'} =~ /\.rus\./i) {
  906. if ($DEBUG) {
  907. print STDERR 'Skipping file: Title contains ".rus.": ' . $tor->{'title'} . "\n";
  908. }
  909. next;
  910. # Skip German files
  911. } elsif ($tor->{'title'} =~ /german/i) {
  912. if ($DEBUG) {
  913. print STDERR 'Skipping file: Title contains "german": ' . $tor->{'title'} . "\n";
  914. }
  915. next;
  916. # Skip French files
  917. } elsif ($tor->{'title'} =~ /french/i) {
  918. if ($DEBUG) {
  919. print STDERR 'Skipping file: Title contains "french": ' . $tor->{'title'} . "\n";
  920. }
  921. next;
  922. # Skip Spanish files
  923. } elsif ($tor->{'title'} =~ /Español/i) {
  924. if ($DEBUG) {
  925. print STDERR 'Skipping file: Title contains "Español": ' . $tor->{'title'} . "\n";
  926. }
  927. next;
  928. # Skip Castellano files
  929. } elsif ($tor->{'title'} =~ /Castellano/i) {
  930. if ($DEBUG) {
  931. print STDERR 'Skipping file: Title contains "Castellano": ' . $tor->{'title'} . "\n";
  932. }
  933. next;
  934. # Skip unedited files
  935. } elsif ($tor->{'title'} =~ /unedited/i) {
  936. if ($DEBUG) {
  937. print STDERR 'Skipping file: Title contains "unedited": ' . $tor->{'title'} . "\n";
  938. }
  939. next;
  940. }
  941. # Skip files that contain a word from the series exclude list
  942. my $exclude = undef();
  943. foreach my $ex (keys(%TITLE_EXCLUDES)) {
  944. $ex = quotemeta($ex);
  945. if ($tor->{'title'} =~ m/${ex}/i) {
  946. $exclude = $ex;
  947. last;
  948. }
  949. }
  950. if (defined($exclude)) {
  951. if ($DEBUG) {
  952. print STDERR 'Skipping file: Title contains "' . $exclude . '": ' . $tor->{'title'} . "\n";
  953. }
  954. next;
  955. }
  956. # Enforce season and episode number matches for standard searches, or CUSTOM_SEARCH matching (if it's a regex)
  957. if (!$CUSTOM_SEARCH) {
  958. # Skip files that don't contain the right season number
  959. if (!defined($tor->{'season'}) || $tor->{'season'} != $season) {
  960. if ($DEBUG) {
  961. print STDERR 'Skipping file: No match for season number (' . $season . '): ' . $tor->{'title'} . "\n";
  962. }
  963. next;
  964. # Skip files that don't contain a needed episode number, unless there is no episode number and NO_QUALITY_CHECKS is set
  965. } elsif ((defined($tor->{'episode'}) && !$need{ $tor->{'episode'} }) || (!defined($tor->{'episode'}) && !$NO_QUALITY_CHECKS)) {
  966. if ($DEBUG) {
  967. print STDERR 'Skipping file: No match for episode number (' . $tor->{'episode'} . '): ' . $tor->{'title'} . "\n";
  968. }
  969. next;
  970. }
  971. } elsif (ref($CUSTOM_SEARCH) eq 'Regexp') {
  972. # Skip files that don't match the regex
  973. if (!($tor->{'title'} =~ $CUSTOM_SEARCH)) {
  974. if ($DEBUG) {
  975. print STDERR 'Skipping file: No match for CUSTOM_SEARCH regex (' . $CUSTOM_SEARCH . '): ' . $tor->{'title'} . "\n";
  976. }
  977. next;
  978. }
  979. }
  980. # Only apply the quality rules if NO_QUALITY_CHECKS is not in effect
  981. if (!$NO_QUALITY_CHECKS) {
  982. # Skip torrents with too few seeders/leachers
  983. if (($tor->{'seeds'} + $tor->{'leaches'}) * $SOURCES->{ $tor->{'source'} }->{'weight'} < $MIN_COUNT) {
  984. if ($DEBUG) {
  985. print STDERR 'Skipping file: Insufficient seeder/leacher count (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  986. }
  987. next;
  988. # Skip torrents with unusual seed/leach ratios
  989. } elsif ($tor->{'seeds'} > 1
  990. && $tor->{'seeds'} < $SEED_RATIO_COUNT
  991. && $tor->{'seeds'} > $tor->{'leaches'} * $MAX_SEED_RATIO)
  992. {
  993. if ($DEBUG) {
  994. print STDERR 'Skipping file: Unusual seeder/leacher ratio (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . '): ' . $tor->{'title'} . "\n";
  995. }
  996. next;
  997. # Skip torrents that are too small
  998. } elsif ($tor->{'size'} < $MIN_SIZE) {
  999. if ($DEBUG) {
  1000. print STDERR 'Skipping file: Insufficient size (' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1001. }
  1002. next;
  1003. }
  1004. }
  1005. # Save good torrents
  1006. push(@{ $tors{ $tor->{'episode'} } }, $tor);
  1007. if ($DEBUG) {
  1008. print STDERR 'Possible URL (' . $tor->{'seeds'} . '/' . $tor->{'leaches'} . ' seeds/leaches, ' . $tor->{'size'} . ' MiB): ' . $tor->{'title'} . "\n";
  1009. }
  1010. }
  1011. # Find the average torrent size for each episode
  1012. my %size = ();
  1013. {
  1014. my %max = ();
  1015. my %avg = ();
  1016. foreach my $episode (keys(%tors)) {
  1017. my $count = 0;
  1018. $avg{$episode} = 0.001;
  1019. $max{$episode} = 0.001;
  1020. foreach my $tor (@{ $tors{$episode} }) {
  1021. $count++;
  1022. $avg{$episode} += $tor->{'size'};
  1023. if ($tor->{'size'} > $max{$episode}) {
  1024. $max{$episode} = $tor->{'size'};
  1025. }
  1026. }
  1027. if ($count > 0) {
  1028. $avg{$episode} /= $count;
  1029. }
  1030. $size{$episode} = ($max{$episode} + $avg{$episode}) / 2;
  1031. if ($DEBUG) {
  1032. print STDERR 'Episode ' . $episode . ' max/avg/cmp size: ' . int($max{$episode}) . '/' . int($avg{$episode}) . '/' . int($size{$episode}) . " MiB\n";
  1033. }
  1034. }
  1035. }
  1036. # Calculate an adjusted count based on the peer count, relative file size, and title contents
  1037. foreach my $episode (keys(%tors)) {
  1038. foreach my $tor (@{ $tors{$episode} }) {
  1039. my $count = $tor->{'seeds'} + $tor->{'leaches'};
  1040. # Start with the peer count
  1041. $tor->{'adj_count'} = $count;
  1042. # Adjust based on file size
  1043. {
  1044. my $size_ratio = $tor->{'size'} / $size{$episode};
  1045. if ($tor->{'size'} >= $size{$episode}) {
  1046. $tor->{'adj_count'} *= $SIZE_BONUS * $size_ratio;
  1047. } else {
  1048. $tor->{'adj_count'} *= (1 / $SIZE_PENALTY) * $size_ratio;
  1049. }
  1050. }
  1051. # Adjust based on title contents
  1052. if ($tor->{'title'} =~ /Subtitulado/i) {
  1053. $tor->{'adj_count'} *= 1 / $TITLE_PENALTY;
  1054. }
  1055. # Truncate to an integer
  1056. $tor->{'adj_count'} = int($tor->{'adj_count'});
  1057. if ($DEBUG) {
  1058. print STDERR 'Possible URL (' . $tor->{'adj_count'} . ' size-adjusted sources): ' . $tor->{'url'} . "\n";
  1059. }
  1060. }
  1061. }
  1062. # Pick the best-adjusted-count torrent for each episode
  1063. my %urls = ();
  1064. foreach my $episode (keys(%tors)) {
  1065. my @sorted = sort { $b->{'adj_count'} <=> $a->{'adj_count'} } @{ $tors{$episode} };
  1066. my $max = undef();
  1067. foreach my $tor (@sorted) {
  1068. if (!defined($max) || $tor->{'adj_count'} > $max) {
  1069. if ($urls{$episode} = resolveSecondary($tor)) {
  1070. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1071. print STDERR 'Double-skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1072. next;
  1073. }
  1074. $max = $tor->{'adj_count'};
  1075. }
  1076. if ($DEBUG) {
  1077. print STDERR 'Semi-final URL (adjusted count: ' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1078. }
  1079. } elsif ($DEBUG) {
  1080. print STDERR 'Skipping for lesser adjusted count (' . $tor->{'adj_count'} . '): ' . $tor->{'url'} . "\n";
  1081. }
  1082. }
  1083. }
  1084. # Output
  1085. foreach my $episode (keys(%tors)) {
  1086. if (defined($urls{$episode})) {
  1087. $urls{$episode} = resolveTrackers($urls{$episode});
  1088. print $urls{$episode} . "\n";
  1089. if ($SYSLOG) {
  1090. syslog(LOG_NOTICE, $show . ': ' . getHash($urls{$episode}));
  1091. }
  1092. if ($DEBUG) {
  1093. print STDERR 'Final URL: ' . $urls{$episode} . "\n";
  1094. }
  1095. } elsif ($DEBUG) {
  1096. print STDERR 'No URL for: ' . $episode . "\n";
  1097. }
  1098. }
  1099. # Cleanup
  1100. unlink($cookies);
  1101. if ($SYSLOG) {
  1102. closelog();
  1103. }
  1104. exit(0);
  1105. sub getHash($) {
  1106. my ($tor) = @_;
  1107. my $url;
  1108. # Allow either a URL or a tor hashref
  1109. if (ref($tor) eq 'HASH') {
  1110. $url = $tor->{'url'};
  1111. } else {
  1112. $url = $tor;
  1113. undef($tor);
  1114. }
  1115. # Extract the BTIH hash, if available
  1116. my $hash = undef();
  1117. if ($url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1118. $hash = lc($1);
  1119. }
  1120. # Save back to the tor, if provided
  1121. if (defined($tor)) {
  1122. $tor->{'hash'} = lc($hash);
  1123. }
  1124. # Always return the hash, or undef() if none can be found
  1125. return $hash;
  1126. }
  1127. # Resolve secondary URLs
  1128. sub resolveSecondary($) {
  1129. my ($tor) = @_;
  1130. # Fetch the torrent-specific page and extract the magent link
  1131. if ($tor->{'source'} eq 'ISO' || $tor->{'source'} eq 'ET') {
  1132. if ($DEBUG) {
  1133. print STDERR 'Secondary fetch with URL: ' . $tor->{'url'} . "\n";
  1134. $fetch->file('/tmp/findTorrent-secondary.html');
  1135. }
  1136. sleep($DELAY * (rand(2) + 0.5));
  1137. $fetch->url($tor->{'url'});
  1138. $fetch->fetch();
  1139. if ($fetch->status_code() != 200) {
  1140. print STDERR 'Error fetching secondary URL: ' . $tor->{'url'} . "\n";
  1141. goto OUT;
  1142. }
  1143. my ($magnet) = $fetch->content() =~ /\<a\s+href\=\"(magnet\:\?[^\"]+)\"/i;
  1144. if (!defined($magnet) || length($magnet) < 1) {
  1145. if ($DEBUG) {
  1146. print STDERR 'No secondary URL available from: ' . $tor->{'url'} . "\n";
  1147. }
  1148. goto OUT;
  1149. }
  1150. $tor->{'url'} = decode_entities($magnet);
  1151. }
  1152. # Extract the hash
  1153. getHash($tor);
  1154. if (!$tor->{'hash'} || $EXCLUDES{ $tor->{'hash'} }) {
  1155. if ($DEBUG) {
  1156. print STDERR 'Skipping file: Excluded hash (' . $tor->{'hash'} . '): ' . $tor->{'title'} . "\n";
  1157. }
  1158. goto OUT;
  1159. }
  1160. OUT:
  1161. return $tor->{'url'};
  1162. }
  1163. sub resolveTrackers($) {
  1164. my ($url) = @_;
  1165. # Always append a few static trackers to the URI
  1166. if ($url =~ /^magnet\:/i) {
  1167. foreach my $tracker (@TRACKERS) {
  1168. my $arg = '&tr=' . uri_encode($tracker, { 'encode_reserved' => 1 });
  1169. my $match = quotemeta($arg);
  1170. if (!($url =~ /${match}/)) {
  1171. $url .= $arg;
  1172. }
  1173. }
  1174. }
  1175. # Fetch a dynamic tracker list for any hashinfo from TorrentZ
  1176. if ($TRACKER_LOOKUP && defined($SOURCES->{'Z'}) && $url =~ /^magnet\:/ && $url =~ /\bxt\=urn\:btih\:(\w+)/i) {
  1177. my $hash = lc($1);
  1178. my $baseURL = $SOURCES->{'Z'}->{'protocol'} . '://' . $SOURCES->{'Z'}->{'host'};
  1179. my $hashURL = $baseURL . '/' . $hash;
  1180. if ($DEBUG) {
  1181. print STDERR 'Hashinfo fetch with URL: ' . $hashURL . "\n";
  1182. $fetch->file('/tmp/findTorrent-hashinfo.html');
  1183. }
  1184. sleep($DELAY * (rand(2) + 0.5));
  1185. $fetch->url($hashURL);
  1186. $fetch->fetch();
  1187. if ($fetch->status_code() != 200) {
  1188. print STDERR 'Error fetching hashinfo URL: ' . $hashURL . "\n";
  1189. return $url;
  1190. }
  1191. # Parse out and fetch the tracker list URL
  1192. my ($list) = $fetch->content() =~ /\<a rel\=\"nofollow\" href\=\"(\/announcelist_\d+)\"\>/;
  1193. if (!defined($list)) {
  1194. if ($DEBUG) {
  1195. print STDERR 'Unable to find tracker list link at: ' . $hashURL . "\n";
  1196. }
  1197. return $url;
  1198. }
  1199. my $listURL = $baseURL . $list;
  1200. if ($DEBUG) {
  1201. print STDERR 'Tracker list fetch with URL: ' . $listURL . "\n";
  1202. $fetch->file('/tmp/findTorrent-tracker.html');
  1203. }
  1204. sleep($DELAY * (rand(2) + 0.5));
  1205. $fetch->url($listURL);
  1206. $fetch->fetch();
  1207. if ($fetch->status_code() != 200) {
  1208. print STDERR 'Error fetching tracker list URL: ' . $listURL . "\n";
  1209. return $url;
  1210. }
  1211. # Parse the tracker list and append our URL
  1212. foreach my $line ($fetch->content()) {
  1213. if ($line =~ /^\s*$/) {
  1214. next;
  1215. }
  1216. $line =~ s/^\s+//;
  1217. $line =~ s/\s+$//;
  1218. if ($line =~ /^(?:http|udp)\:/i) {
  1219. my $arg = '&tr=' . uri_encode($line, { 'encode_reserved' => 1 });
  1220. my $match = quotemeta($arg);
  1221. if (!($url =~ /${match}/)) {
  1222. if ($DEBUG) {
  1223. print STDERR 'Adding tracker: ' . $line . "\n";
  1224. }
  1225. $url .= $arg;
  1226. }
  1227. } else {
  1228. print STDERR 'Unknown tracker type: ' . $line . "\n";
  1229. }
  1230. }
  1231. }
  1232. return $url;
  1233. }
  1234. sub splitTags($$$$) {
  1235. my ($content, $tag, $header, $match) = @_;
  1236. # Find each tag element
  1237. my @out = ();
  1238. my @parts = split(/\<${tag}(?:\s+[^\>]*)?\>/i, $content);
  1239. foreach my $part (@parts) {
  1240. # Trim trailing tags and skip things that aren't complete tags
  1241. if (!($part =~ s/\<\/${tag}\>.*$//is)) {
  1242. if ($DEBUG > 1) {
  1243. print STDERR 'Skipping non-tag line: ' . $part . "\n\n";
  1244. }
  1245. next;
  1246. }
  1247. # Skip headers
  1248. if (defined($header) && $part =~ /<${header}(?:\s+[^\>]*)?\>/i) {
  1249. if ($DEBUG > 2) {
  1250. print STDERR 'Skipping header line: ' . $part . "\n\n";
  1251. }
  1252. next;
  1253. }
  1254. # Skip non-matches
  1255. if (defined($match) && !($part =~ m/${match}/i)) {
  1256. if ($DEBUG > 2) {
  1257. print STDERR 'Skipping non-match line: ' . $part . "\n\n";
  1258. }
  1259. next;
  1260. }
  1261. # Save good tags
  1262. push(@out, $part);
  1263. }
  1264. return @out;
  1265. }
  1266. # Extract season
  1267. sub findSE($) {
  1268. my ($name) = @_;
  1269. my $season = 0;
  1270. my $episode = 0;
  1271. my $seasonBlock = '';
  1272. if ($name =~ /(?:\b|_)(20\d\d(?:\.|\-)[01]?\d(?:\.|\-)[0-3]?\d)(?:\b|_)/) {
  1273. $seasonBlock = $1;
  1274. my ($month, $day);
  1275. ($season, $month, $day) = $seasonBlock =~ /(20\d\d)(?:\.|\-)([01]?\d)(?:\.|\-)([0-3]?\d)/;
  1276. $episode = sprintf('%04d-%02d-%02d', $season, $month, $day);
  1277. } elsif ($name =~ /(?:\b|_)(S(?:eason)?[_\s\.\-]*\d{1,2}[_\s\.\-]*E(?:pisode)?[_\s\.]*\d{1,3}(?:E\d{1,3})?)(?:\b|_)/i) {
  1278. $seasonBlock = $1;
  1279. ($season, $episode) = $seasonBlock =~ /S(?:eason)?[_\s\.\-]*(\d{1,2})[_\s\.\-]*E(?:pisode)?[_\s\.\-]*(\d{1,3})/i;
  1280. } elsif ($name =~ /[\[\_\.](\d{1,2}x\d{2,3})[\]\_\.]/i) {
  1281. $seasonBlock = $1;
  1282. ($season, $episode) = $seasonBlock =~ /(\d+)x(\d+)/i;
  1283. } elsif ($name =~ /(?:\b|_)([01]?\d[_\s\.]?[0-3]\d)(?:\b|_)/i) {
  1284. $seasonBlock = $1;
  1285. ($season, $episode) = $seasonBlock =~ /(?:\b|_)([01]?\d)[_\s\.]?([0-3]\d)/i;
  1286. }
  1287. # Return something valid and INTy or UNDEF
  1288. if (!defined($seasonBlock) || $season < 1 || length($episode) < 1 || $episode eq '0') {
  1289. if ($DEBUG) {
  1290. print STDERR 'Could not find seasonBlock in: ' . $name . "\n";
  1291. }
  1292. $season = undef();
  1293. $episode = undef();
  1294. } elsif ($episode =~ /^20\d{2}\-\d{2}\-\d{2}$/) {
  1295. # Episode-by-date
  1296. $season = int($season);
  1297. } else {
  1298. # Catchall
  1299. # This will warn and return undef() (which is valid) on error
  1300. $season = int($season);
  1301. $episode = int($episode);
  1302. }
  1303. return ($season, $episode);
  1304. }
  1305. sub initSources() {
  1306. my %sources = ();
  1307. # The Pirate Bay
  1308. if ($ENABLE_SOURCE{'TPB'}) {
  1309. my @proxies = ('thepiratebay.org/search/', 'pirateproxy.la/search/', 'tpb.unblocked.co/search/');
  1310. my $source = findProxy(\@proxies, '\bPirate Search\b');
  1311. if ($source) {
  1312. $source->{'weight'} = 1.00;
  1313. $source->{'quote'} = 0;
  1314. $source->{'search_exclude'} = 1;
  1315. $source->{'search_suffix'} = '/0/7/0';
  1316. $sources{'TPB'} = $source;
  1317. }
  1318. }
  1319. # ISOhunt
  1320. if ($ENABLE_SOURCE{'ISO'}) {
  1321. my @proxies = ('isohunters.net/torrents/?ihq=', 'isohunt.to/torrents/?ihq=');
  1322. my $source = findProxy(\@proxies, 'Last\s+\d+\s+files\s+indexed');
  1323. if ($source) {
  1324. $source->{'weight'} = 0.25;
  1325. $source->{'quote'} = 1;
  1326. $source->{'search_exclude'} = 1;
  1327. $source->{'search_suffix'} = '';
  1328. $sources{'ISO'} = $source;
  1329. }
  1330. }
  1331. # Kickass
  1332. if ($ENABLE_SOURCE{'KICK'}) {
  1333. my @proxies = ('kickass.cd/search.php?q=', 'kickass.mx/search.php?q=');
  1334. my $source = findProxy(\@proxies, '/search.php');
  1335. if ($source) {
  1336. $source->{'weight'} = 1.00;
  1337. $source->{'quote'} = 1;
  1338. $source->{'search_exclude'} = 1;
  1339. $source->{'search_suffix'} = '/';
  1340. $sources{'KICK'} = $source;
  1341. }
  1342. }
  1343. # Torrentz
  1344. if ($ENABLE_SOURCE{'Z'}) {
  1345. my @proxies = ('torrentz.eu/search?q=', 'torrentz.me/search?q=', 'torrentz.ch/search?q=', 'torrentz.in/search?q=');
  1346. my $source = findProxy(\@proxies, 'Indexing [\d\,]+ active torrents');
  1347. if ($source) {
  1348. $source->{'weight'} = 1.00;
  1349. $source->{'quote'} = 1;
  1350. $source->{'search_exclude'} = 1;
  1351. $source->{'search_suffix'} = '';
  1352. if (!$NO_QUALITY_CHECKS) {
  1353. $source->{'search_suffix'} = '+peer+%3E+' . $MIN_COUNT,;
  1354. }
  1355. $sources{'Z'} = $source;
  1356. }
  1357. }
  1358. # ExtraTorrent
  1359. if ($ENABLE_SOURCE{'ET'}) {
  1360. my @proxies = ('extratorrent.cc/search/?search=', 'etmirror.com/search/?search=', 'etproxy.com/search/?search=', 'extratorrentlive.com/search/?search=');
  1361. my $source = findProxy(\@proxies, '/search/');
  1362. if ($source) {
  1363. $source->{'weight'} = 1.00;
  1364. $source->{'quote'} = 1;
  1365. $source->{'search_exclude'} = 0;
  1366. $source->{'search_suffix'} = '&new=1&x=0&y=0&srt=seeds&order=desc';
  1367. $sources{'ET'} = $source;
  1368. }
  1369. }
  1370. # Sanity check
  1371. if (scalar(keys(%sources)) < 1) {
  1372. die("No sources available\n");
  1373. }
  1374. return \%sources;
  1375. }
  1376. sub findProxy($$) {
  1377. my ($proxies, $match) = @_;
  1378. # Automatically select a proxy
  1379. my $host = '';
  1380. my $protocol = '';
  1381. my $search_url = '';
  1382. foreach my $url (@{$proxies}) {
  1383. my $path;
  1384. ($protocol, $host, $path) = $url =~ /^(?:(https?)\:\/\/)?([^\/]+)(\/.*)?$/i;
  1385. if (!$protocol) {
  1386. $protocol = $PROTOCOL;
  1387. }
  1388. if (!$host) {
  1389. print STDERR 'Could not parse proxy URL: ' . $url . "\n";
  1390. next;
  1391. }
  1392. $fetch->url($protocol . '://' . $host);
  1393. if ($fetch->fetch('nocheck' => 1) == 200 && $fetch->content() =~ m/${match}/i) {
  1394. $search_url = $protocol . '://' . $host . $path;
  1395. last;
  1396. } elsif ($DEBUG) {
  1397. print STDERR 'Proxy not available: ' . $host . "\n";
  1398. if ($DEBUG > 1) {
  1399. print STDERR $fetch->content() . "\n";
  1400. }
  1401. }
  1402. }
  1403. # Return the search data if at least one proxy is up
  1404. if ($search_url) {
  1405. my %tmp = (
  1406. 'protocol' => $protocol,
  1407. 'host' => $host,
  1408. 'search_url' => $search_url,
  1409. );
  1410. return \%tmp;
  1411. }
  1412. # Return undef if we didn't find any working proxies
  1413. return undef();
  1414. }