From 7744d995bb10f74815f62b0232229a45ede268ee Mon Sep 17 00:00:00 2001 From: Alexandre Morignot <amorignot@meilleursagents.com> Date: Fri, 14 Jul 2023 20:02:25 +0200 Subject: [PATCH] chore: apply perltidy --- PlayBot.pl | 1 + PlayBot/commands/broken.pm | 59 +- PlayBot/commands/conf.pm | 77 ++- PlayBot/commands/fav.pm | 17 +- PlayBot/commands/get.pm | 86 +-- PlayBot/commands/get/query.pm | 126 ++--- PlayBot/commands/later.pm | 21 +- PlayBot/commands/parser.pm | 202 ++++--- PlayBot/commands/stats.pm | 16 +- PlayBot/commands/tag.pm | 23 +- PlayBot/sessions/downloader.pm | 21 +- PlayBot/sessions/downloader/ddl.pm | 133 +++-- PlayBot/sessions/facebook.pm | 13 +- PlayBot/sessions/irc.pm | 321 +++++------ PlayBot/sessions/irc/later.pm | 7 +- PlayBot/sites.pm | 168 +++--- PlayBot/sites/dailymotion.pm | 14 +- PlayBot/sites/deezer.pm | 36 +- PlayBot/sites/facebook.pm | 38 +- PlayBot/sites/mixcloud.pm | 37 +- PlayBot/sites/soundcloud.pm | 173 +++--- PlayBot/sites/spotify.pm | 78 +-- PlayBot/sites/youtube.pm | 114 ++-- PlayBot/sites/zippy.pm | 93 ++-- PlayBot/utils/Logging.pm | 831 +++++++++++++---------------- PlayBot/utils/db.pm | 28 +- PlayBot/utils/db/chan.pm | 81 ++- PlayBot/utils/db/get.pm | 167 +++--- PlayBot/utils/db/stats.pm | 68 ++- PlayBot/utils/id.pm | 52 +- PlayBot/utils/print.pm | 115 ++-- tools/readjson.pl | 11 +- tools/readmail.pl | 44 +- 33 files changed, 1599 insertions(+), 1672 deletions(-) diff --git a/PlayBot.pl b/PlayBot.pl index 5dc1d61..392d822 100755 --- a/PlayBot.pl +++ b/PlayBot.pl @@ -6,6 +6,7 @@ use utf8; use POE; use PlayBot::sessions::irc; + #use PlayBot::sessions::facebook; use PlayBot::sessions::downloader; diff --git a/PlayBot/commands/broken.pm b/PlayBot/commands/broken.pm index 0514662..fca45b6 100644 --- a/PlayBot/commands/broken.pm +++ b/PlayBot/commands/broken.pm @@ -11,80 +11,69 @@ use PlayBot::utils::print; use Try::Tiny; sub exec { - my ($chan, $id) = @_; + my ( $chan, $id ) = @_; my $dbh = PlayBot::utils::db::main_session; my $query = PlayBot::commands::get::query->new( - chan => $chan, - query => $id, + chan => $chan, + query => $id, ); my $db_query = PlayBot::utils::db::get->new(); - my $content = $db_query->get($query); + my $content = $db_query->get($query); - die("La cuillère n'existe pas\n") if (not $content); + die("La cuillère n'existe pas\n") if ( not $content ); - if (not $content->{external_id}) - { + if ( not $content->{external_id} ) { return "Cette feature n'est pas encore disponible pour ce contenu"; } - my $content_r; - try - { - my $site = 'PlayBot::sites::'.$content->{site}; + try { + my $site = 'PlayBot::sites::' . $content->{site}; eval "require $site"; - my %h = $site->get($content->{external_id}); + my %h = $site->get( $content->{external_id} ); $content_r = \%h; } - catch - { + catch { # mark as broken # TODO: be more subtil - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' UPDATE playbot SET broken = 1 WHERE type = ? AND external_id = ? - '); - $sth->execute($content->{site}, $content->{external_id}); + ' ); + $sth->execute( $content->{site}, $content->{external_id} ); $dbh->commit; die "Monde de merde\n"; }; - try - { - foreach my $k (keys %$content_r) - { - die if($content_r->{$k} ne $content->{$k}); + try { + foreach my $k ( keys %$content_r ) { + die if ( $content_r->{$k} ne $content->{$k} ); } } - catch - { + catch { # the content needs an update - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' UPDATE playbot SET sender = ?, title = ?, duration = ?, url = ? WHERE type = ? AND external_id = ? - '); + ' ); $sth->execute( - $content_r->{author}, - $content_r->{title}, - $content_r->{duration}, - $content_r->{url}, - $content_r->{site}, - $content_r->{external_id}, + $content_r->{author}, $content_r->{title}, + $content_r->{duration}, $content_r->{url}, + $content_r->{site}, $content_r->{external_id}, ); $dbh->commit; my $msg = PlayBot::utils::print::print($content); - die"Ça, c’est bon, c’est réparé\n$msg\n"; + die "Ça, c’est bon, c’est réparé\n$msg\n"; }; - + return "http://chezmoicamarche.org/"; } - 1; diff --git a/PlayBot/commands/conf.pm b/PlayBot/commands/conf.pm index 9008545..340e706 100644 --- a/PlayBot/commands/conf.pm +++ b/PlayBot/commands/conf.pm @@ -4,7 +4,10 @@ use strict; use warnings; use utf8; -use Module::Pluggable sub_name => 'sites', search_path => ['PlayBot::sites'], require => 1; +use Module::Pluggable + sub_name => 'sites', + search_path => ['PlayBot::sites'], + require => 1; use PlayBot::utils::print; use PlayBot::utils::db; @@ -12,65 +15,53 @@ use PlayBot::utils::db::chan; our $irc; -sub exec -{ - my ($chan, $nick, $cmd, @args) = @_; - print "$chan, $nick, $cmd, ".join('+', @args)."\n"; +sub exec { + my ( $chan, $nick, $cmd, @args ) = @_; + print "$chan, $nick, $cmd, " . join( '+', @args ) . "\n"; my $msg = 'done'; - if (not $irc->is_channel_operator($chan, $nick)) - { - $irc->yield(privmsg => $chan => "C'est non."); + if ( not $irc->is_channel_operator( $chan, $nick ) ) { + $irc->yield( privmsg => $chan => "C'est non." ); return; } - if ($cmd eq 'list') - { + if ( $cmd eq 'list' ) { my $sites = list($chan); my @list; - foreach (keys %$sites) - { - $_ .= '*' if ($sites->{$_}); + foreach ( keys %$sites ) { + $_ .= '*' if ( $sites->{$_} ); push @list, $_; } - $msg = join(' ', @list); + $msg = join( ' ', @list ); } - elsif ($cmd eq 'add') - { - add($chan, @args); + elsif ( $cmd eq 'add' ) { + add( $chan, @args ); } - elsif ($cmd eq 'remove') - { - remove($chan, @args); + elsif ( $cmd eq 'remove' ) { + remove( $chan, @args ); } - else - { + else { die; } - $irc->yield(privmsg => $chan => $msg); + $irc->yield( privmsg => $chan => $msg ); } - -sub list -{ +sub list { my $chan = shift; my $chan_conf = PlayBot::utils::db::chan->new($chan); - my $sites = {}; + my $sites = {}; - foreach my $site (__PACKAGE__->sites) - { - $site = (split(/::/, $site))[-1]; - if (grep { $site eq $_ } @{ $chan_conf->sites }) - { + foreach my $site ( __PACKAGE__->sites ) { + $site = ( split( /::/, $site ) )[-1]; + if ( grep { $site eq $_ } @{ $chan_conf->sites } ) { $sites->{$site} = 1; } - else - { + else { $sites->{$site} = 0; } } @@ -78,26 +69,20 @@ sub list return $sites; } - -sub add -{ - my ($chan, @sites) = @_; +sub add { + my ( $chan, @sites ) = @_; my $chan_conf = PlayBot::utils::db::chan->new($chan); - foreach (@sites) - { + foreach (@sites) { $chan_conf->add_site($_); } } - -sub remove -{ - my ($chan, @sites) = @_; +sub remove { + my ( $chan, @sites ) = @_; my $chan_conf = PlayBot::utils::db::chan->new($chan); - foreach (@sites) - { + foreach (@sites) { $chan_conf->remove_site($_); } } diff --git a/PlayBot/commands/fav.pm b/PlayBot/commands/fav.pm index 08a670d..a73b3e9 100644 --- a/PlayBot/commands/fav.pm +++ b/PlayBot/commands/fav.pm @@ -9,19 +9,22 @@ our $log; our $irc; sub exec { - my ($nick, $id) = @_; + my ( $nick, $id ) = @_; my $sth = $dbh->prepare('SELECT user FROM playbot_codes WHERE nick = ?'); $sth->execute($nick) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); - if (!$sth->rows) { - $irc->yield(privmsg => $nick => "Ce nick n'est associé à aucun login arise. Va sur http://nightiies.iiens.net/links/fav pour obtenir ton code personel."); + if ( !$sth->rows ) { + $irc->yield( privmsg => $nick => +"Ce nick n'est associé à aucun login arise. Va sur http://nightiies.iiens.net/links/fav pour obtenir ton code personel." + ); } else { - my $sth2 = $dbh->prepare('INSERT INTO playbot_fav (id, user) VALUES (?, ?)'); - $sth2->execute($id, $sth->fetch->[0]) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + my $sth2 = + $dbh->prepare('INSERT INTO playbot_fav (id, user) VALUES (?, ?)'); + $sth2->execute( $id, $sth->fetch->[0] ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); } } diff --git a/PlayBot/commands/get.pm b/PlayBot/commands/get.pm index 014d9a8..3cf4ff3 100644 --- a/PlayBot/commands/get.pm +++ b/PlayBot/commands/get.pm @@ -14,75 +14,82 @@ our $irc; our $log; sub exec { - my ($fts, $chan, $msg, $chan_src) = @_; + my ( $fts, $chan, $msg, $chan_src ) = @_; my $query = PlayBot::commands::get::query->new( - chan => $chan, - query => ($msg) ? $msg : '', - fts => $fts, + chan => $chan, + query => ($msg) ? $msg : '', + fts => $fts, ); my $db_query = PlayBot::utils::db::get->new(); - my $rows = $db_query->get_rows($query); + my $rows = $db_query->get_rows($query); - if (scalar @{$query->tags} == 0 - and scalar @{$query->words} > 0 - and $query->id == -1 - and $rows > 10 - and not $query->force) + if ( scalar @{ $query->tags } == 0 + and scalar @{ $query->words } > 0 + and $query->id == -1 + and $rows > 10 + and not $query->force ) { my $search_name = $db_query->make_view($query); - $irc->yield(privmsg => $chan => "trop de résultats ($rows), utilise -f pour forcer la recherche ou va voir ici : http://nightiies.iiens.net/links/search/$search_name"); + $irc->yield( privmsg => $chan => +"trop de résultats ($rows), utilise -f pour forcer la recherche ou va voir ici : http://nightiies.iiens.net/links/search/$search_name" + ); return; } my $content = $db_query->get($query); - if (!$content) { - if ($rows > 0) { + if ( !$content ) { + if ( $rows > 0 ) { + # the request was already executed, there is nothing more - $irc->yield(privmsg => $chan => "Tu tournes en rond, Jack !"); + $irc->yield( privmsg => $chan => "Tu tournes en rond, Jack !" ); } - elsif (@{$query->words} or @{$query->tags}) { + elsif ( @{ $query->words } or @{ $query->tags } ) { $msg = "Je n'ai rien dans ce registre."; - if (not $query->is_global) { + if ( not $query->is_global ) { + # we check is there is result with global my $q = PlayBot::commands::get::query->new( - chan => $query->chan, - query => $query->query . ' -a', - fts => $fts, + chan => $query->chan, + query => $query->query . ' -a', + fts => $fts, ); my $rows = $db_query->get_rows($q); - if ($rows > 0) { + if ( $rows > 0 ) { $msg .= ' ' . $rows . ' résultat'; - $msg .= 's' if ($rows > 1); + $msg .= 's' if ( $rows > 1 ); $msg .= ' trouvé'; - $msg .= 's' if ($rows > 1); + $msg .= 's' if ( $rows > 1 ); $msg .= ' avec une recherche globale.'; } } - $irc->yield(privmsg => $chan => $msg); + $irc->yield( privmsg => $chan => $msg ); } else { - $irc->yield(privmsg => $chan => "Poste d'abord du contenu, n00b."); + $irc->yield( + privmsg => $chan => "Poste d'abord du contenu, n00b." ); } - return + return; } my $dbh = PlayBot::utils::db::main_session(); - my $sth = $dbh->prepare("select tag + my $sth = $dbh->prepare( + "select tag from playbot_tags where id = ? - "); - $sth->execute($content->{id}); + " + ); + $sth->execute( $content->{id} ); my @tags; - while (my $data = $sth->fetch) { + while ( my $data = $sth->fetch ) { my $tag = $data->[0]; $tag =~ s/([a-zA-Z0-9_-]+)/#$1/; push @tags, $tag; @@ -93,35 +100,34 @@ sub exec { my $irc_msg = PlayBot::utils::print::print($content); # if in query - if ($chan !~ /^#/) { + if ( $chan !~ /^#/ ) { $irc_msg .= ' [' . $chan_src . ']'; } else { $irc_msg .= ' [' . $rows . ' résultat'; - $irc_msg .= 's' if ($rows > 1); + $irc_msg .= 's' if ( $rows > 1 ); $irc_msg .= ']'; } - $irc->yield(privmsg => $chan => $irc_msg); + $irc->yield( privmsg => $chan => $irc_msg ); # BRUTALE - if ($content->{'id'} eq 9320) { - $irc->yield(privmsg => $chan => 'BRUUUTALEEEEEEEEEEEEEE'); + if ( $content->{'id'} eq 9320 ) { + $irc->yield( privmsg => $chan => 'BRUUUTALEEEEEEEEEEEEEE' ); } # we save the get like a post - $sth = $dbh->prepare(' + $sth = $dbh->prepare( ' INSERT INTO playbot_chan (content, chan, sender_irc) - VALUES (?,?,?)'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); + VALUES (?,?,?)' ); + $log->error("Couldn't prepare querie; aborting") unless ( defined $sth ); - $sth->execute($content->{id}, $chan, "PlayBot") - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + $sth->execute( $content->{id}, $chan, "PlayBot" ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); $dbh->commit(); return $content->{id}; } - 1; diff --git a/PlayBot/commands/get/query.pm b/PlayBot/commands/get/query.pm index 4bec96a..8c02f0f 100644 --- a/PlayBot/commands/get/query.pm +++ b/PlayBot/commands/get/query.pm @@ -9,78 +9,78 @@ use overload '~~' => \&_equals; use Scalar::Util qw(looks_like_number); has 'query' => ( - is => 'ro', - isa => 'Str', - required => 1 + is => 'ro', + isa => 'Str', + required => 1 ); has 'chan' => ( - is => 'ro', - isa => 'Str', - required => 1 + is => 'ro', + isa => 'Str', + required => 1 ); has 'fts' => ( - is => 'ro', - isa => 'Bool', - required => 1, + is => 'ro', + isa => 'Bool', + required => 1, ); has 'is_global' => ( - is => 'ro', - isa => 'Bool', - lazy => 1, - builder => '_build_is_global', - init_arg => undef + is => 'ro', + isa => 'Bool', + lazy => 1, + builder => '_build_is_global', + init_arg => undef ); has 'force' => ( - is => 'ro', - isa => 'Bool', - lazy => 1, - builder => '_build_force', - init_arg => undef + is => 'ro', + isa => 'Bool', + lazy => 1, + builder => '_build_force', + init_arg => undef ); has 'tags' => ( - is => 'ro', - isa => 'ArrayRef[Str]', - lazy => 1, - builder => '_build_tags', - init_arg => undef + is => 'ro', + isa => 'ArrayRef[Str]', + lazy => 1, + builder => '_build_tags', + init_arg => undef ); has 'words' => ( - is => 'ro', - isa => 'ArrayRef[Str]', - lazy => 1, - builder => '_build_words', - init_arg => undef + is => 'ro', + isa => 'ArrayRef[Str]', + lazy => 1, + builder => '_build_words', + init_arg => undef ); has 'id' => ( - is => 'ro', - isa => 'Int', - lazy => 1, - builder => '_build_id', - init_arg => undef + is => 'ro', + isa => 'Int', + lazy => 1, + builder => '_build_id', + init_arg => undef ); has 'date' => ( - is => 'ro', - isa => 'Int', - lazy => 0, - builder => '_build_date', - init_arg => undef, + is => 'ro', + isa => 'Int', + lazy => 0, + builder => '_build_date', + init_arg => undef, ); - sub _build_is_global { my $self = shift; - if ($self->chan !~ /^#/ || $self->query =~ /(^|\s)-a(ll)?($|\s)/) { + if ( $self->chan !~ /^#/ || $self->query =~ /(^|\s)-a(ll)?($|\s)/ ) { return 1; - } else { + } + else { return 0; } } @@ -88,9 +88,11 @@ sub _build_is_global { sub _build_force { my $self = shift; - if ($self->fts || $self->chan !~ /^#/ || $self->query =~ /(^|\s)-f($|\s)/) { + if ( $self->fts || $self->chan !~ /^#/ || $self->query =~ /(^|\s)-f($|\s)/ ) + { return 1; - } else { + } + else { return 0; } } @@ -100,26 +102,27 @@ sub _build_tags { my $query = $self->query; $query =~ s/(^|\s)-a(ll)?($|\s)//; - - return [$query =~ /#([a-zA-Z0-9_-]+)/g]; + + return [ $query =~ /#([a-zA-Z0-9_-]+)/g ]; } sub _build_words { my $self = shift; - + my $query = $self->query; $query =~ s/(^|\s)-a(ll)?($|\s)/ /; $query =~ s/(^|\s)-f($|\s)/ /; - return [$query =~ /(?:^| )([^#\s]+)/g]; + return [ $query =~ /(?:^| )([^#\s]+)/g ]; } sub _build_id { my $self = shift; - - if (looks_like_number($self->words->[0])) { + + if ( looks_like_number( $self->words->[0] ) ) { return $self->words->[0]; - } else { + } + else { return -1; } } @@ -129,20 +132,19 @@ sub _build_date { } sub _equals { - my ($self, $query) = @_; + my ( $self, $query ) = @_; - return 0 unless (ref($self) eq ref($query)); + return 0 unless ( ref($self) eq ref($query) ); - my @tags1 = sort @{$self->tags}; - my @tags2 = sort @{$query->tags}; - my @words1 = sort @{$self->words}; - my @words2 = sort @{$query->words}; + my @tags1 = sort @{ $self->tags }; + my @tags2 = sort @{ $query->tags }; + my @words1 = sort @{ $self->words }; + my @words2 = sort @{ $query->words }; - return ($self->is_global eq $query->is_global - and @tags1 ~~ @tags2 - and @words1 ~~ @words2 - and $self->id eq $query->id - ); + return ( $self->is_global eq $query->is_global + and @tags1 ~~ @tags2 + and @words1 ~~ @words2 + and $self->id eq $query->id ); } 1; diff --git a/PlayBot/commands/later.pm b/PlayBot/commands/later.pm index 5886b62..fe8b3ac 100644 --- a/PlayBot/commands/later.pm +++ b/PlayBot/commands/later.pm @@ -8,20 +8,21 @@ our $dbh; our $log; sub exec { - my ($kernel, $nick, $id, $chan, $time, $unit) = @_; + my ( $kernel, $nick, $id, $chan, $time, $unit ) = @_; - $time = 6 if (!$time); - $time *= ($unit eq 's') ? 1 : ($unit eq 'm') ? 60 : 3600; + $time = 6 if ( !$time ); + $time *= ( $unit eq 's' ) ? 1 : ( $unit eq 'm' ) ? 60 : 3600; - my $sth = $dbh->prepare('INSERT INTO playbot_later (content, nick, date) VALUES (?, ?, ?)'); - unless (defined $sth) { + my $sth = $dbh->prepare( + 'INSERT INTO playbot_later (content, nick, date) VALUES (?, ?, ?)'); + unless ( defined $sth ) { $log->error("Couldn't prepare querie; aborting"); return; - } - $sth->execute($id, $nick, time + $time) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); - - $kernel->delay_set('_later', $time, $nick, $id, $chan); + } + $sth->execute( $id, $nick, time + $time ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); + + $kernel->delay_set( '_later', $time, $nick, $id, $chan ); } 1; diff --git a/PlayBot/commands/parser.pm b/PlayBot/commands/parser.pm index 1d0c917..1f3a381 100644 --- a/PlayBot/commands/parser.pm +++ b/PlayBot/commands/parser.pm @@ -18,86 +18,95 @@ my $lastID; my $irc; my $dbh; -my @insultes = ("Ahahahah ! 23 à 0 !", "C'est la piquette, Jack !", "Tu sais pas jouer, Jack !", "T'es mauvais, Jack !"); +my @insultes = ( + "Ahahahah ! 23 à 0 !", + "C'est la piquette, Jack !", + "Tu sais pas jouer, Jack !", + "T'es mauvais, Jack !" +); # store a chan last command my %command; sub setConf { - my ($ircNew, $dbhNew, $log, $lastIDnew) = @_; + my ( $ircNew, $dbhNew, $log, $lastIDnew ) = @_; - $PlayBot::commands::fav::dbh = $dbhNew; - $PlayBot::commands::tag::dbh = $dbhNew; + $PlayBot::commands::fav::dbh = $dbhNew; + $PlayBot::commands::tag::dbh = $dbhNew; $PlayBot::commands::later::dbh = $dbhNew; - $PlayBot::utils::id::dbh = $dbhNew; + $PlayBot::utils::id::dbh = $dbhNew; - $PlayBot::commands::fav::log = $log; - $PlayBot::commands::tag::log = $log; - $PlayBot::commands::get::log = $log; + $PlayBot::commands::fav::log = $log; + $PlayBot::commands::tag::log = $log; + $PlayBot::commands::get::log = $log; $PlayBot::commands::later::log = $log; - $PlayBot::utils::id::log = $log; + $PlayBot::utils::id::log = $log; - $PlayBot::commands::conf::irc = $ircNew; - $PlayBot::commands::fav::irc = $ircNew; - $PlayBot::commands::get::irc = $ircNew; + $PlayBot::commands::conf::irc = $ircNew; + $PlayBot::commands::fav::irc = $ircNew; + $PlayBot::commands::get::irc = $ircNew; $PlayBot::commands::stats::irc = $ircNew; $lastID = $lastIDnew; - $irc = $ircNew; - $dbh = $dbhNew; + $irc = $ircNew; + $dbh = $dbhNew; } sub exec { - my ($kernel, $user, $chan, $msg) = @_; - my ($nick, $mask) = split(/!/,$user); + my ( $kernel, $user, $chan, $msg ) = @_; + my ( $nick, $mask ) = split( /!/, $user ); - if ($msg eq '!' and $command{$chan}) { + if ( $msg eq '!' and $command{$chan} ) { $msg = $command{$chan}; } - if ($msg =~ /^ *!fav(?: (\S+))? *$/) { + if ( $msg =~ /^ *!fav(?: (\S+))? *$/ ) { my $index = $1; try { - my $id = PlayBot::utils::id::get($chan, $index); - PlayBot::commands::fav::exec($nick, $id) - } catch { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + my $id = PlayBot::utils::id::get( $chan, $index ); + PlayBot::commands::fav::exec( $nick, $id ) } - } - elsif ($msg =~ /^ *!later(?: (\S+))?(?: in (\d+)(h|m|s)?)? *$/) { + catch { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); + } + } + elsif ( $msg =~ /^ *!later(?: (\S+))?(?: in (\d+)(h|m|s)?)? *$/ ) { my $index = $1; - my ($time, $unit) = ($2, $3); + my ( $time, $unit ) = ( $2, $3 ); try { - my $id = PlayBot::utils::id::get($chan, $index); - PlayBot::commands::later::exec($kernel, $nick, $id, $chan, $time, $unit); - } catch { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + my $id = PlayBot::utils::id::get( $chan, $index ); + PlayBot::commands::later::exec( $kernel, $nick, $id, $chan, $time, + $unit ); + } + catch { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); }; - } - elsif ($msg =~ /^( *!tag)(?:( +)(-?\d+))?/) { + } + elsif ( $msg =~ /^( *!tag)(?:( +)(-?\d+))?/ ) { my $index = $3; my $id; my $tags; if ($3) { - $tags = substr $msg, (length $1) + (length $2) + (length $3); + $tags = substr $msg, ( length $1 ) + ( length $2 ) + ( length $3 ); } else { - $tags = substr $msg, (length $1) + (length $2); + $tags = substr $msg, ( length $1 ) + ( length $2 ); } try { - $id = PlayBot::utils::id::get($chan, $index); - PlayBot::commands::tag::exec($id, $tags); - } catch { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + $id = PlayBot::utils::id::get( $chan, $index ); + PlayBot::commands::tag::exec( $id, $tags ); + } + catch { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); }; } - elsif ($msg =~ /^ *!(get|fts)( +.*)?$/) { + elsif ( $msg =~ /^ *!(get|fts)( +.*)?$/ ) { my $query = $2; - my $fts = $1 eq 'fts'; - my @args = ($fts, $chan, $query); + my $fts = $1 eq 'fts'; + my @args = ( $fts, $chan, $query ); my $id = PlayBot::commands::get::exec(@args); @@ -105,59 +114,86 @@ sub exec { $lastID->{$chan} = $id; } } - elsif ($msg =~ /^ *!broken(?: (\S+))? *$/) { + elsif ( $msg =~ /^ *!broken(?: (\S+))? *$/ ) { my $index = $1; try { - my $id = PlayBot::utils::id::get($chan, $index); + my $id = PlayBot::utils::id::get( $chan, $index ); my @msg; try { - @msg = PlayBot::commands::broken::exec($chan, $id); - } catch { - @msg = split(/\n/, $_); + @msg = PlayBot::commands::broken::exec( $chan, $id ); + } + catch { + @msg = split( /\n/, $_ ); }; - $irc->yield(privmsg => $chan => $_) foreach (@msg); - } catch { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + $irc->yield( privmsg => $chan => $_ ) foreach (@msg); + } + catch { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); }; } - elsif ($msg =~ /^ *!stats(?: (\S+))? *$/) { + elsif ( $msg =~ /^ *!stats(?: (\S+))? *$/ ) { my $index = $1; try { - my $id = PlayBot::utils::id::get($chan, $index); - PlayBot::commands::stats::exec($chan, $id) - } catch { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + my $id = PlayBot::utils::id::get( $chan, $index ); + PlayBot::commands::stats::exec( $chan, $id ) + } + catch { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); }; - } - elsif ($msg =~ /^ *!conf +(.*)/) { - my @args = split(/ +/, $1); - PlayBot::commands::conf::exec($chan, $nick, @args); } - elsif ($msg =~ /^ *!help/) { - $irc->yield(privmsg => $nick => '!fav [<id>] : enregistre la vidéo dans les favoris'); - $irc->yield(privmsg => $nick => '!tag [<id>] <tag1> <tag2> ... : tag la vidéo'); - $irc->yield(privmsg => $nick => '!later [<id>] [in <x>[s|m|h]] : vidéo rappelée par query (par défaut temps de 6h)'); - $irc->yield(privmsg => $nick => " Sans id précisée, la dernière vidéo postée sur le chan est utilisée."); - $irc->yield(privmsg => $nick => ' L\'id peut être négatif, auquel cas -1 correspond à l\'avant dernière vidéo.'); - $irc->yield(privmsg => $nick => '!get [<id>|<query>] : sort aléatoirement une vidéo'); - $irc->yield(privmsg => $nick => ' Si un id est précisé, sort ce contenu (s\'il existe).'); - $irc->yield(privmsg => $nick => ' <query> : composée de tags commençant par un \'#\' ou de mots. Les mots sont recherché dans le titre ainsi que le nom de l\'auteur du contenu.'); - $irc->yield(privmsg => $nick => "!broken [<id>] : marque un contenu comme indisponible"); - $irc->yield(privmsg => $nick => "!stats [<id>] : informations sur un contenu"); - $irc->yield(privmsg => $nick => "---"); - $irc->yield(privmsg => $nick => "Un tag est de la forme « #[a-zA-Z0-9_]+ ». Par exemple « #loLILol_mdr42 » est un tag valide, tandis que « #céducaca » et « #je-suis-nul » n'en sont pas et seront considéré respectivement comme « #c » et « #je »."); - $irc->yield(privmsg => $nick => "Toutes ces commandes fonctionnent en query."); - $irc->yield(privmsg => $nick => "---"); - $irc->yield(privmsg => $nick => "Configuration d'un channel, utilisable uniquement par un op :"); - $irc->yield(privmsg => $nick => " !conf list : liste les sites supportés, ceux indiqués avec une astérisque étant activés"); - $irc->yield(privmsg => $nick => " !conf add|remove <site> : active ou désactive le support d'un site"); - $irc->yield(privmsg => $nick => "---"); - $irc->yield(privmsg => $nick => "Niveau vie privée, !fav, !later, et bien sûr poster un lien supporté entrainent un enregistrement dans la base de données avec au minimum la date, l'heure et le nick de la personne ayant exécuté la commande."); + elsif ( $msg =~ /^ *!conf +(.*)/ ) { + my @args = split( / +/, $1 ); + PlayBot::commands::conf::exec( $chan, $nick, @args ); + } + elsif ( $msg =~ /^ *!help/ ) { + $irc->yield( privmsg => $nick => + '!fav [<id>] : enregistre la vidéo dans les favoris' ); + $irc->yield( privmsg => $nick => + '!tag [<id>] <tag1> <tag2> ... : tag la vidéo' ); + $irc->yield( privmsg => $nick => +'!later [<id>] [in <x>[s|m|h]] : vidéo rappelée par query (par défaut temps de 6h)' + ); + $irc->yield( privmsg => $nick => +" Sans id précisée, la dernière vidéo postée sur le chan est utilisée." + ); + $irc->yield( privmsg => $nick => +' L\'id peut être négatif, auquel cas -1 correspond à l\'avant dernière vidéo.' + ); + $irc->yield( privmsg => $nick => + '!get [<id>|<query>] : sort aléatoirement une vidéo' ); + $irc->yield( privmsg => $nick => + ' Si un id est précisé, sort ce contenu (s\'il existe).' ); + $irc->yield( privmsg => $nick => +' <query> : composée de tags commençant par un \'#\' ou de mots. Les mots sont recherché dans le titre ainsi que le nom de l\'auteur du contenu.' + ); + $irc->yield( privmsg => $nick => + "!broken [<id>] : marque un contenu comme indisponible" ); + $irc->yield( + privmsg => $nick => "!stats [<id>] : informations sur un contenu" ); + $irc->yield( privmsg => $nick => "---" ); + $irc->yield( privmsg => $nick => +"Un tag est de la forme « #[a-zA-Z0-9_]+ ». Par exemple « #loLILol_mdr42 » est un tag valide, tandis que « #céducaca » et « #je-suis-nul » n'en sont pas et seront considéré respectivement comme « #c » et « #je »." + ); + $irc->yield( + privmsg => $nick => "Toutes ces commandes fonctionnent en query." ); + $irc->yield( privmsg => $nick => "---" ); + $irc->yield( privmsg => $nick => + "Configuration d'un channel, utilisable uniquement par un op :" ); + $irc->yield( privmsg => $nick => +" !conf list : liste les sites supportés, ceux indiqués avec une astérisque étant activés" + ); + $irc->yield( privmsg => $nick => +" !conf add|remove <site> : active ou désactive le support d'un site" + ); + $irc->yield( privmsg => $nick => "---" ); + $irc->yield( privmsg => $nick => +"Niveau vie privée, !fav, !later, et bien sûr poster un lien supporté entrainent un enregistrement dans la base de données avec au minimum la date, l'heure et le nick de la personne ayant exécuté la commande." + ); } - elsif ($msg =~/^ *!(fav|lat|tag|stats)/) { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + elsif ( $msg =~ /^ *!(fav|lat|tag|stats)/ ) { + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); } else { return 0; @@ -168,11 +204,11 @@ sub exec { } sub tag { - my ($msg, $chan, $id) = @_; - my @tags = ($msg =~ /(?:^| )(#[a-zA-Z0-9_]+)/g); + my ( $msg, $chan, $id ) = @_; + my @tags = ( $msg =~ /(?:^| )(#[a-zA-Z0-9_]+)/g ); - $id = PlayBot::utils::id::get($chan) if (not defined($id)); - PlayBot::commands::tag::exec($id, "@tags"); + $id = PlayBot::utils::id::get($chan) if ( not defined($id) ); + PlayBot::commands::tag::exec( $id, "@tags" ); return @tags; } diff --git a/PlayBot/commands/stats.pm b/PlayBot/commands/stats.pm index cff279c..904652a 100644 --- a/PlayBot/commands/stats.pm +++ b/PlayBot/commands/stats.pm @@ -10,21 +10,25 @@ use PlayBot::utils::db::stats; our $irc; -my @insultes = ("Ahahahah ! 23 à 0 !", "C'est la piquette, Jack !", "Tu sais pas jouer, Jack !", "T'es mauvais, Jack !"); +my @insultes = ( + "Ahahahah ! 23 à 0 !", + "C'est la piquette, Jack !", + "Tu sais pas jouer, Jack !", + "T'es mauvais, Jack !" +); sub exec { - my ($chan, $id) = @_; + my ( $chan, $id ) = @_; my $stats = PlayBot::utils::db::stats->new($id); if ($stats) { - foreach (PlayBot::utils::print::stats($stats)) { - $irc->yield(privmsg => $chan => $_) if ($_); + foreach ( PlayBot::utils::print::stats($stats) ) { + $irc->yield( privmsg => $chan => $_ ) if ($_); } } else { - $irc->yield(privmsg => $chan => $insultes[rand @insultes]); + $irc->yield( privmsg => $chan => $insultes[ rand @insultes ] ); } } - 1; diff --git a/PlayBot/commands/tag.pm b/PlayBot/commands/tag.pm index e82f6fa..720a648 100644 --- a/PlayBot/commands/tag.pm +++ b/PlayBot/commands/tag.pm @@ -8,32 +8,29 @@ our $dbh; our $log; sub exec { - my ($id, $msg) = @_; + my ( $id, $msg ) = @_; - while ($msg =~ /(?:^| )#?([a-zA-Z0-9_]+)/g) { - addTag($id, $1); + while ( $msg =~ /(?:^| )#?([a-zA-Z0-9_]+)/g ) { + addTag( $id, $1 ); } } -sub addTag -{ - my ($id, $tag) = @_; +sub addTag { + my ( $id, $tag ) = @_; # BRUTALE - if ($id eq 9320) { + if ( $id eq 9320 ) { return; } my $sth; $sth = $dbh->prepare('INSERT INTO playbot_tags (id, tag) VALUES (?, ?)'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); + $log->error("Couldn't prepare querie; aborting") unless ( defined $sth ); - eval { - $sth->execute($id, $tag) - }; - if ($@) { - $log->error("Couldn't finish transaction: " . $@); + eval { $sth->execute( $id, $tag ) }; + if ($@) { + $log->error( "Couldn't finish transaction: " . $@ ); } } diff --git a/PlayBot/sessions/downloader.pm b/PlayBot/sessions/downloader.pm index b441ce2..d1c7b69 100644 --- a/PlayBot/sessions/downloader.pm +++ b/PlayBot/sessions/downloader.pm @@ -10,32 +10,31 @@ use POE; use PlayBot::utils::Logging; use PlayBot::sessions::downloader::ddl; -my $log = PlayBot::utils::Logging->new('STDOUT', 1); +my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 ); local $/; open CONF, '<', 'playbot.conf'; my $json = <CONF>; my $conf = decode_json($json); -if ($conf->{download}) -{ +if ( $conf->{download} ) { POE::Session->create( - inline_states => { + inline_states => { _start => \&on_start, ddl => \&PlayBot::sessions::downloader::ddl::exec, filename => \&PlayBot::sessions::downloader::ddl::filename, - signal_filename => \&PlayBot::sessions::downloader::ddl::signal_filename, - signal_ddl => \&PlayBot::sessions::downloader::ddl::signal_ddl, - signal_move => \&PlayBot::sessions::downloader::ddl::signal_move, - signal_rm => \&PlayBot::sessions::downloader::ddl::signal_rm, - end_task => \&PlayBot::sessions::downloader::ddl::end_task, + signal_filename => + \&PlayBot::sessions::downloader::ddl::signal_filename, + signal_ddl => \&PlayBot::sessions::downloader::ddl::signal_ddl, + signal_move => \&PlayBot::sessions::downloader::ddl::signal_move, + signal_rm => \&PlayBot::sessions::downloader::ddl::signal_rm, + end_task => \&PlayBot::sessions::downloader::ddl::end_task, }, ); } - sub on_start { - my ($kernel, $heap) = @_[KERNEL, HEAP]; + my ( $kernel, $heap ) = @_[ KERNEL, HEAP ]; $kernel->alias_set('downloader'); $heap->{ddl}->{tasks} = []; diff --git a/PlayBot/sessions/downloader/ddl.pm b/PlayBot/sessions/downloader/ddl.pm index 33c34ef..057a0e2 100644 --- a/PlayBot/sessions/downloader/ddl.pm +++ b/PlayBot/sessions/downloader/ddl.pm @@ -11,7 +11,7 @@ use POE::Wheel::Run; use PlayBot::utils::db; use PlayBot::utils::Logging; -my $log = PlayBot::utils::Logging->new('STDOUT', 1); +my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 ); my $conf; BEGIN { @@ -23,13 +23,13 @@ BEGIN { } sub exec { - my ($kernel, $heap, $id, $url) = @_[KERNEL, HEAP, ARG0, ARG1]; - return if (not $id or not $url); + my ( $kernel, $heap, $id, $url ) = @_[ KERNEL, HEAP, ARG0, ARG1 ]; + return if ( not $id or not $url ); $log->debug("DDL '$id' '$url' "); # is there already a task running ? - if ($heap->{ddl}->{running}) { - push $heap->{ddl}->{tasks}, [$id, $url]; + if ( $heap->{ddl}->{running} ) { + push $heap->{ddl}->{tasks}, [ $id, $url ]; return; } @@ -37,90 +37,88 @@ sub exec { # first we need to got filename my $child = POE::Wheel::Run->new( - Program => [ - "youtube-dl", - "--restrict-filename", - "--get-filename", - "-o", - $conf->{save_format}, - $url, + Program => [ + "youtube-dl", "--restrict-filename", + "--get-filename", "-o", + $conf->{save_format}, $url, ], StdoutEvent => "filename", StderrEvent => "devnull", ); - $kernel->sig_child($child->PID, "signal_filename"); + $kernel->sig_child( $child->PID, "signal_filename" ); # we link playbot id to PID and url $heap->{ddl}->{pb}->{$id} = { - child => $child->PID, - url => $url, + child => $child->PID, + url => $url, }; # we link wheel id to playbot id - $heap->{ddl}->{wid}->{$child->ID} = $id; + $heap->{ddl}->{wid}->{ $child->ID } = $id; + # we link PID to child object - $heap->{ddl}->{pid}->{$child->PID} = $child; + $heap->{ddl}->{pid}->{ $child->PID } = $child; } sub filename { $log->debug("DDL"); - my ($heap, $stdout_line, $wid) = @_[HEAP, ARG0, ARG1]; - return if (not exists $heap->{ddl}->{wid}->{$wid}); + my ( $heap, $stdout_line, $wid ) = @_[ HEAP, ARG0, ARG1 ]; + return if ( not exists $heap->{ddl}->{wid}->{$wid} ); my $id = $heap->{ddl}->{wid}->{$wid}; $heap->{ddl}->{pb}->{$id}->{filename} = $stdout_line; - $heap->{ddl}->{pb}->{$id}->{child} = undef; + $heap->{ddl}->{pb}->{$id}->{child} = undef; } sub signal_filename { $log->debug("DDL"); - my ($kernel, $heap, $pid, $status) = @_[KERNEL, HEAP, ARG1, ARG2]; + my ( $kernel, $heap, $pid, $status ) = @_[ KERNEL, HEAP, ARG1, ARG2 ]; - my $child = delete $heap->{ddl}->{pid}->{$pid}; - my $id = delete $heap->{ddl}->{wid}->{$child->ID}; + my $child = delete $heap->{ddl}->{pid}->{$pid}; + my $id = delete $heap->{ddl}->{wid}->{ $child->ID }; - if (not defined $heap->{ddl}->{pb}->{$id}->{filename}) { + if ( not defined $heap->{ddl}->{pb}->{$id}->{filename} ) { $log->error("error getting filename for $id : $status"); $heap->{ddl}->{pb}->{$id}->{child} = undef; - $kernel->yield("end_task", $id); + $kernel->yield( "end_task", $id ); return; } # we actually download the content $child = POE::Wheel::Run->new( Program => [ - "youtube-dl", - "--restrict-filename", - "-o", - "/tmp/".$conf->{save_format}, + "youtube-dl", "--restrict-filename", + "-o", "/tmp/" . $conf->{save_format}, $heap->{ddl}->{pb}->{$id}->{url}, ], StdoutEvent => "devnull", StderrEvent => "devnull", ); - $kernel->sig_child($child->PID, "signal_ddl"); + $kernel->sig_child( $child->PID, "signal_ddl" ); # we link playbot id to PID and url $heap->{ddl}->{pb}->{$id}->{child} = $child->PID; # we link wheel id to playbot id - $heap->{ddl}->{wid}->{$child->ID} = $id; + $heap->{ddl}->{wid}->{ $child->ID } = $id; + # we link PID to child object - $heap->{ddl}->{pid}->{$child->PID} = $child; + $heap->{ddl}->{pid}->{ $child->PID } = $child; } sub signal_ddl { $log->debug("DDL"); - my ($kernel, $heap, $pid, $status) = @_[KERNEL, HEAP, ARG1, ARG2]; + my ( $kernel, $heap, $pid, $status ) = @_[ KERNEL, HEAP, ARG1, ARG2 ]; - my $child = delete $heap->{ddl}->{pid}->{$pid}; - my $id = delete $heap->{ddl}->{wid}->{$child->ID}; + my $child = delete $heap->{ddl}->{pid}->{$pid}; + my $id = delete $heap->{ddl}->{wid}->{ $child->ID }; $heap->{ddl}->{pb}->{$id}->{child} = undef; - if ($status ne "0") { + if ( $status ne "0" ) { $log->error("error downloading $id : $status"); - rm($kernel, $heap, $id, "/tmp/".$heap->{ddl}->{pb}->{$id}->{filename}.".part"); + rm( $kernel, $heap, $id, + "/tmp/" . $heap->{ddl}->{pb}->{$id}->{filename} . ".part" ); return; } @@ -128,43 +126,46 @@ sub signal_ddl { $child = POE::Wheel::Run->new( Program => [ "mv", - "/tmp/".$heap->{ddl}->{pb}->{$id}->{filename}, - $conf->{save_folder}."/".$heap->{ddl}->{pb}->{$id}->{filename}, + "/tmp/" . $heap->{ddl}->{pb}->{$id}->{filename}, + $conf->{save_folder} . "/" . $heap->{ddl}->{pb}->{$id}->{filename}, ], StdoutEvent => "devnull", StderrEvent => "devnull", ); - $kernel->sig_child($child->PID, "signal_move"); + $kernel->sig_child( $child->PID, "signal_move" ); # we link playbot id to PID and url $heap->{ddl}->{pb}->{$id}->{child} = $child->PID; # we link wheel id to playbot id - $heap->{ddl}->{wid}->{$child->ID} = $id; + $heap->{ddl}->{wid}->{ $child->ID } = $id; + # we link PID to child object - $heap->{ddl}->{pid}->{$child->PID} = $child; + $heap->{ddl}->{pid}->{ $child->PID } = $child; } sub signal_move { $log->debug("DDL"); - my ($kernel, $heap, $pid, $status) = @_[KERNEL, HEAP, ARG1, ARG2]; + my ( $kernel, $heap, $pid, $status ) = @_[ KERNEL, HEAP, ARG1, ARG2 ]; - my $child = delete $heap->{ddl}->{pid}->{$pid}; - my $id = delete $heap->{ddl}->{wid}->{$child->ID}; + my $child = delete $heap->{ddl}->{pid}->{$pid}; + my $id = delete $heap->{ddl}->{wid}->{ $child->ID }; $heap->{ddl}->{pb}->{$id}->{child} = undef; - if ($status ne "0") { + if ( $status ne "0" ) { $log->error("error moving $id from tmp : $status"); # rm file - rm($kernel, $heap, $id, "/tmp/".$heap->{ddl}->{pb}->{$id}->{filename}); + rm( $kernel, $heap, $id, + "/tmp/" . $heap->{ddl}->{pb}->{$id}->{filename} ); return; } # we update db eval { - PlayBot::utils::db::set_filename($id, $heap->{ddl}->{pb}->{$id}->{filename}); - $kernel->yield("end_task", $id); + PlayBot::utils::db::set_filename( $id, + $heap->{ddl}->{pb}->{$id}->{filename} ); + $kernel->yield( "end_task", $id ); }; if ($a) { $log->error($@); @@ -172,57 +173,55 @@ sub signal_move { $kernel, $heap, $id, - $conf->{save_folder}."/".$heap->{ddl}->{pb}->{$id}->{filename}, + $conf->{save_folder} . "/" . $heap->{ddl}->{pb}->{$id}->{filename}, ); } } sub rm { - my ($kernel, $heap, $id, $filename) = @_; + my ( $kernel, $heap, $id, $filename ) = @_; my $child = POE::Wheel::Run->new( - Program => [ - "rm", - $filename - ], + Program => [ "rm", $filename ], StdoutEvent => "devnull", StderrEvent => "devnull", ); - $kernel->sig_child($child->PID, "signal_rm"); + $kernel->sig_child( $child->PID, "signal_rm" ); # we link playbot id to PID and url $heap->{ddl}->{pb}->{$id}->{child} = $child->PID; # we link wheel id to playbot id - $heap->{ddl}->{wid}->{$child->ID} = $id; + $heap->{ddl}->{wid}->{ $child->ID } = $id; + # we link PID to child object - $heap->{ddl}->{pid}->{$child->PID} = $child; + $heap->{ddl}->{pid}->{ $child->PID } = $child; } sub signal_rm { $log->debug("DDL"); - my ($kernel, $heap, $pid, $status) = @_[KERNEL, HEAP, ARG1, ARG2]; + my ( $kernel, $heap, $pid, $status ) = @_[ KERNEL, HEAP, ARG1, ARG2 ]; - my $child = delete $heap->{ddl}->{pid}->{$pid}; - my $id = delete $heap->{ddl}->{wid}->{$child->ID}; + my $child = delete $heap->{ddl}->{pid}->{$pid}; + my $id = delete $heap->{ddl}->{wid}->{ $child->ID }; $heap->{ddl}->{pb}->{$id}->{child} = undef; - if ($status ne "0") { + if ( $status ne "0" ) { $log->critical("cannot remove file"); } - - $kernel->yield("end_task", $id); + + $kernel->yield( "end_task", $id ); } sub end_task { - my ($kernel, $heap, $id) = @_[KERNEL, HEAP, ARG0]; + my ( $kernel, $heap, $id ) = @_[ KERNEL, HEAP, ARG0 ]; $heap->{ddl}->{running} = 0; delete $heap->{ddl}->{pb}->{$id}; - if (@{ $heap->{ddl}->{tasks} }) { + if ( @{ $heap->{ddl}->{tasks} } ) { my $task = shift $heap->{ddl}->{tasks}; - $kernel->yield(ddl => $task->[0], $task->[1]); + $kernel->yield( ddl => $task->[0], $task->[1] ); } } diff --git a/PlayBot/sessions/facebook.pm b/PlayBot/sessions/facebook.pm index f4d6b37..5294455 100644 --- a/PlayBot/sessions/facebook.pm +++ b/PlayBot/sessions/facebook.pm @@ -14,7 +14,7 @@ use POE::Component::IKC::Server; use PlayBot::utils::Logging; -my $log = PlayBot::utils::Logging->new('STDOUT', 1); +my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 ); POE::Component::IKC::Server->spawn( unix => 'playbot.sock', @@ -22,7 +22,7 @@ POE::Component::IKC::Server->spawn( ); POE::Session->create( - inline_states => { + inline_states => { _start => \&on_start, fbmsg => \&on_fbmsg } @@ -31,14 +31,17 @@ POE::Session->create( sub on_start { my $kernel = $_[KERNEL]; $kernel->alias_set('fbrecv'); - $kernel->post(IKC => publish => 'fbrecv', ['fbmsg']); + $kernel->post( IKC => publish => 'fbrecv', ['fbmsg'] ); $log->info('listening for clients'); } sub on_fbmsg { - my ($kernel, $args) = @_[KERNEL, ARG0]; - $kernel->post('bot' => 'irc_public' => $args->[0], ['#nightiies.facebook'], $args->[1]); + my ( $kernel, $args ) = @_[ KERNEL, ARG0 ]; + $kernel->post( + 'bot' => 'irc_public' => $args->[0], + ['#nightiies.facebook'], $args->[1] + ); } 1; diff --git a/PlayBot/sessions/irc.pm b/PlayBot/sessions/irc.pm index 13be30f..f6e5a75 100644 --- a/PlayBot/sessions/irc.pm +++ b/PlayBot/sessions/irc.pm @@ -18,7 +18,7 @@ use PlayBot::sites; use PlayBot::sites::soundcloud; use PlayBot::commands::parser; -my $log = PlayBot::utils::Logging->new('STDOUT', 1); +my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 ); local $/; open CONF, '<', 'playbot.conf'; @@ -27,22 +27,26 @@ my $conf = decode_json($json); ## CONNEXION my ($irc) = POE::Component::IRC::State->spawn(); -my $dbh = DBI->connect('DBI:mysql:'.$conf->{'bdd'}.';host='.$conf->{'host'}, $conf->{'user'}, $conf->{'passwd'}, { - PrintError => 0, - AutoCommit => 1, - mysql_auto_reconnect => 1 - }) - or die("Couldn't connect to database: ".DBI->errstr); +my $dbh = DBI->connect( + 'DBI:mysql:' . $conf->{'bdd'} . ';host=' . $conf->{'host'}, + $conf->{'user'}, + $conf->{'passwd'}, + { + PrintError => 0, + AutoCommit => 1, + mysql_auto_reconnect => 1 + } +) or die( "Couldn't connect to database: " . DBI->errstr ); # config -my $serveur = '193.54.225.86'; -my $nick = $conf->{'nick'}; -my $port = 6667; -my $ircname = 'nightiies'; +my $serveur = '193.54.225.86'; +my $nick = $conf->{'nick'}; +my $port = 6667; +my $ircname = 'nightiies'; my $username = 'nightiies'; my @channels = @{ $conf->{'channels'} }; -my $admin = 'moise'; -my $baseurl = 'http://nightiies.iiens.net/links/'; +my $admin = 'moise'; +my $baseurl = 'http://nightiies.iiens.net/links/'; my @nicksToVerify; my @codesToVerify; my %lastID; @@ -50,81 +54,78 @@ my %lastID; my $debug = 0; # mode debug -if ($#ARGV + 1) { - @channels = ('#hormone'); - $nick = 'kikoo'; - $debug = 1; +if ( $#ARGV + 1 ) { + @channels = ('#hormone'); + $nick = 'kikoo'; + $debug = 1; } # Evenements que le bot va gérer POE::Session->create( - inline_states => { + inline_states => { _start => \&bot_start, irc_001 => \&on_connect, irc_public => \&on_speak, irc_msg => \&on_query, irc_invite => \&on_invite, irc_notice => \&on_notice, - _flux => \&flux, + _flux => \&flux, _later => sub { - PlayBot::sessions::irc::later::consume(@_[ARG0, ARG1, ARG2]) + PlayBot::sessions::irc::later::consume( @_[ ARG0, ARG1, ARG2 ] ); } - }, + }, ); - -my %commandes_admin = ("cycle" => \&cycle); - +my %commandes_admin = ( "cycle" => \&cycle ); ### FONCTIONS -sub flux -{ - my $kernel = $_[ KERNEL ]; - my $date = strftime ("%Y-%m-%d", localtime(time - 3600*24)); +sub flux { + my $kernel = $_[KERNEL]; + my $date = strftime( "%Y-%m-%d", localtime( time - 3600 * 24 ) ); foreach (@channels) { - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' SELECT COUNT(*) FROM playbot p JOIN playbot_chan pc ON p.id = pc.content - WHERE date = ? and chan = ?'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); - $sth->execute($date, $_) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); - my ($nbr) = $sth->fetchrow_array; - - if ($nbr) { - $irc->yield(privmsg => $_ => $nbr.' liens aujourd\'hui : '.$baseurl . substr ($_, 1) . '/' . $date); - } + WHERE date = ? and chan = ?' ); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); + $sth->execute( $date, $_ ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); + my ($nbr) = $sth->fetchrow_array; + + if ($nbr) { + $irc->yield( privmsg => $_ => $nbr + . ' liens aujourd\'hui : ' + . $baseurl + . substr( $_, 1 ) . '/' + . $date ); + } } - $kernel->delay_set('_flux', 3600*24); + $kernel->delay_set( '_flux', 3600 * 24 ); } +sub cycle { + my ($arg) = @_; -sub cycle -{ - my ($arg) = @_; - - $log->info("refresh modules"); + $log->info("refresh modules"); Module::Reload->check; setConf(); } +sub setConf { + PlayBot::commands::parser::setConf( $irc, $dbh, $log, \%lastID ); -sub setConf -{ - PlayBot::commands::parser::setConf($irc, $dbh, $log, \%lastID); - - $PlayBot::sites::irc = $irc; - $PlayBot::sites::log = $log; - $PlayBot::sites::playbot_api_key = $conf->{'playbot_api_key'}; - $PlayBot::sites::soundcloud::clientSecret = $conf->{'soundcloud_secret'}; + $PlayBot::sites::irc = $irc; + $PlayBot::sites::log = $log; + $PlayBot::sites::playbot_api_key = $conf->{'playbot_api_key'}; + $PlayBot::sites::soundcloud::clientSecret = $conf->{'soundcloud_secret'}; } - ## GESTION EVENTS # Au démarrage @@ -133,146 +134,146 @@ sub bot_start { $kernel->alias_set('bot'); $log->info("register all"); - $irc->yield(register => "all"); + $irc->yield( register => "all" ); $log->info("connecting"); - $irc->yield( - connect => { - Nick => $nick, - Username => $username, - Ircname => $ircname, - Server => $serveur, - Port => $port, - } - ); + $irc->yield( + connect => { + Nick => $nick, + Username => $username, + Ircname => $ircname, + Server => $serveur, + Port => $port, + } + ); } - # A la connection -sub on_connect -{ - my $kernel = $_[ KERNEL ]; +sub on_connect { + my $kernel = $_[KERNEL]; - $log->info('connected'); + $log->info('connected'); setConf(); - $irc->yield(privmsg => "NickServ" => "identify ".$conf->{'nickserv_pwd'}) unless ($debug); + $irc->yield( + privmsg => "NickServ" => "identify " . $conf->{'nickserv_pwd'} ) + unless ($debug); - foreach (@channels) { - $irc->delay([join => $_], 20); - $log->info("join $_"); - } + foreach (@channels) { + $irc->delay( [ join => $_ ], 20 ); + $log->info("join $_"); + } - my $hour = strftime ('%H', localtime); - my $min = strftime ('%M', localtime); + my $hour = strftime( '%H', localtime ); + my $min = strftime( '%M', localtime ); - #$kernel->delay_set('_flux', (23-$hour)*3600 + (60-$min)*60); + #$kernel->delay_set('_flux', (23-$hour)*3600 + (60-$min)*60); } - # Discussion privée -sub on_query -{ - my ($kernel, $user, $msg) = @_[KERNEL, ARG0, ARG2]; - my ($nick) = split (/!/,$user); +sub on_query { + my ( $kernel, $user, $msg ) = @_[ KERNEL, ARG0, ARG2 ]; + my ($nick) = split( /!/, $user ); my $fake_chan = $nick; - my @args = ($kernel, $user, $fake_chan, $msg); - - return if (PlayBot::commands::parser::exec(@args)); - - if ($msg =~ m/^!/ && $nick eq $admin) { - my $commande = ( $msg =~ m/^!([^ ]*)/ )[0]; - my @params = grep {!/^\s*$/} split(/\s+/, substr($msg, length("!$commande"))); - - foreach (keys(%commandes_admin)) { - if ($commande eq $_) { - $commandes_admin{$_}->(@params); - last; - } - } - } - elsif ($msg =~ /^PB/) { - # on vérifie si le nick est register - push (@nicksToVerify, $nick); - push (@codesToVerify, $msg); - $irc->yield(privmsg => $nick => 'Vérification en cours…'); - $irc->yield(privmsg => nickserv => 'info '.$nick); - } + my @args = ( $kernel, $user, $fake_chan, $msg ); + + return if ( PlayBot::commands::parser::exec(@args) ); + + if ( $msg =~ m/^!/ && $nick eq $admin ) { + my $commande = ( $msg =~ m/^!([^ ]*)/ )[0]; + my @params = grep { !/^\s*$/ } + split( /\s+/, substr( $msg, length("!$commande") ) ); + + foreach ( keys(%commandes_admin) ) { + if ( $commande eq $_ ) { + $commandes_admin{$_}->(@params); + last; + } + } + } + elsif ( $msg =~ /^PB/ ) { + + # on vérifie si le nick est register + push( @nicksToVerify, $nick ); + push( @codesToVerify, $msg ); + $irc->yield( privmsg => $nick => 'Vérification en cours…' ); + $irc->yield( privmsg => nickserv => 'info ' . $nick ); + } } +sub on_notice { + my ( $user, $msg ) = @_[ ARG0, ARG2 ]; + my ($nick) = split( /!/, $user ); + + return unless ( $nick =~ /^NickServ$/i ); + + my $nickToVerify = shift @nicksToVerify; + my $code = shift @codesToVerify; -sub on_notice -{ - my ($user, $msg) = @_[ARG0, ARG2]; - my ($nick) = split(/!/,$user); - - return unless ($nick =~ /^NickServ$/i); - - my $nickToVerify = shift @nicksToVerify; - my $code = shift @codesToVerify; - - return unless (defined($nickToVerify)); - - if ($msg !~ /$nickToVerify/) { - push (@nicksToVerify, $nickToVerify); - push (@codesToVerify, $code); - } - elsif ($msg =~ /isn't registered/) { - $irc->yield(privmsg => $nickToVerify => "Il faut que ton pseudo soit enregistré auprès de NickServ"); - } - else { - my $sth = $dbh->prepare('SELECT user FROM playbot_codes WHERE code = ?'); - $log->error("Counldn't prepare querie; aborting") unless (defined $sth); - $sth->execute($code); - - if ($sth->rows) { - my $sth = $dbh->prepare('UPDATE playbot_codes SET nick = ? WHERE code = ?'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); - - $sth->execute($nickToVerify, $code) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); - - $irc->yield(privmsg => $nickToVerify => 'Association effectuée'); - $irc->yield(privmsg => $nickToVerify => 'pour enregistrer un lien dans tes favoris : !fav <id>'); - } - else { - $irc->yield(privmsg => $nickToVerify => "Ce code n'existe pas"); - } - } + return unless ( defined($nickToVerify) ); + + if ( $msg !~ /$nickToVerify/ ) { + push( @nicksToVerify, $nickToVerify ); + push( @codesToVerify, $code ); + } + elsif ( $msg =~ /isn't registered/ ) { + $irc->yield( privmsg => $nickToVerify => + "Il faut que ton pseudo soit enregistré auprès de NickServ" ); + } + else { + my $sth = + $dbh->prepare('SELECT user FROM playbot_codes WHERE code = ?'); + $log->error("Counldn't prepare querie; aborting") + unless ( defined $sth ); + $sth->execute($code); + + if ( $sth->rows ) { + my $sth = + $dbh->prepare('UPDATE playbot_codes SET nick = ? WHERE code = ?'); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); + + $sth->execute( $nickToVerify, $code ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); + + $irc->yield( privmsg => $nickToVerify => 'Association effectuée' ); + $irc->yield( privmsg => $nickToVerify => + 'pour enregistrer un lien dans tes favoris : !fav <id>' ); + } + else { + $irc->yield( privmsg => $nickToVerify => "Ce code n'existe pas" ); + } + } } # Quand on m'invite, je join -sub on_invite -{ - my ($kernel, $user, $chan) = @_[KERNEL, ARG0, ARG1]; - my ($nick,$mask) = split(/!/,$user); +sub on_invite { + my ( $kernel, $user, $chan ) = @_[ KERNEL, ARG0, ARG1 ]; + my ( $nick, $mask ) = split( /!/, $user ); - $log->info($nick . " m'invite sur ". $chan); - $irc->yield(join => $chan); + $log->info( $nick . " m'invite sur " . $chan ); + $irc->yield( join => $chan ); push @channels, $chan; } # Quand un user parle -sub on_speak -{ - my ($kernel, $user, $chan, $msg) = @_[KERNEL, ARG0, ARG1, ARG2]; - my @args = ($kernel, $user, lc $chan->[0], $msg); +sub on_speak { + my ( $kernel, $user, $chan, $msg ) = @_[ KERNEL, ARG0, ARG1, ARG2 ]; + my @args = ( $kernel, $user, lc $chan->[0], $msg ); - my ($nick,$mask) = split(/!/,$user); - my %content; + my ( $nick, $mask ) = split( /!/, $user ); + my %content; # first we check for url my @processed_str = PlayBot::sites::parse(@args); # and we check for command - my $cmd = (split /\s/, $msg)[0]; - if ($cmd eq "!fav") - { - @args = ($kernel, $user, lc $chan->[0], $cmd); + my $cmd = ( split /\s/, $msg )[0]; + if ( $cmd eq "!fav" ) { + @args = ( $kernel, $user, lc $chan->[0], $cmd ); } - else - { - @args = ($kernel, $user, lc $chan->[0], $msg); + else { + @args = ( $kernel, $user, lc $chan->[0], $msg ); } PlayBot::commands::parser::exec(@args); } diff --git a/PlayBot/sessions/irc/later.pm b/PlayBot/sessions/irc/later.pm index 7433eff..6f43df6 100644 --- a/PlayBot/sessions/irc/later.pm +++ b/PlayBot/sessions/irc/later.pm @@ -6,11 +6,10 @@ use utf8; use PlayBot::commands::get; -sub consume -{ - my ($nick, $id, $chan_src) = @_; +sub consume { + my ( $nick, $id, $chan_src ) = @_; - my @args = (0, $nick, $id, $chan_src); + my @args = ( 0, $nick, $id, $chan_src ); PlayBot::commands::get::exec(@args); } diff --git a/PlayBot/sites.pm b/PlayBot/sites.pm index 8ee207d..fa8f70c 100644 --- a/PlayBot/sites.pm +++ b/PlayBot/sites.pm @@ -6,7 +6,10 @@ use utf8; use LWP::UserAgent; use JSON; -use Module::Pluggable sub_name => 'sites', search_path => ['PlayBot::sites'], require => 1; +use Module::Pluggable + sub_name => 'sites', + search_path => ['PlayBot::sites'], + require => 1; use Storable qw(dclone); use PlayBot::utils::db; @@ -19,10 +22,9 @@ our $log; our $regex; our $playbot_api_key; - sub parse { - my ($kernel, $user, $chan, $msg, $playlist) = @_; - my ($nick,$mask) = split(/!/,$user); + my ( $kernel, $user, $chan, $msg, $playlist ) = @_; + my ( $nick, $mask ) = split( /!/, $user ); my $ua = LWP::UserAgent->new( timeout => 2, @@ -31,17 +33,16 @@ sub parse { my $response = $ua->post( "http://cloud.cervoi.se:12345/rpc", "X-PLAYBOT-KEY" => $playbot_api_key, - Content => encode_json {"channel" => $chan, "user" => $nick, "value" => $msg}, + Content => + encode_json { "channel" => $chan, "user" => $nick, "value" => $msg }, ); - if ($response->is_success) - { + if ( $response->is_success ) { $log->info("Handled by scala"); - $irc->yield(privmsg => $chan => $response->decoded_content); + $irc->yield( privmsg => $chan => $response->decoded_content ); return; } - else - { - $log->info($response->code. " still perl job"); + else { + $log->info( $response->code . " still perl job" ); } my $chan_conf = PlayBot::utils::db::chan->new($chan); @@ -52,19 +53,19 @@ sub parse { my @matching_tags; # parsing - foreach my $site (__PACKAGE__->sites) - { - not grep { $site eq "PlayBot::sites::$_" } @{ $chan_conf->sites } and next; + foreach my $site ( __PACKAGE__->sites ) { + not grep { $site eq "PlayBot::sites::$_" } @{ $chan_conf->sites } + and next; my @args; - if (@args = ($msg =~ $site->regex)) - { - eval { %content = $site->get(@args) }; + if ( @args = ( $msg =~ $site->regex ) ) { + eval { %content = $site->get(@args) }; $matching_url = $&; $content{playlist} = 0; last; } - elsif ($site->can('regex_playlist') and @args = ($msg =~ $site->regex_playlist)) + elsif ( $site->can('regex_playlist') + and @args = ( $msg =~ $site->regex_playlist ) ) { eval { %content = $site->get_playlist(@args) }; $matching_url = $&; @@ -75,134 +76,133 @@ sub parse { # something goes wrong ? if ($@) { - $log->warning ($@); + $log->warning($@); return; } my $id; + # if we get a new content, we must save it if (%content) { - ($id, @matching_tags) = insert_content($kernel, $nick, $chan, dclone(\%content), $msg, $playlist); + ( $id, @matching_tags ) = + insert_content( $kernel, $nick, $chan, dclone( \%content ), + $msg, $playlist ); - if (not $playlist and $content{playlist}) - { - foreach my $url (@{ $content{urls} }) - { + if ( not $playlist and $content{playlist} ) { + foreach my $url ( @{ $content{urls} } ) { my $new_msg = $msg; $new_msg =~ s/\Q$matching_url\E/$url/; - parse($kernel, $user, $chan, $new_msg, $id); + parse( $kernel, $user, $chan, $new_msg, $id ); } } } - return ( - $matching_url, - @matching_tags - ); + return ( $matching_url, @matching_tags ); } -sub insert_content -{ - my ($kernel, $nick, $chan, $content, $msg, $playlist) = @_; +sub insert_content { + my ( $kernel, $nick, $chan, $content, $msg, $playlist ) = @_; my $dbh = PlayBot::utils::db::main_session(); my $id; # we assume it's a new content my $new = 1; - # insertion de la vidéo dans la bdd + # insertion de la vidéo dans la bdd eval { - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' INSERT INTO playbot (type, url, external_id, sender, title, duration, playlist) VALUES (?,?,?,?,?,?,?) - '); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); - - $sth->execute( - $content->{site}, - $content->{url}, - $content->{external_id}, - $content->{author}, - $content->{title}, - $content->{duration}, + ' ); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); + + $sth->execute( + $content->{site}, $content->{url}, + $content->{external_id}, $content->{author}, + $content->{title}, $content->{duration}, $content->{playlist}, ); }; if ($@) { + # seems to be already present in database $new = 0; - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' UPDATE playbot SET sender = ?, title = ?, duration = ?, external_id = ? WHERE url = ? - '); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); - - $sth->execute( - $content->{author}, - $content->{title}, - $content->{duration}, - $content->{external_id}, + ' ); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); + + $sth->execute( + $content->{author}, $content->{title}, + $content->{duration}, $content->{external_id}, $content->{url}, ); } - # sélection de l'id de la vidéo insérée - my $sth = $dbh->prepare('SELECT id FROM playbot WHERE url = ?'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); + # sélection de l'id de la vidéo insérée + my $sth = $dbh->prepare('SELECT id FROM playbot WHERE url = ?'); + $log->error("Couldn't prepare querie; aborting") unless ( defined $sth ); + + $sth->execute( $content->{url} ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); - $sth->execute($content->{url}) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + $id = $sth->fetch->[0]; - $id = $sth->fetch->[0]; + if ( defined($playlist) ) { - if (defined($playlist)) - { # save track in the playlist - $sth = $dbh->prepare(' + $sth = $dbh->prepare( ' INSERT INTO playbot_playlist_content_association (playlist_id, content_id) - VALUES (?,?)'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); + VALUES (?,?)' ); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); eval { - $sth->execute($playlist, $id); + $sth->execute( $playlist, $id ); $dbh->commit; }; - if ($@) - { + if ($@) { + # the association already exists $dbh->rollback; } } - else - { + else { # insertion du chan - $sth = $dbh->prepare(' + $sth = $dbh->prepare( ' INSERT INTO playbot_chan (content, chan, sender_irc) - VALUES (?,?,?)'); - $log->error("Couldn't prepare querie; aborting") unless (defined $sth); + VALUES (?,?,?)' ); + $log->error("Couldn't prepare querie; aborting") + unless ( defined $sth ); - $sth->execute($id, $chan, $nick) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + $sth->execute( $id, $chan, $nick ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); $dbh->commit; } - my @matching_tags = PlayBot::commands::parser::tag($msg, $chan, $id); + my @matching_tags = PlayBot::commands::parser::tag( $msg, $chan, $id ); my @tags; + # get tags - $sth = $dbh->prepare("select tag + $sth = $dbh->prepare( + "select tag from playbot_tags where id = ? - "); + " + ); $sth->execute($id); - while (my $data = $sth->fetch) { + while ( my $data = $sth->fetch ) { my $tag = $data->[0]; $tag =~ s/([a-zA-Z0-9_-]+)/#$1/; push @tags, $tag; @@ -210,10 +210,11 @@ sub insert_content $dbh->commit; if ($new) { + # schedule download - $kernel->post(downloader => ddl => $id, $content->{url}); + $kernel->post( downloader => ddl => $id, $content->{url} ); - $content->{id} = '+'.$id; + $content->{id} = '+' . $id; } else { $content->{id} = $id; @@ -222,10 +223,11 @@ sub insert_content delete $content->{url}; delete $content->{external_id}; - if (not $playlist) - { + if ( not $playlist ) { + # message sur irc - $irc->yield(privmsg => $chan => PlayBot::utils::print::print($content)); + $irc->yield( + privmsg => $chan => PlayBot::utils::print::print($content) ); } return $content->{id}, @matching_tags; diff --git a/PlayBot/sites/dailymotion.pm b/PlayBot/sites/dailymotion.pm index e2fd872..f7be8a0 100644 --- a/PlayBot/sites/dailymotion.pm +++ b/PlayBot/sites/dailymotion.pm @@ -6,31 +6,27 @@ use utf8; use Inline Python => 'DATA'; - -sub regex -{ +sub regex { return qr#(?:^|[^!])https?://www.dailymotion.com/video/([a-z0-9]+)#; } - sub get { shift; - my $id = shift; + my $id = shift; my $content = weboob_get($id); # weboob returns duration in h:mm:s format - my ($h, $m, $s) = ($content->{'duration'} =~ /(.):(..):(..)/); + my ( $h, $m, $s ) = ( $content->{'duration'} =~ /(.):(..):(..)/ ); $content->{'duration'} = $h * 3600 + $m * 60 + $s; - $content->{site} = 'dailymotion'; - $content->{'url'} = 'https://www.dailymotion.com/video/'.$id; + $content->{site} = 'dailymotion'; + $content->{'url'} = 'https://www.dailymotion.com/video/' . $id; return %{$content}; } 1; - __DATA__ __Python__ diff --git a/PlayBot/sites/deezer.pm b/PlayBot/sites/deezer.pm index 2a01673..d33797f 100644 --- a/PlayBot/sites/deezer.pm +++ b/PlayBot/sites/deezer.pm @@ -11,37 +11,35 @@ use FindBin; my $conf; my $endpoint = "https://api.deezer.com/track/"; -sub regex -{ +sub regex { return qr#(?:^|[^!])https?://(?:www.)?deezer.com/track/([a-zA-Z0-9_-]+)#; } sub get { shift; - my $id = shift; - + my $id = shift; + my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint - .$id); - die($response->status_line) unless ($response->is_success); + my $response = $ua->get( $endpoint . $id ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); - my $content = decode_json($response->decoded_content); + # die "video not found" if (not scalar @{ $content->{items} }); -# die "video not found" if (not scalar @{ $content->{items} }); - my %infos; - $infos{'title'} = $content->{'title'}; - $infos{'duration'} = $content->{'duration'}; - $infos{'site'} = 'deezer'; - $infos{'url'} = 'https://www.deezer.com/track/'.$id; - $infos{'author'} = $content->{'artist'}->{'name'}; - $infos{'external_id'} = $id; + $infos{'title'} = $content->{'title'}; + $infos{'duration'} = $content->{'duration'}; + $infos{'site'} = 'deezer'; + $infos{'url'} = 'https://www.deezer.com/track/' . $id; + $infos{'author'} = $content->{'artist'}->{'name'}; + $infos{'external_id'} = $id; - return %infos; + return %infos; } 1; diff --git a/PlayBot/sites/facebook.pm b/PlayBot/sites/facebook.pm index 66c1ea0..f1284cb 100644 --- a/PlayBot/sites/facebook.pm +++ b/PlayBot/sites/facebook.pm @@ -19,40 +19,42 @@ BEGIN { $conf = decode_json($json); } -sub regex -{ - return qr#(?:^|[^!])https?://(?:www.)?facebook.com/(?:video/)?(?:video.php\?v=|.*/videos/)([a-zA-Z0-9_-]+)#; +sub regex { + return +qr#(?:^|[^!])https?://(?:www.)?facebook.com/(?:video/)?(?:video.php\?v=|.*/videos/)([a-zA-Z0-9_-]+)#; } sub get { shift; my $id = shift; - + my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint - .$id - .'?access_token='.$conf->{'facebook_access_token'} - .'&fields=title,from,permalink_url,length'); - die($response->status_line) unless ($response->is_success); + my $response = + $ua->get( $endpoint + . $id + . '?access_token=' + . $conf->{'facebook_access_token'} + . '&fields=title,from,permalink_url,length' ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); - my $content = decode_json($response->decoded_content); + die "Fuck Facebook." if ( exists $content->{'error'} ); - die "Fuck Facebook." if (exists $content->{'error'} ); - my %infos; $infos{'title'} = $content->{'title'}; - if (!exists $content->{'title'}) { + if ( !exists $content->{'title'} ) { $infos{'title'} = 'Untitled'; } $infos{'duration'} = $content->{'length'}; - $infos{'site'} = 'facebook'; - $infos{'url'} = 'https://www.facebook.com'.$content->{'permalink_url'}; + $infos{'site'} = 'facebook'; + $infos{'url'} = 'https://www.facebook.com' . $content->{'permalink_url'}; $infos{'author'} = $content->{'from'}->{'name'}; - $infos{'external_id'} = $id; + $infos{'external_id'} = $id; return %infos; } diff --git a/PlayBot/sites/mixcloud.pm b/PlayBot/sites/mixcloud.pm index 9acf657..f8852c7 100644 --- a/PlayBot/sites/mixcloud.pm +++ b/PlayBot/sites/mixcloud.pm @@ -8,36 +8,33 @@ use LWP::UserAgent; use JSON; use Encode; - -sub regex -{ +sub regex { return qr#(?:^|[^!])https?://www.mixcloud.com/([\w-]+/[\w-]+)#; } - sub get { shift; - my $id = shift; + my $id = shift; print "$id\n"; - my $url = 'https://api.mixcloud.com/'.$id; + my $url = 'https://api.mixcloud.com/' . $id; - my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + my $ua = LWP::UserAgent->new( + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($url); - die($response->status_line) unless ($response->is_success); - - my $content = decode_json(encode('UTF-8', $response->decoded_content)); - my $infos = { - title => $content->{'name'}, - author => $content->{'user'}->{'name'}, - url => $content->{'url'}, - duration => $content->{'audio_length'}, - site => 'mixcloud', + my $response = $ua->get($url); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( encode( 'UTF-8', $response->decoded_content ) ); + my $infos = { + title => $content->{'name'}, + author => $content->{'user'}->{'name'}, + url => $content->{'url'}, + duration => $content->{'audio_length'}, + site => 'mixcloud', }; - return %{ $infos }; + return %{$infos}; } 1; diff --git a/PlayBot/sites/soundcloud.pm b/PlayBot/sites/soundcloud.pm index e6c2126..67c4f8d 100644 --- a/PlayBot/sites/soundcloud.pm +++ b/PlayBot/sites/soundcloud.pm @@ -10,103 +10,100 @@ use Scalar::Util qw(looks_like_number); use PlayBot::utils::Logging; -my $log = PlayBot::utils::Logging->new('STDOUT', 1); +my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 ); -my $root = 'https://api.soundcloud.com'; +my $root = 'https://api.soundcloud.com'; my $clientId = 'f4956716fe1a9dc9c3725af822963365'; our $clientSecret; my $access_token = ''; my $access_token_time; - -sub regex_playlist -{ - return qr#(?:^|[^!])https?://(?:www\.)?soundcloud.com/([a-zA-Z0-9_-]+/sets/[a-zA-Z0-9_-]+)(?:\?.+)?#; +sub regex_playlist { + return +qr#(?:^|[^!])https?://(?:www\.)?soundcloud.com/([a-zA-Z0-9_-]+/sets/[a-zA-Z0-9_-]+)(?:\?.+)?#; } - -sub regex -{ - return qr#(?:^|[^!])https?://(?:www\.)?soundcloud.com/([a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+)(?:\?.+)?#; +sub regex { + return +qr#(?:^|[^!])https?://(?:www\.)?soundcloud.com/([a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+)(?:\?.+)?#; } -sub get_access_token -{ - if ($access_token ne '' && time() - $access_token_time <= 3000) - { - return $access_token; - } - - $log->info("Get a new soundcloud token"); - - my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, - ); - my $response = $ua->post( - $root.'/oauth2/token?grant_type=client_credentials&client_id='.$clientId.'&client_secret='.$clientSecret, - ); - die($response->status_line) unless ($response->is_success); - - my $content = decode_json($response->decoded_content); - $access_token = $content->{'access_token'}; - $access_token_time = time(); - - return $access_token; +sub get_access_token { + if ( $access_token ne '' && time() - $access_token_time <= 3000 ) { + return $access_token; + } + + $log->info("Get a new soundcloud token"); + + my $ua = LWP::UserAgent->new( + timeout => 30, + env_proxy => 1, + ); + my $response = + $ua->post( $root + . '/oauth2/token?grant_type=client_credentials&client_id=' + . $clientId + . '&client_secret=' + . $clientSecret, ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); + $access_token = $content->{'access_token'}; + $access_token_time = time(); + + return $access_token; } - sub get_playlist { - shift; - my $id = shift; - - my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, - ); - - my $response; - if (looks_like_number($id)) - { - $response = $ua->get($root.'/playlists/'.$id.'?client_id='.$clientId); - } - else - { - my $url = 'https://www.soundcloud.com/'.$id; - $response = $ua->get($root.'/resolve.json?url='.$url.'&client_id='.$clientId); - } - die($response->status_line) unless ($response->is_success); - - my $content = decode_json($response->decoded_content); - my $infos = { - author => $content->{'user'}->{'username'}, - external_id => $content->{'id'}, - duration => $content->{'track_count'}, - site => 'soundcloud', - title => $content->{'title'}, - url => $content->{permalink_url}, - }; - - my @urls; - foreach my $item (@{ $content->{'tracks'} }) - { - push @urls, $item->{'permalink_url'}; - } - - $infos->{'urls'} = \@urls; - return %$infos; + shift; + my $id = shift; + + my $ua = LWP::UserAgent->new( + timeout => 30, + env_proxy => 1, + ); + + my $response; + if ( looks_like_number($id) ) { + $response = + $ua->get( $root . '/playlists/' . $id . '?client_id=' . $clientId ); + } + else { + my $url = 'https://www.soundcloud.com/' . $id; + $response = $ua->get( + $root . '/resolve.json?url=' . $url . '&client_id=' . $clientId ); + } + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); + my $infos = { + author => $content->{'user'}->{'username'}, + external_id => $content->{'id'}, + duration => $content->{'track_count'}, + site => 'soundcloud', + title => $content->{'title'}, + url => $content->{permalink_url}, + }; + + my @urls; + foreach my $item ( @{ $content->{'tracks'} } ) { + push @urls, $item->{'permalink_url'}; + } + + $infos->{'urls'} = \@urls; + return %$infos; } - sub get { - shift; - my $id = shift; + shift; + my $id = shift; - my $response; - $log->info("the id is ".$id); + my $response; + $log->info( "the id is " . $id ); - my $content = `./soundcloud $id`; - my ($external_id, $url, $title, $author, $duration) = split(/\n/, $content); + my $content = `./soundcloud $id`; + my ( $external_id, $url, $title, $author, $duration ) = + split( /\n/, $content ); =cut my $ua = LWP::UserAgent->new( @@ -147,16 +144,16 @@ sub get { } =cut - my $infos = { - author => $author, - external_id => $external_id, - duration => $duration, - site => 'soundcloud', - title => $title, - url => $url, - }; + my $infos = { + author => $author, + external_id => $external_id, + duration => $duration, + site => 'soundcloud', + title => $title, + url => $url, + }; - return %$infos; + return %$infos; } 1; diff --git a/PlayBot/sites/spotify.pm b/PlayBot/sites/spotify.pm index 3c72b63..8c9a797 100644 --- a/PlayBot/sites/spotify.pm +++ b/PlayBot/sites/spotify.pm @@ -11,74 +11,74 @@ use FindBin; my $conf; my $endpoint = "https://api.spotify.com/v1"; -sub regex_playlist -{ - return qr#(?:^|[^!])https?://(?:open|play).spotify.com/album/([a-zA-Z0-9]+)#; +sub regex_playlist { + return + qr#(?:^|[^!])https?://(?:open|play).spotify.com/album/([a-zA-Z0-9]+)#; } -sub regex -{ - return qr#(?:^|[^!])https?://(?:open|play).spotify.com/track/([a-zA-Z0-9_-]+)#; +sub regex { + return + qr#(?:^|[^!])https?://(?:open|play).spotify.com/track/([a-zA-Z0-9_-]+)#; } sub get_playlist { - shift; - my $id = shift; + shift; + my $id = shift; my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint.'/albums/'.$id); - die($response->status_line) unless ($response->is_success); + my $response = $ua->get( $endpoint . '/albums/' . $id ); + die( $response->status_line ) unless ( $response->is_success ); - my $playlist = decode_json($response->decoded_content); + my $playlist = decode_json( $response->decoded_content ); my %infos; - $infos{'title'} = $playlist->{name}; + $infos{'title'} = $playlist->{name}; $infos{'duration'} = 0; - $infos{'author'} = join(' ft. ', map { $_->{name} } @{ $playlist->{artists} }); - $infos{'site'} = 'spotify'; - $infos{'url'} = 'https://open.spotify.com/album/'.$id; - $infos{'external_id'} = $playlist->{id}; + $infos{'author'} = + join( ' ft. ', map { $_->{name} } @{ $playlist->{artists} } ); + $infos{'site'} = 'spotify'; + $infos{'url'} = 'https://open.spotify.com/album/' . $id; + $infos{'external_id'} = $playlist->{id}; my @urls; - foreach my $track (@{ $playlist->{tracks}{items} }) - { + foreach my $track ( @{ $playlist->{tracks}{items} } ) { my $track_id = $track->{id}; - push @urls, 'https://open.spotify.com/track/'.$track_id; - $infos{duration}++; + push @urls, 'https://open.spotify.com/track/' . $track_id; + $infos{duration}++; } $infos{urls} = \@urls; - return %infos; + return %infos; } sub get { shift; - my $id = shift; - + my $id = shift; + my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint.'/tracks/'.$id); - die($response->status_line) unless ($response->is_success); + my $response = $ua->get( $endpoint . '/tracks/' . $id ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); - my $content = decode_json($response->decoded_content); + # die "video not found" if (not scalar @{ $content->{items} }); -# die "video not found" if (not scalar @{ $content->{items} }); - my %infos; - $infos{'title'} = $content->{'name'}; - $infos{'duration'} = $content->{'duration_ms'} / 1000; - $infos{'site'} = 'spotify'; - $infos{'url'} = 'https://open.spotify.com/track/'.$id; - $infos{'author'} = $content->{'artists'}->[0]->{'name'}; - $infos{'external_id'} = $id; + $infos{'title'} = $content->{'name'}; + $infos{'duration'} = $content->{'duration_ms'} / 1000; + $infos{'site'} = 'spotify'; + $infos{'url'} = 'https://open.spotify.com/track/' . $id; + $infos{'author'} = $content->{'artists'}->[0]->{'name'}; + $infos{'external_id'} = $id; - return %infos; + return %infos; } 1; diff --git a/PlayBot/sites/youtube.pm b/PlayBot/sites/youtube.pm index ae30a4e..8a60d4e 100644 --- a/PlayBot/sites/youtube.pm +++ b/PlayBot/sites/youtube.pm @@ -19,90 +19,94 @@ BEGIN { $conf = decode_json($json); } -sub regex_playlist -{ - return qr#(?:^|[^!])https?://www.youtube.com/playlist\?[a-zA-Z0-9_=&-]*list=([a-zA-Z0-9_-]+)#; +sub regex_playlist { + return +qr#(?:^|[^!])https?://www.youtube.com/playlist\?[a-zA-Z0-9_=&-]*list=([a-zA-Z0-9_-]+)#; } -sub regex -{ - return qr#(?:^|[^!])https?://(?:www.youtube.com/watch\?[a-zA-Z0-9_=&-]*v=|youtu.be/)([a-zA-Z0-9_-]+)#; +sub regex { + return +qr#(?:^|[^!])https?://(?:www.youtube.com/watch\?[a-zA-Z0-9_=&-]*v=|youtu.be/)([a-zA-Z0-9_-]+)#; } -sub get_playlist -{ +sub get_playlist { shift; - my $id = shift; - + my $id = shift; + my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint - .'/playlists?id='.$id - .'&key='.$conf->{'youtube_api_key'} - .'&part=snippet,contentDetails'); - die($response->status_line) unless ($response->is_success); + my $response = + $ua->get( $endpoint + . '/playlists?id=' + . $id . '&key=' + . $conf->{'youtube_api_key'} + . '&part=snippet,contentDetails' ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); - my $content = decode_json($response->decoded_content); + die "playlist not found" if ( not scalar @{ $content->{items} } ); - die "playlist not found" if (not scalar @{ $content->{items} }); - my $playlist = $content->{'items'}->[0]; my %infos; - $infos{'title'} = $playlist->{'snippet'}->{'title'}; + $infos{'title'} = $playlist->{'snippet'}->{'title'}; $infos{'duration'} = $playlist->{'contentDetails'}->{'itemCount'}; - $infos{'author'} = $playlist->{'snippet'}->{'channelTitle'}; - $infos{'site'} = 'youtube'; - $infos{'url'} = 'https://www.youtube.com/playlist?list='.$id; + $infos{'author'} = $playlist->{'snippet'}->{'channelTitle'}; + $infos{'site'} = 'youtube'; + $infos{'url'} = 'https://www.youtube.com/playlist?list=' . $id; - $response = $ua->get($endpoint - .'/playlistItems?playlistId='.$id - .'&key='.$conf->{'youtube_api_key'} - .'&part=snippet'); - die($response->status_line) unless ($response->is_success); + $response = + $ua->get( $endpoint + . '/playlistItems?playlistId=' + . $id . '&key=' + . $conf->{'youtube_api_key'} + . '&part=snippet' ); + die( $response->status_line ) unless ( $response->is_success ); - $content = decode_json($response->decoded_content); + $content = decode_json( $response->decoded_content ); - die "empty playlist" if (not scalar @{ $content->{items} }); + die "empty playlist" if ( not scalar @{ $content->{items} } ); my @urls; - foreach my $subcontent (@{ $content->{items} }) - { + foreach my $subcontent ( @{ $content->{items} } ) { my $subid = $subcontent->{snippet}{resourceId}{videoId}; - push @urls, 'https://www.youtube.com/watch?v='.$subid; + push @urls, 'https://www.youtube.com/watch?v=' . $subid; } $infos{urls} = \@urls; - return %infos; + return %infos; } -sub get -{ +sub get { shift; - my $id = shift; - + my $id = shift; + my $ua = LWP::UserAgent->new( - timeout => 30, - env_proxy => 1, + timeout => 30, + env_proxy => 1, ); - my $response = $ua->get($endpoint - .'/videos?id='.$id - .'&key='.$conf->{'youtube_api_key'} - .'&part=snippet,contentDetails'); - die($response->status_line) unless ($response->is_success); + my $response = + $ua->get( $endpoint + . '/videos?id=' + . $id . '&key=' + . $conf->{'youtube_api_key'} + . '&part=snippet,contentDetails' ); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = decode_json( $response->decoded_content ); - my $content = decode_json($response->decoded_content); + die "video not found" if ( not scalar @{ $content->{items} } ); - die "video not found" if (not scalar @{ $content->{items} }); - my $video = $content->{'items'}->[0]; my %infos; $infos{'title'} = $video->{'snippet'}->{'title'}; - $video->{'contentDetails'}->{'duration'} =~ /PT((?<h>\d+)H)?((?<m>\d+)M)?((?<s>\d+)S)?/; + $video->{'contentDetails'}->{'duration'} =~ + /PT((?<h>\d+)H)?((?<m>\d+)M)?((?<s>\d+)S)?/; # default values my ($h) = $+{'h'} || 0; @@ -110,14 +114,14 @@ sub get my ($s) = $+{'s'} || 0; # there is one more second, don't know why - $infos{'duration'} = $h*3600 + $m*60 + $s - 1; + $infos{'duration'} = $h * 3600 + $m * 60 + $s - 1; - $infos{'author'} = $video->{'snippet'}->{'channelTitle'}; - $infos{'site'} = 'youtube'; - $infos{'url'} = 'https://www.youtube.com/watch?v='.$id; + $infos{'author'} = $video->{'snippet'}->{'channelTitle'}; + $infos{'site'} = 'youtube'; + $infos{'url'} = 'https://www.youtube.com/watch?v=' . $id; $infos{'external_id'} = $id; - return %infos; + return %infos; } 1; diff --git a/PlayBot/sites/zippy.pm b/PlayBot/sites/zippy.pm index e1d6d23..40fc508 100644 --- a/PlayBot/sites/zippy.pm +++ b/PlayBot/sites/zippy.pm @@ -8,71 +8,66 @@ use LWP::UserAgent; use HTML::Parser; use HTML::Entities; -my $inTitle = 0; +my $inTitle = 0; my $inAuthor = 0; my %infos; - -sub regex -{ +sub regex { return qr#((^|[^!])http://www[0-9]+.zippyshare.com/v/[0-9]+/file.html)#; } - sub get { shift; my $url = shift; - my $ua = LWP::UserAgent->new( - agent => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 GTB7.1", - timeout => 30, - env_proxy => 1, - ); - - my $response = $ua->get($url); - die($response->status_line) unless ($response->is_success); - - my $content = $response->decoded_content; - - my $parser = HTML::Parser->new(); - $parser->handler(text => \&parser_text, 'text'); - $parser->handler(start => \&parser_start, 'tagname'); - $parser->handler(end => \&parser_end, 'tagname'); - $parser->unbroken_text(1); - $parser->report_tags('title', 'a'); - $parser->parse($content); - $parser->eof(); - - $infos{'url'} = $url; - $infos{'author'} = undef; - $infos{'site'} = 'zippyshare'; - - return %infos; + my $ua = LWP::UserAgent->new( + agent => +"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 GTB7.1", + timeout => 30, + env_proxy => 1, + ); + + my $response = $ua->get($url); + die( $response->status_line ) unless ( $response->is_success ); + + my $content = $response->decoded_content; + + my $parser = HTML::Parser->new(); + $parser->handler( text => \&parser_text, 'text' ); + $parser->handler( start => \&parser_start, 'tagname' ); + $parser->handler( end => \&parser_end, 'tagname' ); + $parser->unbroken_text(1); + $parser->report_tags( 'title', 'a' ); + $parser->parse($content); + $parser->eof(); + + $infos{'url'} = $url; + $infos{'author'} = undef; + $infos{'site'} = 'zippyshare'; + + return %infos; } -sub parser_text -{ - my ($text) = @_; - chomp $text; - $text = decode_entities($text); - - if ($inTitle) { - $text =~ s/^Zippyshare.com - //; - $text =~ s/\.mp3$//; - $infos{'title'} = $text; - } +sub parser_text { + my ($text) = @_; + chomp $text; + $text = decode_entities($text); + + if ($inTitle) { + $text =~ s/^Zippyshare.com - //; + $text =~ s/\.mp3$//; + $infos{'title'} = $text; + } } -sub parser_start -{ - my ($tag) = @_; - $inTitle = 1 if ($tag eq 'title'); +sub parser_start { + my ($tag) = @_; + $inTitle = 1 if ( $tag eq 'title' ); } -sub parser_end -{ - my ($tag) = @_; - $inTitle = 0 if ($tag eq 'title'); +sub parser_end { + my ($tag) = @_; + $inTitle = 0 if ( $tag eq 'title' ); } 1; diff --git a/PlayBot/utils/Logging.pm b/PlayBot/utils/Logging.pm index 36e7038..c4ce8d9 100644 --- a/PlayBot/utils/Logging.pm +++ b/PlayBot/utils/Logging.pm @@ -11,545 +11,460 @@ use utf8; use Fcntl ':mode'; - # ### # new # Instancie la classe - un constructeur en somme # ### -sub new -{ - my $class = shift; - my $self = { - _file => shift, - _colored => 0, - _pending => 0, - _utf8 => 0, - _right_align => shift, - }; - - bless $self, $class; - - # On active la couleur que si on est sur un terminal - # C'est moche après pour les fichiers ou un less - if($self->file eq "STDOUT") - { - $self->{"_colored"} = 1 if((stat(STDOUT))[2] & S_IFCHR); - } - elsif($self->file eq "STDERR") - { - $self->{"_colored"} = 1 if((stat(STDERR))[2] & S_IFCHR); - } - else - { - $self->{"_colored"} = 1 if((stat($self->file))[2] & S_IFCHR); - } - - - unless(defined $self->{"_right_align"}) - { - $self->{"_right_align"} = 0; - } - - return $self; -} # Fin new - +sub new { + my $class = shift; + my $self = { + _file => shift, + _colored => 0, + _pending => 0, + _utf8 => 0, + _right_align => shift, + }; + + bless $self, $class; + + # On active la couleur que si on est sur un terminal + # C'est moche après pour les fichiers ou un less + if ( $self->file eq "STDOUT" ) { + $self->{"_colored"} = 1 if ( ( stat(STDOUT) )[2] & S_IFCHR ); + } + elsif ( $self->file eq "STDERR" ) { + $self->{"_colored"} = 1 if ( ( stat(STDERR) )[2] & S_IFCHR ); + } + else { + $self->{"_colored"} = 1 if ( ( stat( $self->file ) )[2] & S_IFCHR ); + } + + unless ( defined $self->{"_right_align"} ) { + $self->{"_right_align"} = 0; + } + + return $self; +} # Fin new # ### # file # Renvoie/maj $self->{'_file'} # ### -sub file -{ - my $self = shift; - $self->{"_file"} = $_[0] if(defined($_[0])); - return $self->{"_file"}; -} # Fin file - +sub file { + my $self = shift; + $self->{"_file"} = $_[0] if ( defined( $_[0] ) ); + return $self->{"_file"}; +} # Fin file # ### # colored # Renvoie/maj $self->{'_colored'} # ### -sub colored -{ - my $self = shift; - $self->{"_colored"} = $_[0] if(defined($_[0])); - return $self->{"_colored"}; -} # Fin colored - +sub colored { + my $self = shift; + $self->{"_colored"} = $_[0] if ( defined( $_[0] ) ); + return $self->{"_colored"}; +} # Fin colored # ### # pending # Renvoie/maj $self->{'_pending'} # ### -sub pending -{ - my $self = shift; - $self->{"_pending"} = $_[0] if(defined($_[0])); - return $self->{"_pending"}; -} # Fin pending - +sub pending { + my $self = shift; + $self->{"_pending"} = $_[0] if ( defined( $_[0] ) ); + return $self->{"_pending"}; +} # Fin pending # ### # utf8 # Renvoie/maj $self->{"_utf8"} # ### -sub utf8 -{ - my $self = shift; - $self->{"_utf8"} = $_[0] if(defined($_[0])); - return $self->{"_utf8"}; -} # Fin utf8 - +sub utf8 { + my $self = shift; + $self->{"_utf8"} = $_[0] if ( defined( $_[0] ) ); + return $self->{"_utf8"}; +} # Fin utf8 # ### # right_align # Renvoie/maj $self->{"_right_align"} # ### -sub right_align -{ - my $self = shift; - $self->{"_right_align"} = $_[0] if(defined($_[0])); - return $self->{"_right_align"}; -} # Fin right_align - +sub right_align { + my $self = shift; + $self->{"_right_align"} = $_[0] if ( defined( $_[0] ) ); + return $self->{"_right_align"}; +} # Fin right_align # ### # debug # Fonction gérant les logs du niveau debug (1) # ### -sub debug -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[36mDEBUG\e[0m:$parent:$text"; - } - else - { - $text = "DEBUG:$parent:$text"; - } - - return $self->print_in_file($text, $self->DEBUG); -} # Fin debug +sub debug { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + if ( $self->colored ) { + $text = "\e[36mDEBUG\e[0m:$parent:$text"; + } + else { + $text = "DEBUG:$parent:$text"; + } + + return $self->print_in_file( $text, $self->DEBUG ); +} # Fin debug # ### # pending_debug # Fonction gérant les logs du niveau debug (1) # ### -sub pending_debug -{ - my ($self, $text) = @_; - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[36mDEBUG\e[0m:$parent:$text"; - } - else - { - $text = "DEBUG:$parent:$text"; - } - - return $self->pending_in_file($text, $self->DEBUG); -} # Fin pending_debug +sub pending_debug { + my ( $self, $text ) = @_; + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + if ( $self->colored ) { + $text = "\e[36mDEBUG\e[0m:$parent:$text"; + } + else { + $text = "DEBUG:$parent:$text"; + } + + return $self->pending_in_file( $text, $self->DEBUG ); +} # Fin pending_debug # ### # info # Fonction gérant les logs du niveau info (2) # ### -sub info -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[33;1mINFO\e[0m:$parent:$text"; - } - else - { - $text = "INFO:$parent:$text"; - } - - return $self->print_in_file($text, $self->INFO); -} # Fin info +sub info { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + if ( $self->colored ) { + $text = "\e[33;1mINFO\e[0m:$parent:$text"; + } + else { + $text = "INFO:$parent:$text"; + } + + return $self->print_in_file( $text, $self->INFO ); +} # Fin info # ### # pending_info # Fonction gérant les logs du niveau info (2) # ### -sub pending_info -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[33;1mINFO\e[0m:$parent:$text"; - } - else - { - $text = "INFO:$parent:$text"; - } - - return $self->pending_in_file($text, $self->INFO); -} # Fin pending_info +sub pending_info { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + if ( $self->colored ) { + $text = "\e[33;1mINFO\e[0m:$parent:$text"; + } + else { + $text = "INFO:$parent:$text"; + } + + return $self->pending_in_file( $text, $self->INFO ); +} # Fin pending_info # ### # warning # Fonction gérant les logs du niveau warning (3) # ### -sub warning -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[33mWARNING\e[0m:$parent:$text"; - } - else - { - $text = "WARNING:$parent:$text"; - } - - return $self->print_in_file($text, $self->WARNING); -} # Fin warning +sub warning { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + if ( $self->colored ) { + $text = "\e[33mWARNING\e[0m:$parent:$text"; + } + else { + $text = "WARNING:$parent:$text"; + } + + return $self->print_in_file( $text, $self->WARNING ); +} # Fin warning # ### # pending_warning # Fonction gérant les logs du niveau warning (3) # ### -sub pending_warning -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[33mWARNING\e[0m:$parent:$text"; - } - else - { - $text = "WARNING:$parent:$text"; - } - - return $self->pending_in_file($text, $self->WARNING); -} # Fin pending_warning +sub pending_warning { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + + if ( $self->colored ) { + $text = "\e[33mWARNING\e[0m:$parent:$text"; + } + else { + $text = "WARNING:$parent:$text"; + } + + return $self->pending_in_file( $text, $self->WARNING ); +} # Fin pending_warning # ### # error # Fonction gérant les logs du niveau error (4) # ### -sub error -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[31mERROR\e[0m:$parent:$text"; - } - else - { - $text = "ERROR:$parent:$text"; - } - - return $self->print_in_file($text, $self->ERROR); -} # Fin error +sub error { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + + if ( $self->colored ) { + $text = "\e[31mERROR\e[0m:$parent:$text"; + } + else { + $text = "ERROR:$parent:$text"; + } + + return $self->print_in_file( $text, $self->ERROR ); +} # Fin error # ### # pending_error # Fonction gérant les logs du niveau error (4) # ### -sub pending_error -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[31mERROR\e[0m:$parent:$text"; - } - else - { - $text = "ERROR:$parent:$text"; - } - - return $self->pending_in_file($text, $self->ERROR); -} # Fin pending_error +sub pending_error { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + + if ( $self->colored ) { + $text = "\e[31mERROR\e[0m:$parent:$text"; + } + else { + $text = "ERROR:$parent:$text"; + } + + return $self->pending_in_file( $text, $self->ERROR ); +} # Fin pending_error # ### # critical # Fonction gérant les logs du niveau critical (5) # ### -sub critical -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[31;1mCRITICAL\e[0m:$parent:$text"; - } - else - { - $text = "CRITICAL:$parent:$text"; - } - - return $self->print_in_file($text, $self->CRITICAL); -} # Fin critical +sub critical { + my ( $self, $text ) = @_; + return unless ( defined $text ); + + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + + if ( $self->colored ) { + $text = "\e[31;1mCRITICAL\e[0m:$parent:$text"; + } + else { + $text = "CRITICAL:$parent:$text"; + } + return $self->print_in_file( $text, $self->CRITICAL ); +} # Fin critical # ### # pending_critical # Fonction gérant les logs du niveau critical (5) # ### -sub pending_critical -{ - my ($self, $text) = @_; - return unless(defined $text); - - chomp $text; - - my $parent = ( caller(1) )[3]; - $parent = "" if(!defined($parent)); - - if($self->colored) - { - $text = "\e[31;1mCRITICAL\e[0m:$parent:$text"; - } - else - { - $text = "CRITICAL:$parent:$text"; - } - - return $self->pending_in_file($text, $self->CRITICAL); -} # Fin pending_critical +sub pending_critical { + my ( $self, $text ) = @_; + return unless ( defined $text ); + chomp $text; + + my $parent = ( caller(1) )[3]; + $parent = "" if ( !defined($parent) ); + + if ( $self->colored ) { + $text = "\e[31;1mCRITICAL\e[0m:$parent:$text"; + } + else { + $text = "CRITICAL:$parent:$text"; + } + + return $self->pending_in_file( $text, $self->CRITICAL ); +} # Fin pending_critical # ### # print_in_file # Écrit dans le fichier # ### -sub print_in_file -{ - my ($self, $text, $level) = @_; - return unless(defined $text); - - chomp $text; - $text = "[\e[32m" . (scalar localtime time) . "\e[0m] $text"; - - $self->end_pending(0, $level) if($self->pending); - - if($self->file eq "STDOUT") - { - print STDOUT $text."\n"; - } - elsif($self->file eq "STDERR") - { - print STDERR $text."\n"; - } - else - { - open LOG, ">>", $self->file or return 0; - print LOG $text."\n"; - close LOG; - - print $text."\n" if(defined($level) && $Config::debug >= $level); - } - - return 1; -} # Fin print_in_file +sub print_in_file { + my ( $self, $text, $level ) = @_; + return unless ( defined $text ); + + chomp $text; + $text = "[\e[32m" . ( scalar localtime time ) . "\e[0m] $text"; + + $self->end_pending( 0, $level ) if ( $self->pending ); + + if ( $self->file eq "STDOUT" ) { + print STDOUT $text . "\n"; + } + elsif ( $self->file eq "STDERR" ) { + print STDERR $text . "\n"; + } + else { + open LOG, ">>", $self->file or return 0; + print LOG $text . "\n"; + close LOG; + print $text. "\n" if ( defined($level) && $Config::debug >= $level ); + } + + return 1; +} # Fin print_in_file # ### # pending_in_file # Écrit dans le fichier en attendant de savoir si ça a réussi ou pas # ### -sub pending_in_file -{ - my ($self, $text, $level) = @_; - return unless(defined $text); - - chomp $text; - $text = "[" . (scalar localtime time) . "] $text"; - - if($self->file eq "STDOUT") - { - if($self->right_align) - { - printf STDOUT "%-90s", $text; - } - else - { - print STDOUT $text; - } - } - elsif($self->file eq "STDERR") - { - if($self->right_align) - { - printf STDERR "%-90s", $text; - } - else - { - print STDERR $text; - } - } - else - { - if($self->right_align) - { - open LOG, ">>", $self->file or return 0; - printf LOG "%-90s", $text; - close LOG; - - printf "%-90s", $text if(defined($level) && $Config::debug >= $level); - } - else - { - open LOG, ">>", $self->file or return 0; - print LOG $text; - close LOG; - - print $text if(defined($level) && $Config::debug >= $level); - } - } - - $self->pending(1); - - return 1; -} # Fin pending_in_file - +sub pending_in_file { + my ( $self, $text, $level ) = @_; + return unless ( defined $text ); + + chomp $text; + $text = "[" . ( scalar localtime time ) . "] $text"; + + if ( $self->file eq "STDOUT" ) { + if ( $self->right_align ) { + printf STDOUT "%-90s", $text; + } + else { + print STDOUT $text; + } + } + elsif ( $self->file eq "STDERR" ) { + if ( $self->right_align ) { + printf STDERR "%-90s", $text; + } + else { + print STDERR $text; + } + } + else { + if ( $self->right_align ) { + open LOG, ">>", $self->file or return 0; + printf LOG "%-90s", $text; + close LOG; + + printf "%-90s", $text + if ( defined($level) && $Config::debug >= $level ); + } + else { + open LOG, ">>", $self->file or return 0; + print LOG $text; + close LOG; + + print $text if ( defined($level) && $Config::debug >= $level ); + } + } + + $self->pending(1); + + return 1; +} # Fin pending_in_file # ### # end_pending # Écrit dans le fichier le résultat de l'attente # ### -sub end_pending -{ - my ($self, $done_or_error, $level) = @_; - - my $done = ""; - - if($done_or_error) - { - if($self->colored) - { - $done = sprintf "%c[32m Done ", 0x1B; - } - else - { - $done = sprintf " Done \n"; - } - - $done .= "☑" if($self->utf8); - } - else - { - if($self->colored) - { - $done = sprintf "%c[31m Error ", 0x1B; - } - else - { - $done = sprintf " Error \n"; - } - - $done .= "☒" if($self->utf8); - } - - $done .= "\e[0m\n" if($self->colored); - - - # À partir d'ici, $done peut vouloir dire que c'est bon, ou pas - if($self->file eq "STDOUT") - { - printf STDOUT $done; - } - elsif($self->file eq "STDERR") - { - printf STDERR $done; - } - else - { - open LOG, ">>", $self->file or return 0; - printf LOG $done; - close LOG; - - printf $done if(defined($level) && $Config::debug >= $level); - } - - - $self->pending(0); - - return 1; -} # Fin end_pending - +sub end_pending { + my ( $self, $done_or_error, $level ) = @_; + + my $done = ""; + + if ($done_or_error) { + if ( $self->colored ) { + $done = sprintf "%c[32m Done ", 0x1B; + } + else { + $done = sprintf " Done \n"; + } + + $done .= "☑" if ( $self->utf8 ); + } + else { + if ( $self->colored ) { + $done = sprintf "%c[31m Error ", 0x1B; + } + else { + $done = sprintf " Error \n"; + } + + $done .= "☒" if ( $self->utf8 ); + } + + $done .= "\e[0m\n" if ( $self->colored ); + + # À partir d'ici, $done peut vouloir dire que c'est bon, ou pas + if ( $self->file eq "STDOUT" ) { + printf STDOUT $done; + } + elsif ( $self->file eq "STDERR" ) { + printf STDERR $done; + } + else { + open LOG, ">>", $self->file or return 0; + printf LOG $done; + close LOG; + + printf $done if ( defined($level) && $Config::debug >= $level ); + } + + $self->pending(0); + + return 1; +} # Fin end_pending # # Fonctions pour récupérer les différents niveaux de debug # -sub DEBUG { return 3; } -sub INFO { return 2; } -sub WARNING { return 1; } -sub ERROR { return 0; } +sub DEBUG { return 3; } +sub INFO { return 2; } +sub WARNING { return 1; } +sub ERROR { return 0; } sub CRITICAL { return -1; } + # Pour ceux qui préfèrent utiliser des variables... our $DEBUG = 3; our $INFO = 2; @@ -557,49 +472,45 @@ our $WARNING = 1; our $ERROR = 0; our $CRITICAL = -1; our %LVL_NAME = ( - "DEBUG" => 3, - "INFO" => 2, - "WARNING" => 1, - "ERROR" => 0, - "CRITICAL" => -1 + "DEBUG" => 3, + "INFO" => 2, + "WARNING" => 1, + "ERROR" => 0, + "CRITICAL" => -1 ); # Et dans l'autre sens -sub LVL -{ - my ($self, $num) = @_; - - my %LVL = ( - 3 => "DEBUG", - 2 => "INFO", - 1 => "WARNING", - 0 => "ERROR", - "-1" => "CRITICAL" - ); - - return $LVL{$num}; +sub LVL { + my ( $self, $num ) = @_; + + my %LVL = ( + 3 => "DEBUG", + 2 => "INFO", + 1 => "WARNING", + 0 => "ERROR", + "-1" => "CRITICAL" + ); + + return $LVL{$num}; } our %LVL = ( - 3 => "DEBUG", - 2 => "INFO", - 1 => "WARNING", - 0 => "ERROR", - "-1" => "CRITICAL" + 3 => "DEBUG", + 2 => "INFO", + 1 => "WARNING", + 0 => "ERROR", + "-1" => "CRITICAL" ); - # ### # dbg # Imprime des infos de debug à l'écran (STDOUT) # ### -sub dbg -{ - my $self = shift; - - require Data::Dumper; - print Data::Dumper->Dump([$self], [qw(Logging)]); -} # Fin dbg +sub dbg { + my $self = shift; + require Data::Dumper; + print Data::Dumper->Dump( [$self], [qw(Logging)] ); +} # Fin dbg 1; diff --git a/PlayBot/utils/db.pm b/PlayBot/utils/db.pm index 6d74330..7436239 100644 --- a/PlayBot/utils/db.pm +++ b/PlayBot/utils/db.pm @@ -20,29 +20,37 @@ BEGIN { } sub main_session { - $dbh = get_new_session() if (not $dbh or not $dbh->ping); + $dbh = get_new_session() if ( not $dbh or not $dbh->ping ); return $dbh; } sub get_new_session { - my $dbh = DBI->connect('DBI:mysql:'.$conf->{'bdd'}.';host='.$conf->{'host'}.';mysql_enable_utf8mb4=1', $conf->{'user'}, $conf->{'passwd'}, { + my $dbh = DBI->connect( + 'DBI:mysql:' + . $conf->{'bdd'} + . ';host=' + . $conf->{'host'} + . ';mysql_enable_utf8mb4=1', + $conf->{'user'}, + $conf->{'passwd'}, + { RaiseError => 1, - AutoCommit => 0 - }) - or die("Couldn't connect to database: ".DBI->errstr); + AutoCommit => 0 + } + ) or die( "Couldn't connect to database: " . DBI->errstr ); - #$dbh->{'mysql_enable_utf8mb4'} = 1; + #$dbh->{'mysql_enable_utf8mb4'} = 1; #$dbh->do(qq{SET NAMES utf8;}); return $dbh; } sub set_filename { - my ($id, $file) = @_; + my ( $id, $file ) = @_; my $dbh = main_session(); - my $sth = $dbh->prepare('UPDATE playbot SET file = ? WHERE id = ?'); - die ("Couldn't prepare querie; aborting") unless (defined $sth); - $sth->execute($file, $id); + my $sth = $dbh->prepare('UPDATE playbot SET file = ? WHERE id = ?'); + die("Couldn't prepare querie; aborting") unless ( defined $sth ); + $sth->execute( $file, $id ); $dbh->commit; } diff --git a/PlayBot/utils/db/chan.pm b/PlayBot/utils/db/chan.pm index f185ac4..02985c7 100644 --- a/PlayBot/utils/db/chan.pm +++ b/PlayBot/utils/db/chan.pm @@ -9,50 +9,39 @@ use Moose; use PlayBot::utils::db; +has 'name' => ( is => 'ro', isa => 'Str' ); +has 'sites' => ( is => 'ro', isa => 'ArrayRef[Str]', writer => '_set_sites' ); -has 'name' => (is => 'ro', isa => 'Str'); -has 'sites' => (is => 'ro', isa => 'ArrayRef[Str]', writer => '_set_sites'); - - -around 'BUILDARGS' => sub -{ - my ($orig, $class, $name) = @_; +around 'BUILDARGS' => sub { + my ( $orig, $class, $name ) = @_; not $name and die "missing arg 'name'"; my $dbh = PlayBot::utils::db::main_session; - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' select sites from playbot_config where name = ? - '); + ' ); $sth->execute($name); my $sites; my $row = $sth->fetch; - if (not $row) - { - $sites = ['dailymotion', - 'mixcloud', - 'soundcloud', - 'youtube', - 'spotify', - 'deezer', - 'facebook']; - - $sth = $dbh->prepare(' + if ( not $row ) { + $sites = [ + 'dailymotion', 'mixcloud', 'soundcloud', 'youtube', + 'spotify', 'deezer', 'facebook' + ]; + + $sth = $dbh->prepare( ' insert into playbot_config (name, sites) values (?, ?) - '); - $sth->execute($name, encode_json($sites)); + ' ); + $sth->execute( $name, encode_json($sites) ); } - else - { - eval - { - $sites = decode_json($row->[0]); - }; + else { + eval { $sites = decode_json( $row->[0] ); }; $@ and $sites = []; } @@ -60,51 +49,43 @@ around 'BUILDARGS' => sub $dbh->commit; return $class->$orig( - name => $name, - sites => $sites, + name => $name, + sites => $sites, ); }; - -sub add_site -{ +sub add_site { my $self = shift; my $site = shift; - my @new_sites = (@{ $self->sites }, $site); + my @new_sites = ( @{ $self->sites }, $site ); - $self->_update_db(\@new_sites); - $self->_set_sites(\@new_sites); + $self->_update_db( \@new_sites ); + $self->_set_sites( \@new_sites ); } - -sub remove_site -{ +sub remove_site { my $self = shift; my $site = shift; my @new_sites = grep { $_ ne $site } @{ $self->sites }; - $self->_update_db(\@new_sites); - $self->_set_sites(\@new_sites); + $self->_update_db( \@new_sites ); + $self->_set_sites( \@new_sites ); } - -sub _update_db -{ - my $self = shift; +sub _update_db { + my $self = shift; my $sites = shift; my $dbh = PlayBot::utils::db::main_session; - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' update playbot_config set sites = ? - '); - $sth->execute(encode_json($sites)); + ' ); + $sth->execute( encode_json($sites) ); $dbh->commit; } - - 1; diff --git a/PlayBot/utils/db/get.pm b/PlayBot/utils/db/get.pm index 3da527d..209f100 100644 --- a/PlayBot/utils/db/get.pm +++ b/PlayBot/utils/db/get.pm @@ -9,35 +9,36 @@ use Moose; use PlayBot::utils::db; - has '_dbh' => ( - is => 'rw', - isa => 'HashRef', - init_arg => undef, - default => sub { state %h; return \%h; } + is => 'rw', + isa => 'HashRef', + init_arg => undef, + default => sub { state %h; return \%h; } ); has '_sth' => ( - is => 'rw', - isa => 'HashRef', - init_arg => undef, - default => sub { state %h; return \%h; } + is => 'rw', + isa => 'HashRef', + init_arg => undef, + default => sub { state %h; return \%h; } ); has '_queries' => ( - is => 'rw', - isa => 'HashRef', - init_arg => undef, - default => sub { state %h; return \%h; } + is => 'rw', + isa => 'HashRef', + init_arg => undef, + default => sub { state %h; return \%h; } ); sub get { - my ($self, $query) = @_; + my ( $self, $query ) = @_; my $chan = $query->chan; my $result; - if (defined $self->_queries->{$chan} and $self->_queries->{$chan} ~~ $query) { - if ($self->_queries->{$chan}->date < time - 3600*6) { + if ( defined $self->_queries->{$chan} + and $self->_queries->{$chan} ~~ $query ) + { + if ( $self->_queries->{$chan}->date < time - 3600 * 6 ) { $self->_clean($chan); $self->_init($query); $self->_queries->{$chan} = $query; @@ -53,28 +54,29 @@ sub get { $result = $self->_get_next($query); # if id was precised, we (and so the user) know there is no more results - $self->_clean($chan) if ($query->id >= 0); + $self->_clean($chan) if ( $query->id >= 0 ); return undef unless $result; my %content; - $content{'id'} = $result->[0]; - $content{'author'} = $result->[1]; - $content{'title'} = $result->[2]; - $content{'url'} = $result->[3]; - $content{'duration'} = $result->[4]; + $content{'id'} = $result->[0]; + $content{'author'} = $result->[1]; + $content{'title'} = $result->[2]; + $content{'url'} = $result->[3]; + $content{'duration'} = $result->[4]; $content{'external_id'} = $result->[5]; - $content{'site'} = $result->[6]; + $content{'site'} = $result->[6]; return \%content; } sub get_rows { - my ($self, $query) = @_; + my ( $self, $query ) = @_; my $dbh = PlayBot::utils::db::get_new_session(); - my ($request, @args) = $self->_prepare_request($query); + my ( $request, @args ) = $self->_prepare_request($query); - my $sth = $dbh->prepare('select count(*) from ('.$request.') as TGTGTG'); + my $sth = + $dbh->prepare( 'select count(*) from (' . $request . ') as TGTGTG' ); $sth->execute(@args); my $rows = $sth->fetch->[0]; @@ -86,20 +88,23 @@ sub get_rows { } sub make_view { - my ($self, $query) = @_; + my ( $self, $query ) = @_; my $dbh = PlayBot::utils::db::get_new_session(); $dbh->{AutoCommit} = 0; - my ($request, @args) = $self->_prepare_request($query); - my $view_name = join'', map +(0..9,'a'..'z','A'..'Z')[rand(10+26*2)], 1..32; - my $sth = $dbh->prepare('create view '.$view_name.' AS '.$request); + my ( $request, @args ) = $self->_prepare_request($query); + my $view_name = join '', + map +( 0 .. 9, 'a' .. 'z', 'A' .. 'Z' )[ rand( 10 + 26 * 2 ) ], 1 .. 32; + my $sth = $dbh->prepare( 'create view ' . $view_name . ' AS ' . $request ); $sth->execute(@args); - $dbh->do('create event clear'.$view_name.' + $dbh->do( + 'create event clear' . $view_name . ' on schedule at current_timestamp + interval 1 hour do - drop view '.$view_name); + drop view ' . $view_name + ); $dbh->commit; $dbh->disconnect; @@ -108,7 +113,7 @@ sub make_view { } sub _get_next { - my ($self, $query) = @_; + my ( $self, $query ) = @_; my $chan = $query->chan; my $result = $self->_sth->{$chan}->fetch(); @@ -119,9 +124,8 @@ sub _get_next { return undef; } -sub _clean -{ - my ($self, $chan) = @_; +sub _clean { + my ( $self, $chan ) = @_; # we take care of the db delete $self->_sth->{$chan}; @@ -132,121 +136,126 @@ sub _clean } sub _init { - my ($self, $query) = @_; + my ( $self, $query ) = @_; my $chan = $query->chan; - if (defined $self->_sth->{$chan}) { + if ( defined $self->_sth->{$chan} ) { $self->_sth->{$chan}->finish(); } - my ($request, @args) = $self->_prepare_request($query); + my ( $request, @args ) = $self->_prepare_request($query); my $sth = $self->_get_dbh($chan)->prepare($request); $sth->execute(@args); - $self->_sth->{$query->chan} = $sth; + $self->_sth->{ $query->chan } = $sth; } sub _prepare_request { - my ($self, $query) = @_; - + my ( $self, $query ) = @_; + my $req; my @args; my $words_sql; my @words_param; - if ($query->fts) { - @words_param = (join(' ', @{$query->words})); - $words_sql = 'match (sender, title) against (?)'; + if ( $query->fts ) { + @words_param = ( join( ' ', @{ $query->words } ) ); + $words_sql = 'match (sender, title) against (?)'; } else { - foreach (@{$query->words}) { - unshift @words_param, '%'.$_.'%'; + foreach ( @{ $query->words } ) { + unshift @words_param, '%' . $_ . '%'; } - foreach (@{$query->words}) { + foreach ( @{ $query->words } ) { $words_sql .= ' and ' if ($words_sql); $words_sql .= "concat(p.sender, ' ', p.title) like ?"; } } - if ($query->id >= 0) { - $req = 'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; + if ( $query->id >= 0 ) { + $req = +'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; $req .= ' from playbot p where id = ?'; - @args = ($query->id); - return ($req, @args); + @args = ( $query->id ); + return ( $req, @args ); } - if (@{$query->tags}) { + if ( @{ $query->tags } ) { my @where; - foreach my $tag (@{$query->tags}) { - unshift @where, 'p.id in (select pt.id from playbot_tags pt where pt.tag = ?)'; + foreach my $tag ( @{ $query->tags } ) { + unshift @where, + 'p.id in (select pt.id from playbot_tags pt where pt.tag = ?)'; } my $where = join ' and ' => @where; - if ($query->is_global) { - $req = 'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; - $req .= ' from playbot p where '.$where; - $req .= ' and '.$words_sql if ($words_sql); + if ( $query->is_global ) { + $req = +'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; + $req .= ' from playbot p where ' . $where; + $req .= ' and ' . $words_sql if ($words_sql); $req .= ' and p.playlist is false'; $req .= ' group by p.id'; - @args = (@{$query->tags}, @words_param); + @args = ( @{ $query->tags }, @words_param ); } else { - $req = 'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; + $req = +'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; $req .= ' from playbot p join playbot_chan pc on p.id = pc.content'; - $req .= ' where '.$where; - $req .= ' and '.$words_sql if ($words_sql); + $req .= ' where ' . $where; + $req .= ' and ' . $words_sql if ($words_sql); $req .= ' and p.playlist is false'; $req .= ' and pc.chan = ? group by p.id'; - @args = (@{$query->tags}, @words_param, $query->chan); + @args = ( @{ $query->tags }, @words_param, $query->chan ); } } else { - if ($query->is_global) { - $req = 'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; + if ( $query->is_global ) { + $req = +'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; $req .= ' from playbot p where'; - $req .= ' '.$words_sql.' and' if ($words_sql); + $req .= ' ' . $words_sql . ' and' if ($words_sql); $req .= ' p.playlist is false'; $req .= ' group by p.id'; @args = (@words_param); } else { - $req = 'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; + $req = +'select p.id, p.sender, p.title, p.url, p.duration, p.external_id, p.type'; $req .= ' from playbot p join playbot_chan pc on p.id = pc.content'; $req .= ' where pc.chan = ?'; - $req .= ' and '.$words_sql if ($words_sql); + $req .= ' and ' . $words_sql if ($words_sql); $req .= ' and p.playlist is false'; $req .= ' group by p.id'; - @args = ($query->chan, @words_param); + @args = ( $query->chan, @words_param ); } } - - if ($query->fts and $words_sql) { - $req .= ' order by '.$words_sql.' desc'; - push @args, @words_param; + if ( $query->fts and $words_sql ) { + $req .= ' order by ' . $words_sql . ' desc'; + push @args, @words_param; } else { $req .= ' order by rand()'; } - return ($req, @args); + return ( $req, @args ); } sub _get_dbh { - my ($self, $chan) = @_; + my ( $self, $chan ) = @_; - if (not defined $self->_dbh->{$chan} or - not $self->_dbh->{$chan}->ping - ) { + if ( not defined $self->_dbh->{$chan} + or not $self->_dbh->{$chan}->ping ) + { $self->_dbh->{$chan} = PlayBot::utils::db::get_new_session(); } diff --git a/PlayBot/utils/db/stats.pm b/PlayBot/utils/db/stats.pm index fbf6e94..d05d067 100644 --- a/PlayBot/utils/db/stats.pm +++ b/PlayBot/utils/db/stats.pm @@ -10,90 +10,86 @@ use List::Util qw( reduce ); use PlayBot::utils::db; - -has 'sender' => (is => 'ro', isa => 'Str'); -has 'chan' => (is => 'ro', isa => 'Str'); -has 'date' => (is => 'ro', isa => 'Str'); -has 'count' => (is => 'ro', isa => 'Int'); -has 'senders' => (is => 'ro', isa => 'HashRef[Str]'); -has 'channels' => (is => 'ro', isa => 'HashRef[Str]'); -has 'fav' => (is => 'ro', isa => 'Int'); - +has 'sender' => ( is => 'ro', isa => 'Str' ); +has 'chan' => ( is => 'ro', isa => 'Str' ); +has 'date' => ( is => 'ro', isa => 'Str' ); +has 'count' => ( is => 'ro', isa => 'Int' ); +has 'senders' => ( is => 'ro', isa => 'HashRef[Str]' ); +has 'channels' => ( is => 'ro', isa => 'HashRef[Str]' ); +has 'fav' => ( is => 'ro', isa => 'Int' ); around 'BUILDARGS' => sub { - my ($orig, $class, $id) = @_; + my ( $orig, $class, $id ) = @_; my $count = 0; my $sender; my $chan; my $date; - my $senders = {}; + my $senders = {}; my $channels = {}; my $dbh = PlayBot::utils::db::main_session; - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' select date, chan, sender_irc from playbot_chan where content = ? and chan like \'#%\' order by date - '); + ' ); $sth->execute($id); - while (my $row = $sth->fetch) { + while ( my $row = $sth->fetch ) { + # first entry - if (not $sender) { + if ( not $sender ) { $sender = $row->[2]; - $chan = $row->[1]; - $date = $row->[0]; + $chan = $row->[1]; + $date = $row->[0]; } - $senders->{$row->[2]}++; - $channels->{$row->[1]}++; + $senders->{ $row->[2] }++; + $channels->{ $row->[1] }++; $count++; } my $fav; - $sth = $dbh->prepare(' + $sth = $dbh->prepare( ' select count(*) from playbot_fav where id = ? - '); + ' ); $sth->execute($id); - while (my $row = $sth->fetch) { + while ( my $row = $sth->fetch ) { $fav++; } $dbh->commit; return $class->$orig( - count => $count, - sender => $sender, - chan => $chan, - date => $date, - senders => $senders, - channels => $channels, - fav => $fav, + count => $count, + sender => $sender, + chan => $chan, + date => $date, + senders => $senders, + channels => $channels, + fav => $fav, ); }; sub max_sender { my $self = shift; - my $max = reduce { - $self->senders->{$a} > $self->senders->{$b} ? $a : $b - } keys %{$self->senders}; + my $max = reduce { $self->senders->{$a} > $self->senders->{$b} ? $a : $b } + keys %{ $self->senders }; return $max; } sub max_channel { my $self = shift; - my $max = reduce { - $self->channels->{$a} > $self->channels->{$b} ? $a : $b - } keys %{$self->channels}; + my $max = reduce { $self->channels->{$a} > $self->channels->{$b} ? $a : $b } + keys %{ $self->channels }; return $max; } - 1; diff --git a/PlayBot/utils/id.pm b/PlayBot/utils/id.pm index a07913b..80f81f6 100644 --- a/PlayBot/utils/id.pm +++ b/PlayBot/utils/id.pm @@ -19,23 +19,27 @@ use Scalar::Util qw(looks_like_number); # The object used to communicate with the database and the loging object. # MUST BE SET before using any subrouting. -our $dbh; +our $dbh; our $log; # The public method. sub get { - my ($chan, $index) = @_; + my ( $chan, $index ) = @_; my $id; - if (!defined($index) or !length($index)) { - $id = _get_last_id ($chan); - } elsif (!looks_like_number($index)) { + if ( !defined($index) or !length($index) ) { + $id = _get_last_id($chan); + } + elsif ( !looks_like_number($index) ) { die "wrong index"; - } elsif ($index < 0) { - $id = _get_from_offset ($index, $chan); - } elsif (_test_if_exists ($index, $chan)) { + } + elsif ( $index < 0 ) { + $id = _get_from_offset( $index, $chan ); + } + elsif ( _test_if_exists( $index, $chan ) ) { $id = $index; - } else { + } + else { die "wrong index"; } @@ -43,11 +47,11 @@ sub get { } sub _get_from_offset { - my ($offset, $chan) = @_; - my $id = _get_last_id ($chan); + my ( $offset, $chan ) = @_; + my $id = _get_last_id($chan); - while ($offset < 0) { - my $sth = $dbh->prepare(' + while ( $offset < 0 ) { + my $sth = $dbh->prepare( ' SELECT content FROM playbot_chan WHERE date < (SELECT date @@ -63,13 +67,13 @@ sub _get_from_offset { ORDER BY date DESC LIMIT 1) ORDER BY date DESC - LIMIT 1'); - unless (defined $sth) { + LIMIT 1' ); + unless ( defined $sth ) { $log->error("Couldn't prepare querie; aborting"); return; - } - $sth->execute($id, $chan, $id, $chan) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + } + $sth->execute( $id, $chan, $id, $chan ) + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); my $content = $sth->fetch; return unless ($content); @@ -81,19 +85,19 @@ sub _get_from_offset { } sub _test_if_exists { - my ($index, $chan) = @_; + my ( $index, $chan ) = @_; my $sth; - $sth = $dbh->prepare(' + $sth = $dbh->prepare( ' SELECT content FROM playbot_chan WHERE content = ? LIMIT 1 - '); + ' ); $sth->execute($index) - or $log->error("Couldn't finish transaction: " . $dbh->errstr); + or $log->error( "Couldn't finish transaction: " . $dbh->errstr ); my $content = $sth->fetch; if ($content) { @@ -107,13 +111,13 @@ sub _test_if_exists { sub _get_last_id { my ($chan) = @_; - my $sth = $dbh->prepare(' + my $sth = $dbh->prepare( ' SELECT content FROM playbot_chan WHERE chan = ? AND date <= NOW() ORDER BY date DESC - LIMIT 1'); + LIMIT 1' ); $sth->execute($chan); return $sth->fetch->[0]; } diff --git a/PlayBot/utils/print.pm b/PlayBot/utils/print.pm index 05e6b96..db5c881 100644 --- a/PlayBot/utils/print.pm +++ b/PlayBot/utils/print.pm @@ -21,40 +21,37 @@ use IRC::Utils qw(YELLOW ORANGE GREEN NORMAL LIGHT_BLUE GREY); # returns : # - a string well formated -sub print -{ +sub print { my ($content) = @_; my $id = $content->{'id'}; + # BRUTALE - $id = 'BRUTALE' if ($id eq 9320); - - my $msg = YELLOW.'['.$id.'] '.GREEN.$content->{'title'}; - - if (defined $content->{'author'}) - { - $msg .= ' | '.$content->{'author'}; - } - - if (defined $content->{'duration'}) - { - my $h = int($content->{'duration'} / 3600); - my $m = int(($content->{'duration'} % 3600) / 60); - my $s = int(($content->{'duration'} % 3600) % 60); - - $msg .= LIGHT_BLUE.' ('; - $msg .= sprintf("%02d:", $h) if ($h > 0); - $msg .= sprintf("%02d:", $m); - $msg .= sprintf("%02d", $s); - $msg .= ')'.NORMAL; + $id = 'BRUTALE' if ( $id eq 9320 ); + + my $msg = YELLOW . '[' . $id . '] ' . GREEN . $content->{'title'}; + + if ( defined $content->{'author'} ) { + $msg .= ' | ' . $content->{'author'}; + } + + if ( defined $content->{'duration'} ) { + my $h = int( $content->{'duration'} / 3600 ); + my $m = int( ( $content->{'duration'} % 3600 ) / 60 ); + my $s = int( ( $content->{'duration'} % 3600 ) % 60 ); + + $msg .= LIGHT_BLUE . ' ('; + $msg .= sprintf( "%02d:", $h ) if ( $h > 0 ); + $msg .= sprintf( "%02d:", $m ); + $msg .= sprintf( "%02d", $s ); + $msg .= ')' . NORMAL; } - $msg .= ' => '.$content->{'url'} if (defined $content->{'url'}); + $msg .= ' => ' . $content->{'url'} if ( defined $content->{'url'} ); - if (defined $content->{'tags'}) - { - $msg .= ' '.ORANGE; - $msg .= join(' ', @{$content->{'tags'}}); + if ( defined $content->{'tags'} ) { + $msg .= ' ' . ORANGE; + $msg .= join( ' ', @{ $content->{'tags'} } ); } $msg .= GREY; @@ -62,54 +59,50 @@ sub print return $msg; } -sub stats -{ +sub stats { + # a utils::db::stats object; my $stats = shift; - my $line1; + my $line1; my $line2; my $line3; my $line4; - $line1 .= 'Posté la 1re fois par '.$stats->sender; - $line1 .= ' le '.$stats->date; - $line1 .= ' sur '.$stats->chan; - - if ($stats->count > 1) - { - my $senders_count = keys %{$stats->senders}; - my $channels_count = keys %{$stats->channels}; - - $line2 .= 'Posté '.$stats->count.' fois'; - $line2 .= ' par '.$senders_count.' personne'; - $line2 .= 's' if ($senders_count > 1); - $line2 .= ' sur '.$channels_count.' channel'; - $line2 .= 's' if ($channels_count > 1); - - my $max_sender_count = $stats->senders->{$stats->max_sender}; - if ($max_sender_count > 1) - { - $line3 .= $stats->max_sender. " l'a posté "; - $line3 .= $max_sender_count. ' fois'; + $line1 .= 'Posté la 1re fois par ' . $stats->sender; + $line1 .= ' le ' . $stats->date; + $line1 .= ' sur ' . $stats->chan; + + if ( $stats->count > 1 ) { + my $senders_count = keys %{ $stats->senders }; + my $channels_count = keys %{ $stats->channels }; + + $line2 .= 'Posté ' . $stats->count . ' fois'; + $line2 .= ' par ' . $senders_count . ' personne'; + $line2 .= 's' if ( $senders_count > 1 ); + $line2 .= ' sur ' . $channels_count . ' channel'; + $line2 .= 's' if ( $channels_count > 1 ); + + my $max_sender_count = $stats->senders->{ $stats->max_sender }; + if ( $max_sender_count > 1 ) { + $line3 .= $stats->max_sender . " l'a posté "; + $line3 .= $max_sender_count . ' fois'; } - my $max_channel_count = $stats->channels->{$stats->max_channel}; - if ($max_channel_count != $stats->count and $max_channel_count > 1) - { - $line3 .= ' et ' if ($max_sender_count > 1); - $line3 .= 'il a été posté '.$max_channel_count; - $line3 .= ' fois sur '.$stats->max_channel; + my $max_channel_count = $stats->channels->{ $stats->max_channel }; + if ( $max_channel_count != $stats->count and $max_channel_count > 1 ) { + $line3 .= ' et ' if ( $max_sender_count > 1 ); + $line3 .= 'il a été posté ' . $max_channel_count; + $line3 .= ' fois sur ' . $stats->max_channel; } } - if ($stats->fav) - { + if ( $stats->fav ) { $line4 = "Sauvegardé dans ses favoris par "; - $line4 .= $stats->fav.' personne'; - $line4 .= 's' if ($stats->fav > 1); + $line4 .= $stats->fav . ' personne'; + $line4 .= 's' if ( $stats->fav > 1 ); } - return ($line1, $line2, $line3, $line4); + return ( $line1, $line2, $line3, $line4 ); } 1; diff --git a/tools/readjson.pl b/tools/readjson.pl index cbebe2e..630a2fc 100755 --- a/tools/readjson.pl +++ b/tools/readjson.pl @@ -8,8 +8,8 @@ use POE::Component::IKC::Client; use FindBin; POE::Component::IKC::Client->spawn( - unix => "$FindBin::Bin/../playbot.sock", - name => "client-$$", + unix => "$FindBin::Bin/../playbot.sock", + name => "client-$$", on_connect => \&on_connect ); @@ -32,10 +32,11 @@ sub on_start { # we 'slurp' stdin local $/; - my $json = <>; + my $json = <>; my $content = decode_json $json; print "$json\n"; - $kernel->post('IKC', 'post', 'poe://PlayBot/fbrecv/fbmsg', [ $content->{'author'}, $content->{'msg'} ]); - $kernel->post('IKC', 'shutdown'); + $kernel->post( 'IKC', 'post', 'poe://PlayBot/fbrecv/fbmsg', + [ $content->{'author'}, $content->{'msg'} ] ); + $kernel->post( 'IKC', 'shutdown' ); } diff --git a/tools/readmail.pl b/tools/readmail.pl index 88a87cf..9901c0e 100755 --- a/tools/readmail.pl +++ b/tools/readmail.pl @@ -8,16 +8,17 @@ use JSON; use File::Temp qw/ tempfile /; sub get_txt_path { - my $entity = shift; + my $entity = shift; my $num_parts = $entity->parts; if ($num_parts) { - foreach (1..$num_parts) { - return get_txt_path($entity->parts($_ - 1)); + foreach ( 1 .. $num_parts ) { + return get_txt_path( $entity->parts( $_ - 1 ) ); } - } else { + } + else { # we only want text - if ($entity->effective_type =~ /^text\/(?!(html|enriched))/) { + if ( $entity->effective_type =~ /^text\/(?!(html|enriched))/ ) { my $path = $entity->bodyhandle->path; return $path; } @@ -28,25 +29,28 @@ sub get_content { my $file = shift; my %content; my $uri = URI::Encode->new( { encode_reserved => 0 } ); - open (my $fh, "<", $file); + open( my $fh, "<", $file ); $content{'msg'} = ''; while (<$fh>) { if (/^(.*) posted in NightIIEs/) { $content{'author'} = $1; - } elsif (/^https:\/\/l.facebook.com\/l\/.*\/(.*)/) { - $content{'msg'} .= ' '.$uri->decode($1); - } elsif (/#/) { + } + elsif (/^https:\/\/l.facebook.com\/l\/.*\/(.*)/) { + $content{'msg'} .= ' ' . $uri->decode($1); + } + elsif (/#/) { chomp; - $content{'msg'} .= ' '.$_; + $content{'msg'} .= ' ' . $_; } } return \%content; } -my ($fh, $filename) = tempfile('playbot' . time . '_XXXX', UNLINK => 0, DIR => '/tmp'); +my ( $fh, $filename ) = + tempfile( 'playbot' . time . '_XXXX', UNLINK => 0, DIR => '/tmp' ); while (<STDIN>) { print $fh $_; } @@ -56,21 +60,25 @@ $parser->output_under('/tmp'); my $entity = $parser->parse_open($filename); my $txt_path = get_txt_path($entity); -my $content = get_content($txt_path); +my $content = get_content($txt_path); #remove_files($entity); my $json = encode_json $content; -pipe(READ,WRITE); -select((select(READ), $| = 1)[0]); +pipe( READ, WRITE ); +select( ( select(READ), $| = 1 )[0] ); + +if ( my $pid = fork ) { -if (my $pid = fork) { # parent # map READ to STDIN - open(STDIN, "<&READ"); - exec('ssh -i /usr/local/lib/playbot/key morignot2011@perso.iiens.net ./PlayBot/tools/readjson.pl'); -} else { + open( STDIN, "<&READ" ); + exec( +'ssh -i /usr/local/lib/playbot/key morignot2011@perso.iiens.net ./PlayBot/tools/readjson.pl' + ); +} +else { # child print WRITE "$json\n"; } -- GitLab