findTorrent.pl 40 KB

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