]> www.fi.muni.cz Git - aoc.git/blob - lib/Y/AoC/UA.pm
New fancy infrastructure: downloader, inotify watcher, submitter
[aoc.git] / lib / Y / AoC / UA.pm
1 package Y::AoC::UA;
2
3 use v5.36;
4
5 use Mojo::Base -signatures;
6 use Mojo::UserAgent;
7 use Mojo::DOM;
8 use Y::AoC qw(white);
9
10 our $user_agent = 'kas@yenya.net https://www.fi.muni.cz/~kas/git/aoc.git';
11 our $cache_dir = '/home/kas/aoc/cache';
12 our $cookie;
13
14 sub request($url, $args) {
15         chomp($cookie //= Mojo::File->new("$cache_dir/cookie")->slurp);
16
17         my ($cache, $cachefile);
18         if ($args->{cache_to}) {
19                 $cachefile = $cache_dir . '/' . $args->{cache_to};
20                 $cache = Mojo::File->new("$cachefile");
21
22                 if ($args->{max_age}) { 
23                         $cache->remove
24                                 if $cache->stat
25                                 && time - $cache->stat->mtime
26                                         > $args->{max_age};
27                 }
28
29                 if ($cache->stat) {
30                         say "\n", white('cached'),
31                                 " response from $cachefile";
32                         return Mojo::DOM->new($cache->slurp);
33                 }
34         }
35
36         my $res;
37         my %hdrs = (
38                 Cookie       => $cookie,
39                 'User-Agent' => $user_agent,
40         );
41         my $ua = Mojo::UserAgent->new;
42         if ($args->{form}) {
43                 $res = $ua->post($url => \%hdrs => form => $args->{form})
44                         ->result;
45         } else {
46                 $res = $ua->get($url => \%hdrs)->result;
47         }
48
49         if (!$res->is_success) {
50                 say $res->message;
51                 say "body:\n",  $res->body;
52                 die red("http request failed");
53         }
54
55         if ($cache) {
56                 $cache->spurt($res->body);
57                 # say "Stored response to $cachefile";
58         }
59         return $args->{body} ? $res->body : $res->dom;
60 }
61
62 sub cache_del($file) {
63         my $f = Mojo::File->new("$cache_dir/$file");
64         return if !$f->stat;
65         $f->move_to("$cache_dir/old-$file");
66 }
67
68 sub is_cached($file) { Mojo::File->new("$cache_dir/$file")->stat; }
69
70 1;
71 __END__
72 package Y::AoC::UA;
73
74 sub new($class, $year, $day) {
75         eval 'require
76 }
77
78 sub get($ua) {
79 1;