Cookie
view release on metacpan or search on metacpan
lib/Cookie/Domain.pm view on Meta::CPAN
{
$this //= __PACKAGE__;
$self = $this->new( $opts );
}
$opts->{file} //= '';
my $file = $opts->{file} || $self->file;
$file = $self->_is_a( $file, 'Module::Generic::File' ) ? $file : Module::Generic::File::file( $file );
require LWP::UserAgent;
my $ua = LWP::UserAgent->new(
agent => "Cookie::Domain/" . $VERSION,
);
my $meta = $self->meta;
my $req_headers = {};
my $dont_have_etag = 0;
my $mtime = $meta->{db_last_modified}
? $meta->{db_last_modified}
: ( $file->exists && !$file->is_empty )
? $file->mtime
: undef;
# If we have already a local file and it is not empty, let's use the etag when making the request
if( $meta->{etag} && $file->exists && !$file->is_empty )
{
$meta->{etag} =~ s/^\"([^"]+)\"$/$1/;
$req_headers->{'If-None-Match'} = qq{"$meta->{etag}"};
}
elsif( !$meta->{etag} )
{
$dont_have_etag = 1;
# <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since>
if( defined( $mtime ) && $mtime )
{
my $dt = $self->_parse_timestamp( $mtime );
if( $dt )
{
# HTTP Date format
my $dt_fmt = DateTime::Format::Strptime->new(
pattern => '%a, %d %b %Y %H:%M:%S GMT',
locale => 'en_GB',
time_zone => 'GMT',
);
$dt->set_formatter( $dt_fmt );
$req_headers->{ 'If-Modified-Since' } = $dt;
}
}
}
# try-catch
local $@;
my $resp = eval
{
$ua->get( URL, %$req_headers );
};
if( $@ )
{
return( $self->error( "Error trying to perform an HTTP GET request to ", URL, ": $@" ) );
}
my $code = $resp->code;
# try-catch
my $data = eval
{
$resp->decoded_content( default_charset => 'utf-8', alt_charset => 'utf-8' );
};
if( $@ )
{
return( $self->error( "Error decoding response content: $@" ) );
}
my $last_mod = $resp->header( 'Last-Modified' );
my $tz;
# DateTime::TimeZone::Local will die ungracefully if the local timezeon is not set with the error:
# "Cannot determine local time zone"
# try-catch
$tz = eval
{
DateTime::TimeZone->new( name => 'local' );
};
if( $@ )
{
$tz = DateTime::TimeZone->new( name => 'UTC' );
}
if( $last_mod )
{
$last_mod = $self->_parse_timestamp( $last_mod )->set_time_zone( $tz );
}
else
{
$last_mod = DateTime->now( time_zone => $tz );
}
my $epoch = $last_mod->epoch;
if( $resp->header( 'etag' ) )
{
$dont_have_etag = $resp->header( 'etag' ) eq ( $meta->{etag} // '' ) ? 0 : 1;
$meta->{etag} = $resp->header( 'etag' );
$meta->{etag} =~ s/^\"([^"]+)\"$/$1/;
}
if( $code == 304 ||
( !$file->is_empty && $mtime && $mtime == $epoch ) )
{
if( !$self->suffixes->length )
{
$self->load_public_suffix || return( $self->pass_error );
}
# Did not have an etag, but I do have one now
if( $dont_have_etag && $meta->{etag} )
{
$self->save_as_json || return( $self->pass_error );
}
return( $self );
}
elsif( $code ne 200 )
{
return( $self->error( "Failed to get the remote public domain list. Server responded with code '$code': ", $resp->as_string ) );
}
elsif( !length( $data ) )
{
return( $self->error( "Remote server returned no data." ) );
}
$file->unload_utf8( $data, { lock => 1 } ) || return( $self->error( "Unable to open public suffix data file \"$file\" in write mode: ", $file->error ) );
$file->unlock;
lib/Cookie/Domain.pm view on Meta::CPAN
This module will use a json cache data file to speed up the loading of the suffixes, a.k.a, top level domains, data.
By default the location of this json file will be C<public_suffix.json> under your system temporary directory, but you can override this by specifying your own location upon object instantiation:
my $dom = Cookie::Domain->new( json_file => '/home/joe/var/public_suffix.json' );
=head1 METHODS
=head2 new
This initiates the package and take the following parameters either as an hash or hash reference:
=over 4
=item * C<debug>
Optional. If set with a positive integer, this will activate verbose debugging message
=item * C<file>
Specify the location of the Public Suffix data file. The default one is under the same directory as this module with the file name C<public_suffix_list.txt>
You can download a different (new) version and specify with this parameter where it will be found.
=item * C<json_file>
Specify the location of the json cache data file. The default location is set using L<Module::Generic::File> to get the system temporary directory and the file name C<public_suffix.json>.
This json file is created once upon initiating an object and if it does not already exist. See the L</json_file> method for more information.
=item * C<min_suffix>
Sets the minimum suffix length required. Default to 0.
=item * C<no_load>
If this is set to true, this will prevent the object instantiation method from loading the public suffix file upon object instantiation. Normally you would not want to do that, unless you want to control when the file is loaded before you call L</sta...
=back
=head2 cron_fetch
You need to have installed the package L<LWP::UserAgent> to use this method.
This method can also be called as a package subroutine, such as C<Cookie::Domain::cron_fetch>
Its purpose is to perform a remote connection to L<https://publicsuffix.org/list/effective_tld_names.dat> and check for an updated copy of the public suffix data file.
It checks if the remote file has changed by using the http header field C<Last-Modified> in the server response, or if there is already an C<etag> stored in the cache, it performs a conditional http query using C<If-None-Matched>. See L<Mozilla docum...
This is important to save bandwidth and useless processing.
If the file has indeed changed, L</save_as_json> is invoked to refresh the cache.
It returns the object it was called with for chaining.
=head2 decode
Takes a domain name, or rather called a host name, such as C<www.æ±äº¬.jp> or C<ä»ä½å¹´.jp> and this will return its punycode ascii representation prefixed with a so-called ASCII Compatible Encoding, a.k.a. C<ACE>. Thus, using our previous example...
Even if the host name contains non-ascii dots, they will be recognised. For example C<wwwãæ±äº¬ãjp> would still be successfully decoded to C<www.xn--1lqs71d.jp>
If the host name provided is not an international domain name (a.k.a. IDN), it is simply returned as is. Thus, if C<www.example.org> is provided, it would return C<www.example.org>
If an error occurred, it sets an error object and returns L<perlfunc/undef>. The error can then be retrieved using L<Module::Generic/error> inherited by this module.
It uses L<Net::IDN::Encode/domain_to_ascii> to perform the actual decoding.
=head2 encode
This does the reverse operation from L</decode>.
It takes a domain name, or rather called a host name, already decoded, and with its so called ASCII Compatible Encoding a.k.a. C<ACE> prefix C<xn--> such as C<xn--wmq0m700b.jp> and returns its encoded version in perl internal utf8 encoding. Using the...
Just like in L</decode>, if a non-international domain name is provided, it is returned as is. Thus, if C<www.example.org> is provided, it would return C<www.example.org>
Note that this returns the name in perl's internal utf8 encoding, so if you need to save it to an utf8 file or print it out as utf8 string, you still need to encode it in utf8 before. For example:
use Cookie::Domain;
use open ':std' => ':utf8';
my $d = Cookie::Domain->new;
say $d->encode( "xn--wmq0m700b.jp" );
Or
use Cookie::Domain;
use Encode;
my $d = Cookie::Domain->new;
my $encoded = $d->encode( "xn--wmq0m700b.jp" );
say Encode::encode_utf8( $encoded );
If an error occurred, it sets an error object and returns L<perlfunc/undef>. The error can then be retrieved using L<Module::Generic/error> inherited by this module.
It uses L<Net::IDN::Encode/domain_to_unicode> to perform the actual encoding.
=head2 file
Sets the file path to the Public Suffix file. This file is a public domain file at the initiative of Mozilla Foundation and its latest version can be accessed here: L<https://publicsuffix.org/list/>
=head2 json_file
Sets the file path of the json cache data file. THe purpose of this file is to contain a json representation of the parsed data from the Public Suffix data file. This is to avoid re-parsing it each time and instead load the json file using the XS mod...
=head2 load
This method takes no parameter and relies on the properties set with L</file> and L</json_file>.
If the hash data is already accessibly in a module-wide variable, the data is taken from it.
Otherwise, if json_file is set and accessible, this will load the data from it, otherwise, it will load the data from the file specified with L</file> and save it as json.
If the json file meta data enclosed, specifically the property I<db_last_modified> has a unix timestamp value lower than the last modification timestamp of the public suffix data file, then, L</load> will reload that data file and save it as json aga...
That way, all you need to do is set up a crontab to fetch the latest version of that public suffix data file.
For example, to fetch it every day at 1:00 in the morning:
0 1 * * * perl -MCookie::Domain -e 'Cookie::Domain::cron_fetch' >/dev/null 2>&1
But if you want to store the public suffix data file somewhere other than the default location:
0 1 * * * perl -MCookie::Domain -e 'my $d=Cookie::Domain->new(file=>"/some/system/file.txt"); $d->cron_fetch' >/dev/null 2>&1
See your machine manpage for C<crontab> for more detail.
The data read are loaded into L</suffixes>.
It returns the current object for chaining.
=head2 load_json
This takes a file path to the json cache data as the only argument, and attempt to read its content and set it onto the data accessible with L</suffixes>.
( run in 2.549 seconds using v1.01-cache-2.11-cpan-ad19def0cd9 )