Add caching to naodash_user
[nethack-naodash.git] / lib / NetHack / NAOdash.pm
index af574ef2fcfe71b12796bc383c4ef412bfe53834..92f17ef6d2a79e408b845dd80d15ec031d14f132 100644 (file)
@@ -10,6 +10,8 @@ our $VERSION = '0.001';
 our @EXPORT_OK = qw/naodash_xlog naodash_user/;
 our @EXPORT = @EXPORT_OK;
 
+use File::Slurp;
+use File::Spec::Functions qw/tmpdir catdir catfile/;
 use HTTP::Tiny;
 use List::Util qw/max min sum/;
 use List::MoreUtils qw/uniq/;
@@ -111,11 +113,26 @@ sub naodash_xlog { ## no critic (RequireArgUnpacking)
 
 my $ht = HTTP::Tiny->new(agent => "NetHack-NAOdash/$VERSION ");
 
-sub naodash_user {
+sub _get_xlog_from_server {
        my ($name) = @_;
        my $ret = $ht->get("http://alt.org/nethack/player-all-xlog.php?player=$name");
        die 'Error while retrieving xlogfile from alt.org: ' . $ret->{status} . ' ' . $ret->{reason} . "\n" unless $ret->{success};
-       my ($xlog) = $ret->{content} =~ m{<pre>(.*)</pre>}i;
+       $ret->{content} =~ m{<pre>(.*)</pre>}i;
+}
+
+sub _get_xlog {
+       my ($name) = @_;
+       return _get_xlog_from_server $name if $ENV{NAODASH_CACHE} && lc $ENV{NAODASH_CACHE} eq 'none';
+       my $dir = $ENV{NAODASH_CACHE} || catdir tmpdir, 'naodash';
+       mkdir $dir or die "Cannot create cache directory: $!\n" unless -d $dir;
+       my $file = catfile $dir, $name;
+       write_file $file, _get_xlog_from_server $name unless -f $file && time - (stat $file)[9] < 86400;
+       scalar read_file $file
+}
+
+sub naodash_user {
+       my ($name) = @_;
+       my $xlog = _get_xlog $name;
        die "No xlogfile found for user $name\n" unless defined $xlog;
        naodash_xlog $xlog;
 }
@@ -264,6 +281,24 @@ Retrieves the xlogfile of a user from NAO and gives it to
 B<naodash_xlog>. Dies if no xlogfile is found or if the server cannot
 be contacted.
 
+This method caches the downloaded xlogfiles for one day in the
+directory named by the NAODASH_CACHE environment variable.
+
+=back
+
+=head1 ENVIRONMENT
+
+=over
+
+=item NAODASH_CACHE
+
+Path to a directory that should be used to cache xlogfiles downloaded
+from NAO, or the special value 'none' (case-insensitive) to disable
+caching.
+
+By default a directory named 'naodash' in the default temporary
+directory (C<< File::Spec->tmpdir >>) is used.
+
 =back
 
 =head1 SEE ALSO
This page took 0.010882 seconds and 4 git commands to generate.