Lstu.pm 8.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
# vim:set sw=4 ts=4 sts=4 ft=perl expandtab:
package Lstu::Controller::Lstu;
use Mojo::Base 'Mojolicious::Controller';
use LstuModel;
use Data::Validate::URI qw(is_http_uri is_https_uri);
use Mojo::JSON qw(to_json decode_json);
use Mojo::URL;

sub add {
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    my $c = shift;

    #$c->cleaning;

    my $ip = $c->ip;

    my @banned = LstuModel::Ban->select('WHERE ip = ? AND until > ? AND strike >= 3', $ip, time);
    if (scalar @banned) {
        my $penalty = 3600;
        if ($banned[0]->strike >= 6) {
            $penalty = 3600 * 24 * 30; # 30 days of banishing
        }
        $banned[0]->update(
            strike => $banned[0]->strike + 1,
            until  => time + $penalty
        );
        my $msg = $c->l('You asked to shorten too many URLs too quickly. You\'re banned for %1 hour(s).', $penalty/3600);
        $c->respond_to(
            json => { json => { success => Mojo::JSON->false, msg => $msg } },
            any  => sub {
                my $c = shift;

                $c->flash('msg' => $msg);
                $c->flash('banned' => 1);
                $c->redirect_to('index');
            }
        );
    } else {
        my $url        = Mojo::URL->new($c->param('lsturl'));
        my $custom_url = $c->param('lsturl-custom');
        my $format     = $c->param('format');

        $custom_url = undef if (defined($custom_url) && $custom_url eq '');
43

44 45 46 47 48 49 50 51 52 53 54
        my ($msg, $short);
        if (defined($custom_url) && ($custom_url =~ m/^a(pi)?$|^stats$/ || $custom_url =~ m/^d$/ ||
            $custom_url =~ m/\.json$/ || $custom_url !~ m/^[-a-zA-Z0-9_]+$/))
        {
            $msg = $c->l('The shortened text can contain only numbers, letters and the - and _ character, can\'t be "a", "api", "d" or "stats" or end with ".json". Your URL to shorten: %1', $url);
        } elsif (defined($custom_url) && LstuModel::Lstu->count('WHERE short = ?', $custom_url) > 0) {
            $msg = $c->l('The shortened text (%1) is already used. Please choose another one.', $custom_url);
        } elsif (is_http_uri($url->to_string) || is_https_uri($url->to_string)) {
            my $res = $c->is_spam($url, 0);
            if ($res->{is_spam}) {
                $msg = $res->{msg};
55
            } else {
56
                my @records = LstuModel::Lstu->select('WHERE url = ?', $url);
57

58 59 60 61 62 63 64 65 66 67
                if (scalar(@records) && !defined($custom_url)) {
                    # Already got this URL
                    $short = $records[0]->short;
                } else {
                    my @bans = LstuModel::Ban->select('WHERE ip = ?', $ip);
                    if (scalar @bans) {
                        $bans[0]->update(
                            strike => $bans[0]->strike + 1,
                            until  => time + 1
                        );
68
                    } else {
69 70 71 72 73 74 75 76 77 78 79
                        LstuModel::Ban->create(
                            ip     => $ip,
                            strike => 1,
                            until  => time + 1
                        );
                    }

                    if(LstuModel->begin) {
                        if (defined($custom_url)) {
                            LstuModel::Lstu->create(
                                short     => $custom_url,
80 81 82 83 84
                                url       => $url,
                                counter   => 0,
                                timestamp => time()
                            );

85
                            $short = $custom_url;
86
                        } else {
87 88 89 90 91 92 93 94 95 96 97 98 99
                            @records = LstuModel::Lstu->select('WHERE url IS NULL LIMIT 1');
                            if (scalar(@records)) {
                                $records[0]->update(
                                    url       => $url,
                                    counter   => 0,
                                    timestamp => time()
                                );

                                $short = $records[0]->short;
                            } else {
                                # Houston, we have a problem
                                $msg = $c->l('No shortened URL available. Please retry or contact the administrator at %1. Your URL to shorten: [_2]', $c->config('contact'), $url);
                            }
100
                        }
101
                        LstuModel->commit;
102 103 104
                    }
                }
            }
105 106
        } else {
            $msg = $c->l('%1 is not a valid URL.', $url);
107
        }
108 109 110 111 112
        if ($msg) {
            $c->respond_to(
                json => { json => { success => Mojo::JSON->false, msg => $msg } },
                any  => sub {
                    my $c = shift;
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
                    $c->flash('msg' => $msg);
                    $c->redirect_to('index');
                }
            );
        } else {
            # Get URLs from cookie
            my $u = (defined($c->cookie('url'))) ? decode_json $c->cookie('url') : [];
            # Add the new URL
            push @{$u}, $short;
            # Make the array contain only unique URLs
            my %k = map { $_, 1 } @{$u};
            @{$u} = keys %k;
            # And set the cookie
            my $cookie = to_json($u);
            $c->cookie('url' => $cookie, {expires => time + 142560000}); # expires in 10 years
129

130
            my $prefix = $c->prefix;
131

132 133 134 135 136 137 138 139 140 141 142
            $c->respond_to(
                json => { json => { success => Mojo::JSON->true, url => $url, short => $prefix.$short } },
                any  => sub {
                    my $c = shift;

                    $c->flash('url'   => $url);
                    $c->flash('short' => $prefix.$short);
                    $c->redirect_to('index');
                }
            );
        }
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    }
}

sub stats {
    my $c = shift;

    if (defined($c->session('token')) && LstuModel::Sessions->count('WHERE token = ?', $c->session('token'))) {
        my $total = LstuModel::Lstu->count("WHERE url IS NOT NULL");
        my $page  = $c->param('page') || 0;
           $page  = 0 if ($page < 0);
           $page  = $page - 1 if ($page * $c->config('page_offset') > $total);

        my ($first, $last) = (!$page, ($page * $c->config('page_offset') <= $total && $total < ($page + 1) * $c->config('page_offset')));

        my @urls  = LstuModel::Lstu->select("WHERE url IS NOT NULL ORDER BY counter DESC LIMIT ? offset ?", $c->config('page_offset'), $page * $c->config('page_offset'));
        $c->render(
            template => 'stats',
            prefix   => $c->prefix,
            urls     => \@urls,
            first    => $first,
            last     => $last,
            page     => $page,
            admin    => 1,
            total    => $total
        )
    } else {
        my $u = (defined($c->cookie('url'))) ? decode_json $c->cookie('url') : [];

        my $p = join ",", (('?') x @{$u});
        my @urls = LstuModel::Lstu->select("WHERE short IN ($p) ORDER BY counter DESC", @{$u});

        my $prefix = $c->prefix;

        $c->respond_to(
            json => sub {
                my @struct;
                for my $url (@urls) {
                    push @struct, {
                        short      => $prefix.$url->{short},
                        url        => $url->{url},
                        counter    => $url->{counter},
                        created_at => $url->{timestamp}
                    };
                }
                $c->render( json => \@struct );
            },
            any  => sub {
                shift->render(
                    template => 'stats',
                    prefix   => $prefix,
                    urls     => \@urls
                )
            }
        )
    }
}

sub get {
    my $c = shift;
    my $short = $c->param('short');

    my @urls = LstuModel::Lstu->select('WHERE short = ?', $short);
    if (scalar(@urls)) {
        my $url = $urls[0]->url;
        $c->respond_to(
            json => { json => { success => Mojo::JSON->true, url => $url } },
            any  => sub {
                my $c = shift;
                $c->res->code(301);
                $c->redirect_to($url);
            }
        );
        # Update counter
        $c->on(finish => sub {
            my $counter = $urls[0]->counter + 1;
            $urls[0]->update (counter => $counter);
        });
    } else {
        my $msg = $c->l('The shortened URL %1 doesn\'t exist.', $c->url_for('/')->to_abs.$short);
        $c->respond_to(
            json => { json => { success => Mojo::JSON->false, msg => $msg } },
            any  => sub {
                my $c = shift;

                $c->flash('msg' => $msg);
                $c->redirect_to('index');
            }
        );
    }
}

1;