findTorrent.pl 33 KB

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