Helpers.pm 8.75 KB
Newer Older
Luc Didry's avatar
Luc Didry committed
1
2
3
4
# vim:set sw=4 ts=4 sts=4 ft=perl expandtab:
package Lutim::Plugin::Helpers;
use Mojo::Base 'Mojolicious::Plugin';
use Mojo::Util qw(quote);
Luc Didry's avatar
Luc Didry committed
5
use Mojo::File;
Luc Didry's avatar
Luc Didry committed
6
7
use Crypt::CBC;
use Data::Entropy qw(entropy_source);
8
use DateTime;
Luc Didry's avatar
Luc Didry committed
9
10
11
12

sub register {
    my ($self, $app) = @_;

Luc Didry's avatar
Luc Didry committed
13
14
    $app->plugin('PgURLHelper');

Luc Didry's avatar
Luc Didry committed
15
16
17
18
19
20
    if ($app->config('dbtype') eq 'postgresql') {
        use Mojo::Pg;
        $app->helper(pg => \&_pg);

        # Database migration
        my $migrations = Mojo::Pg::Migrations->new(pg => $app->pg);
Luc Didry's avatar
Luc Didry committed
21
        if ($app->mode eq 'development' && $ENV{LUTIM_DEBUG}) {
22
            $migrations->from_file('utilities/migrations/postgresql.sql')->migrate(0)->migrate(3);
Luc Didry's avatar
Luc Didry committed
23
        } else {
24
            $migrations->from_file('utilities/migrations/postgresql.sql')->migrate(3);
25
26
27
28
29
30
31
32
33
34
35
36
        }
    } elsif ($app->config('dbtype') eq 'sqlite') {
        # SQLite database migration if needed
        use Mojo::SQLite;
        $app->helper(sqlite => \&_sqlite);

        my $sql = Mojo::SQLite->new('sqlite:'.$app->config('db_path'));
        my $migrations = $sql->migrations;
        if ($app->mode eq 'development' && $ENV{LUTIM_DEBUG}) {
            $migrations->from_file('utilities/migrations/sqlite.sql')->migrate(0)->migrate(2);
        } else {
            $migrations->from_file('utilities/migrations/sqlite.sql')->migrate(2);
Luc Didry's avatar
Luc Didry committed
37
38
39
        }
    }

Luc Didry's avatar
Luc Didry committed
40
41
42
43
44
45
46
47
48
49
50
    $app->helper(render_file     => \&_render_file);
    $app->helper(ip              => \&_ip);
    $app->helper(provisioning    => \&_provisioning);
    $app->helper(shortener       => \&_shortener);
    $app->helper(stop_upload     => \&_stop_upload);
    $app->helper(max_delay       => \&_max_delay);
    $app->helper(default_delay   => \&_default_delay);
    $app->helper(is_selected     => \&_is_selected);
    $app->helper(crypt           => \&_crypt);
    $app->helper(decrypt         => \&_decrypt);
    $app->helper(delete_image    => \&_delete_image);
Luc Didry's avatar
Luc Didry committed
51
52
53
54
55
}

sub _pg {
    my $c     = shift;

Luc Didry's avatar
Luc Didry committed
56
    state $pg = Mojo::Pg->new($c->app->pg_url($c->app->config('pgdb')));
Luc Didry's avatar
Luc Didry committed
57
58
59
    return $pg;
}

60
61
62
63
64
65
66
sub _sqlite {
    my $c     = shift;

    state $sqlite = Mojo::SQLite->new('sqlite:'.$c->app->config('db_path'));
    return $sqlite;
}

Luc Didry's avatar
Luc Didry committed
67
68
sub _render_file {
    my $c = shift;
69
70
71
72
73
74
75
76
    my ($im_loaded, $img, $dl, $key, $thumb) = @_;

    my ($filename, $path, $iv, $mediatype, $no_cache) = ($img->filename, $img->path, $img->iv, $img->mediatype, $img->delete_at_first_view);

    my $expires = ($img->delete_at_day) ? $img->delete_at_day : 360;
    my $dt = DateTime->from_epoch( epoch => $expires * 86400 + $img->created_at);
    $dt->set_time_zone('GMT');
    $expires = $dt->strftime("%a, %d %b %Y %H:%M:%S GMT");
Luc Didry's avatar
Luc Didry committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

    $dl       = 'attachment' if ($mediatype =~ m/svg/);
    $filename = quote($filename);

    unless (-f $path && -r $path) {
        $c->app->log->error("Cannot read file [$path]. error [$!]");
        $c->flash(
            msg => $c->l('Unable to find the image: it has been deleted.')
        );
        return 500;
    }

    $mediatype =~ s/x-//;

    my $headers = Mojo::Headers->new();
92
    if ($no_cache || defined($thumb)) {
Luc Didry's avatar
Luc Didry committed
93
94
95
96
97
98
99
100
        $headers->add('Cache-Control'   => 'no-cache, no-store, max-age=0, must-revalidate');
    } else {
        $headers->add('Expires'         => $expires);
    }
    $headers->add('Content-Type'        => $mediatype.';name='.$filename);
    $headers->add('Content-Disposition' => $dl.';filename='.$filename);
    $c->res->content->headers($headers);

Luc Didry's avatar
Luc Didry committed
101
102
103
104
105
106
107
108
109
110
111
112
113
    my $cache = $c->app->{images_cache}->compute($img->short, undef, sub {
        if ($key) {
            return {
                asset      => $c->decrypt($key, $path, $iv),
                key        => $key
            };
        } else {
            return {
                asset      => Mojo::File->new($path)->slurp,
            };
        }
    });
    if ($key && $key ne $cache->{key}) {
Luc Didry's avatar
Luc Didry committed
114
115
        my $tmp = $c->decrypt($key, $path, $iv);
        $cache->{asset} = $tmp;
Luc Didry's avatar
Luc Didry committed
116
117
118
        $c->app->{images_cache}->replace(
            $img->short,
            {
Luc Didry's avatar
Luc Didry committed
119
                asset      => $tmp,
Luc Didry's avatar
Luc Didry committed
120
121
122
                key        => $key
            },
        );
Luc Didry's avatar
Luc Didry committed
123
    }
Luc Didry's avatar
Luc Didry committed
124
125
126
    # Extend expiration time
    my $asset = Mojo::Asset::Memory->new;
    $asset->add_chunk($cache->{asset});
Luc Didry's avatar
Luc Didry committed
127
128
129
130
131
132

    if (defined $thumb && $im_loaded && $mediatype ne 'image/svg+xml' && $mediatype !~ m#image/(x-)?xcf# && $mediatype ne 'image/webp') { # ImageMagick don't work in Debian with svg (for now?)
        my $im  = Image::Magick->new;
        $im->BlobToImage($asset->slurp);

        # Create the thumbnail
133
134
135
136
137
        if ($thumb eq '') {
            $im->Resize(geometry => 'x'.$c->config('thumbnail_size'));
        } else {
            $im->Resize(geometry => $thumb);
        }
Luc Didry's avatar
Luc Didry committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

        # Replace the asset with the thumbnail
        $asset = Mojo::Asset::Memory->new->add_chunk($im->ImageToBlob());
    }

    $c->res->content->asset($asset);
    $headers->add('Content-Length' => $asset->size);

    return $c->rendered(200);
}

sub _ip {
    my $c  = shift;
    my $ip_only = shift || 0;

    my $proxy = $c->req->headers->header('X-Forwarded-For');

    my $ip = ($proxy) ? $proxy : $c->tx->remote_address;

    my $remote_port = (defined($c->req->headers->header('X-Remote-Port'))) ? $c->req->headers->header('X-Remote-Port') : $c->tx->remote_port;

    return ($ip_only) ? $ip : "$ip remote port:$remote_port";
}

sub _provisioning {
    my $c = shift;

    # Create some short patterns for provisioning
    my $img = Lutim::DB::Image->new(app => $c->app);
Luc Didry's avatar
Luc Didry committed
167
168
    if ($img->count_empty < $c->app->config('provisioning')) {
        for (my $i = 0; $i < $c->app->config('provis_step'); $i++) {
Luc Didry's avatar
Luc Didry committed
169
170
            my $short;
            do {
Luc Didry's avatar
Luc Didry committed
171
                $short = $c->shortener($c->app->config('length'));
Luc Didry's avatar
Luc Didry committed
172
173
174
175
176
177
178
            } while ($img->count_short($short) || $short eq 'about' || $short eq 'stats' || $short eq 'd' || $short eq 'm' || $short eq 'gallery' || $short eq 'zip' || $short eq 'infos');

            $img->short($short)
                ->counter(0)
                ->enabled(1)
                ->delete_at_first_view(0)
                ->delete_at_day(0)
Luc Didry's avatar
Luc Didry committed
179
                ->mod_token($c->shortener($c->app->config('token_length')))
Luc Didry's avatar
Luc Didry committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                ->write;

            $img = Lutim::DB::Image->new(app => $c->app);
        }
    }
}

sub _shortener {
    my $c      = shift;
    my $length = shift;

    my @chars  = ('a'..'z','A'..'Z','0'..'9');
    my $result = '';
    foreach (1..$length) {
        $result .= $chars[entropy_source->get_int(scalar(@chars))];
    }
    return $result;
}

sub _stop_upload {
    my $c = shift;

    if (-f 'stop-upload' || -f 'stop-upload.manual') {
        $c->stash(
Luc Didry's avatar
Luc Didry committed
204
            stop_upload => $c->l('Uploading is currently disabled, please try later or contact the administrator (%1).', $c->app->config('contact'))
Luc Didry's avatar
Luc Didry committed
205
206
207
208
209
210
211
212
213
        );
        return 1;
    }
    return 0;
}

sub _max_delay {
    my $c = shift;

Luc Didry's avatar
Luc Didry committed
214
    return $c->app->config('max_delay') if ($c->app->config('max_delay') >= 0);
Luc Didry's avatar
Luc Didry committed
215
216
217
218
219
220
221
222

    warn "max_delay set to a negative value. Default to 0.";
    return 0;
}

sub _default_delay {
    my $c = shift;

Luc Didry's avatar
Luc Didry committed
223
    return $c->app->config('default_delay') if ($c->app->config('default_delay') >= 0);
Luc Didry's avatar
Luc Didry committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

    warn "default_delay set to a negative value. Default to 0.";
    return 0;
}

sub _is_selected {
    my $c   = shift;
    my $num = shift;

    return ($num == $c->default_delay) ? 'selected="selected"' : '';
}

sub _crypt {
    my $c        = shift;
    my $upload   = shift;
    my $filename = shift;

    my $key   = $c->shortener($c->config('crypto_key_length'));
242
    my $iv    = $c->shortener(8);
Luc Didry's avatar
Luc Didry committed
243
244
245
246
247

    my $cipher = Crypt::CBC->new(
        -key    => $key,
        -cipher => 'Blowfish',
        -header => 'none',
248
        -iv     => $iv
Luc Didry's avatar
Luc Didry committed
249
250
251
252
253
254
255
256
257
258
259
260
261
    );

    $cipher->start('encrypting');

    my $crypt_asset = Mojo::Asset::File->new;

    $crypt_asset->add_chunk($cipher->crypt($upload->slurp));
    $crypt_asset->add_chunk($cipher->finish);

    my $crypt_upload = Mojo::Upload->new;
    $crypt_upload->filename($filename);
    $crypt_upload->asset($crypt_asset);

262
    return ($crypt_upload, $key, $iv);
Luc Didry's avatar
Luc Didry committed
263
264
265
266
267
268
}

sub _decrypt {
    my $c    = shift;
    my $key  = shift;
    my $file = shift;
269
270
    my $iv   = shift;
    $iv = 'dupajasi' unless $iv;
Luc Didry's avatar
Luc Didry committed
271
272
273
274
275

    my $cipher = Crypt::CBC->new(
        -key    => $key,
        -cipher => 'Blowfish',
        -header => 'none',
276
        -iv     => $iv
Luc Didry's avatar
Luc Didry committed
277
278
279
280
281
282
283
284
    );

    $cipher->start('decrypting');

    my $decrypt_asset = Mojo::Asset::File->new;

    open(my $f, "<",$file) or die "Unable to read encrypted file: $!";
    binmode $f;
Luc Didry's avatar
Luc Didry committed
285
    while (read($f, my $buffer, 1024)) {
Luc Didry's avatar
Luc Didry committed
286
287
288
289
          $decrypt_asset->add_chunk($cipher->crypt($buffer));
    }
    $decrypt_asset->add_chunk($cipher->finish) ;

Luc Didry's avatar
Luc Didry committed
290
    return $decrypt_asset->slurp;
Luc Didry's avatar
Luc Didry committed
291
292
293
294
295
}

sub _delete_image {
    my $c   = shift;
    my $img = shift;
Luc Didry's avatar
Luc Didry committed
296
297
298
    if ($c->app->{images_cache}) {
        $c->app->{images_cache}->remove($img->short);
    }
Luc Didry's avatar
Luc Didry committed
299
300
301
    unlink $img->path or warn "Could not unlink ".$img->path.": $!";
    $img->disable();
}
Luc Didry's avatar
Luc Didry committed
302
303

1;