Functional :)

This commit is contained in:
Luc Didry
2014-02-14 00:59:02 +01:00
parent d144db9310
commit 283642e36f
32 changed files with 5103 additions and 39 deletions
+248 -7
View File
@@ -1,18 +1,259 @@
package Lutim;
use Mojo::Base 'Mojolicious';
use LutimModel;
use MIME::Types 'by_suffix';
use Mojo::Util qw(quote);
use Mojo::JSON;;
use Digest::file qw(digest_file_hex);
# This method will run once at server start
sub startup {
my $self = shift;
my $self = shift;
# Documentation browser under "/perldoc"
$self->plugin('PODRenderer');
$self->plugin('I18N');
# Router
my $r = $self->routes;
my $config = $self->plugin('Config');
# Normal route to controller
$r->get('/')->to('example#welcome');
# Default values
$config->{provisionning} = 100 unless (defined($config->{provisionning}));
$config->{provis_step} = 5 unless (defined($config->{provis_step}));
$config->{length} = 8 unless (defined($config->{length}));
$self->secrets($config->{secrets});
$self->helper(
render_file => sub {
my $c = shift;
my ($filename, $path, $mediatype, $dl) = @_;
$filename = quote($filename);
my $asset;
unless ( -f $path && -r _ ) {
$c->app->log->error("Cannot read file [$path]. error [$!]");
$c->flash(
msg => $c->l('image_not_found')
);
return 500;
}
$asset = Mojo::Asset::File->new(path => $path);
my $headers = Mojo::Headers->new();
$headers->add('Content-Type' => $mediatype.';name='.$filename);
$headers->add('Content-Disposition' => $dl.';filename='.$filename);
$headers->add('Content-Length' => $asset->size);
$c->res->content->headers($headers);
$c->res->content->asset($asset);
return $c->rendered(200);
}
);
$self->helper(
provisionning => sub {
my $c = shift;
# Create some short patterns for provisionning
if (LutimModel::Lutim->count('WHERE path IS NULL') < $c->config->{provisionning}) {
for (my $i = 0; $i < $c->config->{provis_step}; $i++) {
if (LutimModel->begin) {
my $short;
do {
$short= $c->shortener($c->config->{length});
} while (LutimModel::Lutim->count('WHERE short = ?', $short));
LutimModel::Lutim->create(
short => $short,
counter => 0,
enabled => 1,
delete_at_first_view => 0,
delete_at_day => 0
);
LutimModel->commit;
}
}
}
}
);
$self->helper(
shortener => sub {
my $c = shift;
my $length = shift;
my @chars = ('a'..'z','A'..'Z','0'..'9');
my $result = '';
foreach (1..$length) {
$result .= $chars[rand scalar(@chars)];
}
return $result;
}
);
$self->defaults(layout => 'default');
$self->provisionning();
# Router
my $r = $self->routes;
$r->get('/' => sub {
my $c = shift;
$c->render( template => 'index');
# Check provisionning
$c->on(finish => sub {
shift->provisionning();
}
);
}
)->name('index');
$r->post('/' => sub {
my $c = shift;
my $upload = $c->param('file');
my ($mediatype, $encoding) = by_suffix $upload->filename;
my ($msg, $short);
# Check file type
if (index($mediatype, 'image') >= 0) {
# Create directory if needed
mkdir('files', 0700) unless (-d 'files');
if(LutimModel->begin) {
my @records = LutimModel::Lutim->select('WHERE path IS NULL LIMIT 1');
if (scalar(@records)) {
# Save file and create record
my $filename = $upload->filename;
my $ext = ($filename =~ m/([^.]+)$/)[0];
my $path = 'files/'.$records[0]->short.'.'.$ext;
$upload->move_to($path);
$records[0]->update(
path => $path,
filename => $filename,
mediatype => $mediatype,
footprint => digest_file_hex($path, 'SHA-512'),
enabled => 1,
delete_at_day => ($c->param('delete-day')) ? 1 : 0,
delete_at_first_view => ($c->param('first-view')) ? 1 : 0,
created_at => time(),
created_by => $c->tx->remote_address
);
# Log image creation
$c->app->log->info('[CREATION] '.$c->tx->remote_address.' pushed '.$filename.' (path: '.$path.')');
# Give url to user
$short = $records[0]->short;
} else {
# Houston, we have a problem
$msg = $c->l('no_more_short', $c->config->{contact});
}
}
LutimModel->commit;
} else {
$msg = $c->l('no_valid_file', $upload->filename);
}
# Check provisionning
$c->on(finish => sub {
shift->provisionning();
}
);
if (defined($c->param('format')) && $c->param('format') eq 'json') {
if (defined($short)) {
$msg = {
filename => $upload->filename,
short => $short
};
} else {
$msg = {
filename => $upload->filename,
msg => $msg
};
}
$c->render(
json => {
success => (defined($short)) ? Mojo::JSON->true : Mojo::JSON->false,
msg => $msg
}
);
} else {
$c->flash(msg => $msg) if (defined($msg));
$c->flash(short => $short) if (defined($short));
$c->flash(filename => $upload->filename);
$c->redirect_to('/');
}
}
)->name('add');
$r->get('/:short' => sub {
my $c = shift;
my $short = $c->param('short');
my $dl = (defined($c->param('dl'))) ? 'attachment' : 'inline';
my @images = LutimModel::Lutim->select('WHERE short = ? AND ENABLED = 1 AND path IS NOT NULL', $short);
if (scalar(@images)) {
if($images[0]->delete_at_day && $images[0]->created_at + 86400 <= time()) {
# Log deletion
$c->app->log->info('[DELETION] '.$c->tx->remote_address.' tried to view '.$images[0]->filename.' but it has been removed by expiration (path: '.$images[0]->path.')');
# Delete image
unlink $images[0]->path();
$images[0]->update(enabled => 0);
# Warn user
$c->flash(
msg => $c->l('image_not_found')
);
return $c->redirect_to('/');
}
if($c->render_file($images[0]->filename, $images[0]->path, $images[0]->mediatype, $dl) != 500) {
# Update counter and check provisionning
$c->on(finish => sub {
# Log access
$c->app->log->info('[VIEW] '.$c->tx->remote_address.' viewed '.$images[0]->filename.' (path: '.$images[0]->path.')');
# Update record
my $counter = $images[0]->counter + 1;
$images[0]->update(counter => $counter);
$images[0]->update(last_access_at => time());
$images[0]->update(last_access_by => $c->tx->remote_address);
# Delete image if needed
if ($images[0]->delete_at_first_view) {
# Log deletion
$c->app->log->info('[DELETION] '.$c->tx->remote_address.' made '.$images[0]->filename.' removed (path: '.$images[0]->path.')');
# Delete image
unlink $images[0]->path();
$images[0]->update(enabled => 0);
}
shift->provisionning();
});
}
} else {
@images = LutimModel::Lutim->select('WHERE short = ? AND ENABLED = 0 AND path IS NOT NULL', $short);
if (scalar(@images)) {
# Log access try
$c->app->log->info('[NOT FOUND] '.$c->tx->remote_address.' tried to view '.$short.' but it does\'nt exist.');
# Warn user
$c->flash(
msg => $c->l('image_not_found')
);
return $c->redirect_to('/');
} else {
# Image never existed
$c->render_not_found;
}
}
})->name('short');
}
1;
-12
View File
@@ -1,12 +0,0 @@
package Lutim::Example;
use Mojo::Base 'Mojolicious::Controller';
# This action will render a template
sub welcome {
my $self = shift;
# Render template "example/welcome.html.ep" with message
$self->render(msg => 'Welcome to the Mojolicious real-time web framework!');
}
1;
+48
View File
@@ -0,0 +1,48 @@
package Lutim::I18N::en;
use Mojo::Base 'Lutim::I18N';
my $inf_body = <<EOF;
<h4>What is LUTIm?</h4>
<p>LUTIm is a free (as in free beer) and anonymous image hosting service. It's also the name of the free (as in free speech) software which provides this service.</p>
<p>The images you post on LUTIm can be stored indefinitely or be deleted at first view or after 24 hours.</p>
<h4>How does it work?</h4>
<p>Drag and drop an image in the appropriate area or use the traditional way to send files and LUTIm will provide you two URLs. One to view the image, the other to directly download it.</p>
<p>You can, optionally, request that the image(s) posted on LUTIm to be deleted at first view (or download) or after 24 hours.</p>
<h4>Is it really free (as in free beer)?</h4>
<p>Yes, it is! On the other side, if you want to support the developer, you can do it via <a href="https://flattr.com/submit/auto?user_id=_SKy_&url=[_1]&title=LUTIm&category=software">Flattr</a> or with <a href="bitcoin:1K3n4MXNRSMHk28oTfXEvDunWFthePvd8v?label=lutim">BitCoin</a>.</p>
<h4>Is it really anonymous?</h4>
<p>Yes, it is! On the other side, for legal reasons, your IP address will be stored when you send or view an image. Don't panic, it is the case of all sites on which you go!</p>
<p>The log files containing the IP address of image viewers are retained for one year while the IP addresse of the image's sender, as the address of the last viewer are permanently retained.</p>
<p>If the files are deleted if you ask it while posting it, their SHA512 footprint are retained.</p>
<h4>How to report an image?</h4>
<p>Please contact the administrator: [_2]</p>
<h4>How do you pronounce LUTIm?</h4>
<p>Juste like you pronounce the french word <a href="https://fr.wikipedia.org/wiki/Lutin">lutin</a> (/ly.tɛ̃/).</p>
<h4>What about the software which provides the service?</h4>
<p>The LUTIm software is a <a href="http://en.wikipedia.org/wiki/Free_software">free software</a>, which allows you to download and install it on you own server. Have a look at the <a href="https://www.gnu.org/licenses/agpl-3.0.html">AGPL</a> to see what you can do.</p>
<p>For more details, see the <a href="https://github.com/ldidry/lutim">Github</a> page of the project.</p>
EOF
our %Lexicon = (
'license' => 'License:',
'fork-me' => 'Fork me on Github !',
'share-twitter' => 'Share on Twitter',
'informations' => 'Informations',
'informations-body' => $inf_body,
'view-link' => 'View link:',
'download-link' => 'Download link:',
'some-bad' => 'Something bad happened',
'delete-first' => 'Delete at first view?',
'delete-day' => 'Delete after 24 hours?',
'upload_image' => 'Send an image',
'image-only' => 'Only images are allowed',
'go' => 'Let\'s go!',
'drag-n-drop' => 'Drag & drop images here',
'or' => '-or-',
'file-browser' => 'Click to open the file browser',
'image_not_found' => 'Unable to find the image',
'no_more_short' => 'There is no more available URL. Retry or contact the administrator. [_1]',
'no_valid_file' => 'The file [_1] is not an image.',
);
1;
+48
View File
@@ -0,0 +1,48 @@
package Lutim::I18N::fr;
use Mojo::Base 'Lutim::I18N';
my $inf_body = <<EOF;
<h4>Quest-ce que LUTIm ?</h4>
<p>LUTIm est un service gratuit et anonyme dhébergement dimages. Il sagit aussi du nom du logiciel (libre) qui fournit ce service.</p>
<p>Les images déposées sur LUTIm peuvent être stockées indéfiniment, ou seffacer dès le premier affichage ou au bout de 24h.</p>
<h4>Comment ça marche ?</h4>
<p>Faites glisser des images dans la zone prévue à cette effet ou sélectionnez un fichier de façon classique et LUTIm vous fournira deux URLs en retour. Une pour afficher limage, lautre pour la télécharger directement.</p>
<p>Vous pouvez, de façon optionnelle, demander à ce que la ou les images déposées sur LUTIm soient supprimées après leur premier affichage (ou téléchargement) ou au bout de 24 heures.</p>
<h4>Cest vraiment gratuit ?</h4>
<p>Oui, ça lest ! Par contre, si vous avez envie de soutenir le développeur, vous pouvez faire un microdon avec <a href="https://flattr.com/submit/auto?user_id=_SKy_&url=[_1]&title=LUTIm&category=software">Flattr</a> ou en <a href="bitcoin:1K3n4MXNRSMHk28oTfXEvDunWFthePvd8v?label=lutim">BitCoin</a>.</p>
<h4>Cest vraiment anonyme ?</h4>
<p>Oui, ça lest ! Par contre, pour des raisons légales, votre adresse IP sera enregistrée lorsque vous enverrez ou consulterez une image.Ne vous affolez pas, cest de toute façon le cas sur tous les sites sur lesquels vous surfez !</p>
<p>Les journaux systèmes contenant ladresse IP des visiteurs dune image sont conservés un an, tandis que lIP de la personne ayant déposé limage et celle du dernier visiteur de limage sont stockées de manière définitive.</p>
<p>Si les fichiers sont bien supprimés si vous en avez exprimé le choix, leur empreinte SHA512 est toutefois conservée.</p>
<h4>Comment peut-on faire pour signaler une image ?</h4>
<p>Veuillez contacter ladministrateur : [_2]</p>
<h4>Comment doit-on prononcer LUTIm ?</h4>
<p>Comme on prononce <a href="https://fr.wikipedia.org/wiki/Lutin">lutin</a> !</p>
<h4>Et à propos du logiciel qui fournit le service ?</h4>
<p>Le logiciel LUTIm est un <a href="https://fr.wikipedia.org/wiki/Logiciel_libre">logiciel libre</a>, ce qui vous permet de le télécharger et de linstaller sur votre propre serveur. Jetez un coup d’œil à l<a href="https://www.gnu.org/licenses/agpl-3.0.html">AGPL</a> pour voir quels sont vos droits.</p>
<p>Pour plus de détails, consultez la page <a href="https://github.com/ldidry/lutim">Github</a> du projet.</p>
EOF
our %Lexicon = (
'license' => 'Licence :',
'fork-me' => 'Fork me on Github',
'share-twitter' => 'Partager sur Twitter',
'informations' => 'Informations',
'informations-body' => $inf_body,
'view-link' => 'Lien d\'affichage :',
'download-link' => 'Lien de téléchargement :',
'some-bad' => 'Un problème est survenu',
'delete-first' => 'Supprimer au premier accès ?',
'delete-day' => 'Supprimer après 24 heures ?',
'upload_image' => 'Envoyez une image',
'image-only' => 'Seules les images sont acceptées',
'go' => 'Allons-y !',
'drag-n-drop' => 'Déposez vos images ici',
'or' => '-ou-',
'file-browser' => 'Cliquez pour utiliser le navigateur de fichier',
'image_not_found' => 'Impossible de trouver l\'image',
'no_more_short' => 'Il n\'y a plus d\'URL disponible. Veuillez réessayer ou contactez l\'administrateur. [_1].',
'no_valid_file' => 'Le fichier [_1] n\'est pas une image.'
);
1;
+29
View File
@@ -0,0 +1,29 @@
package LutimModel;
# Create database
use ORLite {
file => 'lutim.db',
unicode => 1,
create => sub {
my $dbh = shift;
$dbh->do(
'CREATE TABLE lutim (
short TEXT PRIMARY KEY,
path TEXT,
footprint TEXT,
enabled INTEGER,
mediatype TEXT,
filename TEXT,
counter INTEGER,
delete_at_first_view INTEGER,
delete_at_day INTEGER,
created_at INTEGER,
created_by TEXT,
last_access_at INTEGER,
last_access_by INTEGER)'
);
return 1;
}
};
1;