| 1 | package Mojo::UserAgent::CookieJar::Role::Persistent; | ||
| 2 | use Mojo::Base '-role'; | ||
| 3 | |||
| 4 | use Mojo::Cookie::Response; | ||
| 5 | use Mojo::File; | ||
| 6 | |||
| 7 | our $VERSION = '0.002'; | ||
| 8 | |||
| 9 | has file => 'cookies.txt'; | ||
| 10 | has session => 1; | ||
| 11 | |||
| 12 | has expires_in => sub { sub {time + (60*10)} }; | ||
| 13 | |||
| 14 | requires qw(add all); | ||
| 15 | |||
| 16 | sub load { | ||
| 17 | my $self = shift; | ||
| 18 | |||
| 19 | my $file = Mojo::File->new($self->file); | ||
| 20 | return $self if !-e $file; | ||
| 21 | |||
| 22 | foreach my $cookie (map {[split /\t/]} split /\R/, $file->slurp) { | ||
| 23 | next if $#$cookie != 6; | ||
| 24 | my %cookie; | ||
| 25 | @cookie{qw[domain flag path secure expires name value]} | ||
| 26 | = @{$cookie}; | ||
| 27 | delete $cookie{flag}; | ||
| 28 | $cookie{secure} = $cookie{secure} eq 'TRUE' ? 1 : 0; | ||
| 29 | $self->add(Mojo::Cookie::Response->new(%cookie)); | ||
| 30 | } | ||
| 31 | |||
| 32 | return $self; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub save { | ||
| 36 | my $self = shift; | ||
| 37 | |||
| 38 | my $session = $self->session; | ||
| 39 | |||
| 40 | my @cookies; | ||
| 41 | foreach my $cookie (@{$self->all}) { | ||
| 42 | push @cookies, [ | ||
| 43 | $cookie->domain // ($session ? $cookie->origin : next), | ||
| 44 | ($session) ? 'TRUE' : 'FALSE', | ||
| 45 | $cookie->path, | ||
| 46 | ($cookie->secure) ? 'TRUE' : 'FALSE', | ||
| 47 | $cookie->expires // ($session ? $self->expires_in->() : next), | ||
| 48 | $cookie->name, | ||
| 49 | $cookie->value, | ||
| 50 | ]; | ||
| 51 | } | ||
| 52 | |||
| 53 | Mojo::File->new($self->file)->spurt(join "\n", | ||
| 54 | '# Netscape HTTP Cookie File', | ||
| 55 | '', | ||
| 56 | map { join "\t", @{$_} } @cookies | ||
| 57 | ); | ||
| 58 | |||
| 59 | return $self; | ||
| 60 | } | ||
| 61 | |||
| 62 | 1; |