71 lines
2.0 KiB
Perl
71 lines
2.0 KiB
Perl
package BurguillosInfo::Controller::ConquerTile;
|
|
|
|
use v5.34.1;
|
|
|
|
use strict;
|
|
use warnings;
|
|
|
|
use utf8;
|
|
|
|
use Mojo::Base 'Mojolicious::Controller', '-signatures';
|
|
use Path::Tiny;
|
|
use Mojo::UserAgent;
|
|
use DateTime::Format::HTTP;
|
|
use DateTime;
|
|
|
|
my $cache_files_dir =
|
|
path(__FILE__)->parent->parent->parent->parent->child('cache/tiles/');
|
|
|
|
sub _cache_response ($self) {
|
|
my $tomorrow_same_hour_datetime = DateTime->now->add( days => 1 );
|
|
$self->res->headers->cache_control("max_age=@{[3600*24]}");
|
|
$self->res->headers->expires(
|
|
DateTime::Format::HTTP->format_datetime($tomorrow_same_hour_datetime) );
|
|
}
|
|
|
|
sub tile ($self) {
|
|
my $zoom = $self->stash('zoom');
|
|
my $x = $self->stash('x');
|
|
my $y = $self->stash('y');
|
|
my $candidate_file = $cache_files_dir->child("$zoom-$x-$y.png");
|
|
if ( -f $candidate_file ) {
|
|
$self->_cache_response;
|
|
return $self->_render_png($candidate_file);
|
|
}
|
|
if ( !defined $self->current_user ) {
|
|
return $self->render(
|
|
status => 401,
|
|
text => '¡¡No estás loggeado, no puedes cargar mapa nuevo.!!'
|
|
);
|
|
}
|
|
$self->_cache_response;
|
|
my $file_to_write = $candidate_file;
|
|
my $ua = Mojo::UserAgent->new;
|
|
my $png_tile =
|
|
$ua->get("https://tile.openstreetmap.org/$zoom/$x/$y.png")->result->body;
|
|
open my $fh, '|-', 'convert', '/dev/stdin', '-channel', 'RGB', '-negate',
|
|
$file_to_write;
|
|
print $fh $png_tile;
|
|
close $fh;
|
|
$self->_render_png($file_to_write);
|
|
$self->_delete_extra_files();
|
|
}
|
|
|
|
sub _delete_extra_files ($self) {
|
|
my @files = $cache_files_dir->children;
|
|
if ( scalar @files < 20001 ) {
|
|
return;
|
|
}
|
|
@files = sort { -M $a <=> -M $b } @files;
|
|
for ( my $i = 0 ; $i < ( scalar @files ) - 20000 ; $i++ ) {
|
|
system 'rm', '-v', $files[$i];
|
|
}
|
|
}
|
|
|
|
sub _render_png ( $self, $file ) {
|
|
system 'touch', $file;
|
|
return $self->render( data => $file->slurp_raw, status => 200,
|
|
format => 'png' );
|
|
}
|
|
1;
|