aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/TgLib/Cache.pm26
-rwxr-xr-xtgrecv11
-rwxr-xr-xtgsend2
3 files changed, 21 insertions, 18 deletions
diff --git a/lib/TgLib/Cache.pm b/lib/TgLib/Cache.pm
index b6bb9e6..dbbf252 100644
--- a/lib/TgLib/Cache.pm
+++ b/lib/TgLib/Cache.pm
@@ -3,6 +3,7 @@ package TgLib::Cache;
use Storable qw<store retrieve>;
use File::Basename qw<dirname>;
use File::Path qw<make_path>;
+use Data::Dumper;
use TgLib::Env qw<$CACHE_HOME>;
@@ -12,24 +13,31 @@ our @EXPORT = qw<new>;
my $CACHE_FILE = "$CACHE_HOME/tgutils/cache";
sub new {
- my $class = shift;
+ my ($class, $logger) = @_;
+ my $cache = -f $CACHE_FILE
+ ? retrieve($CACHE_FILE)
+ : { version => 1 };
+ $logger->debug("Using cache: " . Dumper($cache));
# Fetch cache
- return bless((-f $CACHE_FILE
- ? retrieve($CACHE_FILE)
- : {'version' => $main::VERSION}), $class);
+ return bless { cache => $cache, logger => $logger }, $class;
}
sub offset {
- my $cache = shift;
- $cache->{'offset'} = shift if @_;
- return $cache->{'offset'};
+ my $self = shift;
+ if (@_) {
+ $self->{'cache'}{'offset'} = shift;
+ $self->save;
+ }
+ return $self->{'cache'}{'offset'};
}
+# Not needed to be called explicitly; every cache modification calls this
sub save {
- my $cache = shift;
+ my $self = shift;
make_path dirname $CACHE_FILE;
- store($cache, $CACHE_FILE);
+ store($self->{'cache'}, $CACHE_FILE);
+ $self->{'logger'}->debug(sprintf "Saved cache: %s\n", Dumper($self->{'cache'}));
}
1;
diff --git a/tgrecv b/tgrecv
index 01b2d9e..4670b63 100755
--- a/tgrecv
+++ b/tgrecv
@@ -18,9 +18,9 @@ use JSON qw<encode_json>;
use FindBin;
use lib "$FindBin::Bin/lib";
use TgLib qw<fetch_token>;
+require TgLib::Api;
require TgLib::Cache;
require TgLib::Logger;
-require TgLib::Api;
my $TOKEN;
my $OUTPUT;
@@ -46,8 +46,7 @@ $TOKEN ||= fetch_token() or
pod2usage(-message => "ERROR: Unable to get bot token ($!).\n",
-verbose => 99, -sections => "AUTHENTICATION");
-my $cache = TgLib::Cache->new;
-$logger->debug("Using cache: " . Dumper($cache));
+my $cache = TgLib::Cache->new($logger);
# Get offset from cache if --auto-offset is enabled (and no --offset provided)
if ($AUTO_OFFSET && ! $OFFSET) {
@@ -63,11 +62,7 @@ if ($OUTPUT) {
}
# Store new offset in cache (last update id +1)
-if ($AUTO_OFFSET && @$updates) {
- $cache->offset($updates->[-1]{'update_id'}+1);
- $logger->debug(sprintf "Cached offset %s (--auto-offset)\n", $cache->offset);
- $cache->save;
-}
+$cache->offset($updates->[-1]{'update_id'}+1) if ($AUTO_OFFSET && @$updates);
print $out encode_json($updates);
diff --git a/tgsend b/tgsend
index e9100b7..db6f412 100755
--- a/tgsend
+++ b/tgsend
@@ -16,8 +16,8 @@ use Pod::Usage qw<pod2usage>;
use FindBin;
use lib "$FindBin::Bin/lib";
use TgLib qw<fetch_token>;
-require TgLib::Logger;
require TgLib::Api;
+require TgLib::Logger;
my $TOKEN;
my $PRETEND;