« blib/lib/Bootylicious/Plugin/BootyConfig.pm
↑ Summary
blib/lib/Bootylicious/ArticleArchiveSimple.pm »
| 1 | package Bootylicious::Plugin::PageCache; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base 'Mojolicious::Plugin'; | ||
| 7 | |||
| 8 | use File::stat; | ||
| 9 | use File::Spec; | ||
| 10 | |||
| 11 | __PACKAGE__->attr('root'); | ||
| 12 | |||
| 13 | sub register { | ||
| 14 | my ($self, $app, $conf) = @_; | ||
| 15 | |||
| 16 | $conf ||= {}; | ||
| 17 | $conf->{root} ||= 'cache'; | ||
| 18 | |||
| 19 | #->rel_dir('public/cache'); | ||
| 20 | |||
| 21 | $self->root($conf->{root}); | ||
| 22 | |||
| 23 | $app->plugins->add_hook(before_render => sub { _cache_hit(@_, $conf) }); | ||
| 24 | $app->plugins->add_hook( | ||
| 25 | after_dispatch => sub { _cache_response(@_, $conf) }); | ||
| 26 | } | ||
| 27 | |||
| 28 | sub _cache_path { | ||
| 29 | my ($c, $root) = @_; | ||
| 30 | |||
| 31 | my $path = $c->req->url->path; | ||
| 32 | $path = 'index' if !$path || $path eq '/'; | ||
| 33 | $path =~ s{^/}{}; | ||
| 34 | |||
| 35 | $path =~ s{/}{-}g; | ||
| 36 | |||
| 37 | $path .= '.html' unless $path =~ m/\.html$/; | ||
| 38 | |||
| 39 | return File::Spec->catfile($root, $path); | ||
| 40 | } | ||
| 41 | |||
| 42 | sub _cache_file { | ||
| 43 | my ($c, $path) = @_; | ||
| 44 | |||
| 45 | return File::Spec->catfile($c->app->static->root, $path); | ||
| 46 | } | ||
| 47 | |||
| 48 | sub _cache_hit { | ||
| 49 | my ($c, $conf) = @_; | ||
| 50 | |||
| 51 | return unless $c->req->method eq 'GET'; | ||
| 52 | |||
| 53 | return unless my $booty = $c->stash('booty'); | ||
| 54 | |||
| 55 | my $last_modified = $booty->modified->epoch; | ||
| 56 | return unless $last_modified; | ||
| 57 | |||
| 58 | my $path = _cache_path($c, $conf->{root}); | ||
| 59 | my $file = _cache_file($c, $path); | ||
| 60 | return unless $file; | ||
| 61 | |||
| 62 | if (-r $file && stat($file)->mtime >= $last_modified) { | ||
| 63 | $c->app->log->debug('Serving cached version'); | ||
| 64 | return $c->render_static($path); | ||
| 65 | } | ||
| 66 | |||
| 67 | $c->stash(page_cache => 1); | ||
| 68 | |||
| 69 | return; | ||
| 70 | } | ||
| 71 | |||
| 72 | sub _cache_response { | ||
| 73 | my ($c, $conf) = @_; | ||
| 74 | |||
| 75 | return unless $c->req->method eq 'GET'; | ||
| 76 | |||
| 77 | return unless $c->res->code && $c->res->code eq 200; | ||
| 78 | |||
| 79 | return unless $c->stash('page_cache'); | ||
| 80 | |||
| 81 | my $path = _cache_path($c, $conf->{root}); | ||
| 82 | my $file = _cache_file($c, $path); | ||
| 83 | return unless $file; | ||
| 84 | |||
| 85 | open my $fh, '>:encoding(UTF-8)', $file or return; | ||
| 86 | print $fh $c->res->body; | ||
| 87 | |||
| 88 | $c->app->log->debug('Cached response'); | ||
| 89 | } | ||
| 90 | |||
| 91 | 1; |