2021-06-22 22:37:01 +02:00
|
|
|
# File: LWPUserAgentCached.pm
|
|
|
|
#
|
2020-01-31 06:17:17 +01:00
|
|
|
# Purpose: variant of LWP::UserAgent::WithCache. Instead of depending on
|
|
|
|
# the 'expires' or 'Last-Modified' attributes, we always cache for the
|
|
|
|
# specified duration.
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
# SPDX-FileCopyrightText: 2021-2023 Pragmatic Software <pragma78@gmail.com>
|
2021-07-11 00:00:22 +02:00
|
|
|
# SPDX-License-Identifier: MIT
|
2021-06-22 22:37:01 +02:00
|
|
|
|
2021-07-24 04:22:25 +02:00
|
|
|
package PBot::Core::Utils::LWPUserAgentCached;
|
2021-06-22 22:37:01 +02:00
|
|
|
|
|
|
|
use PBot::Imports;
|
|
|
|
|
2020-01-31 06:17:17 +01:00
|
|
|
use base qw/LWP::UserAgent/;
|
|
|
|
use Cache::FileCache;
|
|
|
|
use File::HomeDir;
|
|
|
|
use File::Spec;
|
|
|
|
|
|
|
|
our %default_cache_args = (
|
2020-02-15 23:38:32 +01:00
|
|
|
'namespace' => 'pbot-cached',
|
|
|
|
'cache_root' => File::Spec->catfile(File::HomeDir->my_home, '.cache'),
|
|
|
|
'default_expires_in' => 600
|
2020-01-31 06:17:17 +01:00
|
|
|
);
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub new($class, @args) {
|
2020-02-15 23:38:32 +01:00
|
|
|
my $cache_opt;
|
|
|
|
my %lwp_opt;
|
2023-04-14 06:04:12 +02:00
|
|
|
unless (scalar @args % 2) {
|
|
|
|
%lwp_opt = @args;
|
2020-02-15 23:38:32 +01:00
|
|
|
$cache_opt = {};
|
|
|
|
for my $key (qw(namespace cache_root default_expires_in)) { $cache_opt->{$key} = delete $lwp_opt{$key} if exists $lwp_opt{$key}; }
|
|
|
|
} else {
|
2023-04-14 06:04:12 +02:00
|
|
|
$cache_opt = shift @args || {};
|
|
|
|
%lwp_opt = @args;
|
2020-01-31 06:17:17 +01:00
|
|
|
}
|
2020-02-15 23:38:32 +01:00
|
|
|
my $self = $class->SUPER::new(%lwp_opt);
|
|
|
|
my %cache_args = (%default_cache_args, %$cache_opt);
|
|
|
|
$self->{cache} = Cache::FileCache->new(\%cache_args);
|
|
|
|
return $self;
|
2020-01-31 06:17:17 +01:00
|
|
|
}
|
|
|
|
|
2023-04-14 06:04:12 +02:00
|
|
|
sub request($self, @args) {
|
2020-02-15 23:38:32 +01:00
|
|
|
my $request = $args[0];
|
|
|
|
return $self->SUPER::request(@args) if $request->method ne 'GET';
|
2020-02-09 05:53:05 +01:00
|
|
|
|
2020-02-15 23:38:32 +01:00
|
|
|
my $uri = $request->uri->as_string;
|
|
|
|
my $cached = $self->{cache}->get($uri);
|
|
|
|
return HTTP::Response->parse($cached) if defined $cached;
|
2020-02-09 05:53:05 +01:00
|
|
|
|
2020-02-15 23:38:32 +01:00
|
|
|
my $res = $self->SUPER::request(@args);
|
|
|
|
$self->{cache}->set($uri, $res->as_string) if $res->code eq HTTP::Status::RC_OK;
|
|
|
|
return $res;
|
2020-01-31 06:17:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
1;
|