burguillos.info/lib/BurguillosInfo/Controller/ConquerTile.pm

53 lines
1.5 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;
my $cache_files_dir = path(__FILE__)->parent->parent->parent->parent->child('cache/tiles/');
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) {
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.!!');
}
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;