# HG changeset patch # User Dominic Cleal # Date 1232904547 0 # Node ID ccbd8fa63b9ff2565f6f29c0d8a855d4ce7f7f2b # Parent 266c93756c1b4ea780232951a613173ec4229dd1 Adding a cache for mineral marks diff -r 266c93756c1b -r ccbd8fa63b9f reproctool.cgi --- a/reproctool.cgi Sun Jan 25 17:03:23 2009 +0000 +++ b/reproctool.cgi Sun Jan 25 17:29:07 2009 +0000 @@ -6,9 +6,13 @@ use CGI; use DBI; use LWP::UserAgent; +use Storable qw/store_fd fd_retrieve/; # Settings my $img_http_path = '/itemimgs'; +my $eve_central_url = 'http://eve-central.com/api/evemon'; +my $marks_cache = 'minerals.cache'; +my $marks_cache_expiry = 4 * 60 * 60; # 4 hours my $cgi = new CGI; print $cgi->header(-type => 'text/html', @@ -34,21 +38,54 @@ unless ($str_items) { - my $eveCentralURL = 'http://eve-central.com/api/evemon'; - my $ua = LWP::UserAgent->new; - $ua->agent('reproctool'); - my $resp = $ua->request(HTTP::Request->new(GET => $eveCentralURL)); + my $marks; + if (-e $marks_cache) + { + open CACHE, "< $marks_cache" || die("Can't open cache $marks_cache: $!"); + $marks = fd_retrieve(*CACHE) || die("Can't read marks from cache: $!"); + close CACHE; + + if (time > ($marks->{timestamp} + $marks_cache_expiry)) + { + $marks = undef; + } + else + { + delete $marks->{timestamp}; + } + } - my %marks; - $marks{$_} = 1 foreach ('Tritanium', 'Pyerite', 'Mexallon', 'Isogen', - 'Nocxium', 'Zydrine', 'Megacyte', 'Morphite'); - - if ($resp->is_success) + unless ($marks) { - foreach (split(/[\n\r]/, $resp->content)) + my $ua = LWP::UserAgent->new; + $ua->agent('reproctool'); + my $resp = $ua->request(HTTP::Request->new(GET => $eve_central_url)); + + if ($resp->is_success) { - next unless (/(.+)<\/name>.*([0-9\.]+)<\/price>/i); - $marks{$1} = $2; + $marks = { timestamp => time }; + foreach (split(/[\n\r]/, $resp->content)) + { + next unless (/(.+)<\/name>.*([0-9\.]+)<\/price>/i); + $marks->{$1} = $2; + } + + if (-e $marks_cache) + { + unlink $marks_cache + || die("Unable to unlink cache $marks_cache: $!"); + } + + open CACHE, "> $marks_cache" + || die("Can't open cache $marks_cache to write: $!"); + store_fd($marks, *CACHE) || die("Can't write to cache: $!"); + close CACHE; + } + else + { + $marks->{$_} = 1 foreach ('Tritanium', 'Pyerite', 'Mexallon', + 'Isogen', 'Nocxium', 'Zydrine', + 'Megacyte', 'Morphite'); } } @@ -63,13 +100,13 @@ END # Lists the name of the minerals. - print "$_\n" foreach (keys %marks); + print "$_\n" foreach (keys %{$marks}); print ""; - foreach (keys %marks) + foreach (keys %{$marks}) { my $sname = lc substr($_, 0, 4); - my $fmt = sprintf('%.2f', $marks{$_}); + my $fmt = sprintf('%.2f', $marks->{$_}); print "\n"; }