77 lines
1.7 KiB
Perl
77 lines
1.7 KiB
Perl
package Shrlbe::Controller::Main;
|
|
use Mojo::Base 'Mojolicious::Controller', -signatures;
|
|
|
|
use Shrlbe::Model::Url;
|
|
use Shrlbe::Model::Url::Manager;
|
|
|
|
|
|
sub index($self)
|
|
{
|
|
$self->render(template => 'index', page_data => {});
|
|
}
|
|
|
|
sub short_api ($self)
|
|
{
|
|
my $original_url = $self->param('url');
|
|
|
|
my $shorten_url = $self->_saveShortUrl($original_url);
|
|
|
|
$self->render(text => $shorten_url);
|
|
}
|
|
|
|
sub short($self)
|
|
{
|
|
my $original_url = $self->param('url');
|
|
|
|
my $shorten_url = $self->_saveShortUrl($original_url);
|
|
|
|
$self->render(template => 'index', page_data => {url => $original_url, shorten_url => $shorten_url});
|
|
}
|
|
|
|
sub get_shorten($self)
|
|
{
|
|
my $path = $self->param('shorten_path');
|
|
|
|
my $url = Shrlbe::Model::Url->new(hash => $path);
|
|
if ($url->load(speculative => 1)) {
|
|
$self->res->code(307);
|
|
$self->redirect_to($url->original_url());
|
|
}
|
|
else {
|
|
$self->render(status => 404, text => 'Page not found :(');
|
|
}
|
|
}
|
|
|
|
sub _saveShortUrl($self, $original_url)
|
|
{
|
|
my $hash;
|
|
|
|
my $normalized_url = $self->sh_utils()->normalizeUrl($original_url);
|
|
|
|
my $url = $self->_loadUrl($normalized_url);
|
|
|
|
if (!$url) {
|
|
$hash = $self->sh_utils()->hashUrl($normalized_url);
|
|
|
|
$url = Shrlbe::Model::Url->new(hash => $hash, normalized_url => $normalized_url, original_url => $original_url)->save();
|
|
}
|
|
else {
|
|
$hash = $url->hash();
|
|
}
|
|
|
|
return sprintf('%s/%s', $self->site_name(), $hash);
|
|
}
|
|
|
|
sub _loadUrl($self, $normalized_url)
|
|
{
|
|
my $urls = Shrlbe::Model::Url::Manager->get_urls(
|
|
query => [
|
|
normalized_url => $normalized_url
|
|
],
|
|
limit => 1,
|
|
);
|
|
|
|
return $urls->[0];
|
|
}
|
|
|
|
1;
|