Skip to content
Extraits de code Groupes Projets

Comparer les révisions

Les modifications sont affichées comme si la révision source était fusionnée avec la révision cible. En savoir plus sur la comparaison des révisions.

Source

Sélectionner le projet cible
No results found
Sélectionner une révision Git
  • cinch
  • gh-pages
  • master
  • ruby
  • v1.0.0
5 résultats

Cible

Sélectionner le projet cible
  • morignot2011/playbot.old
  • defrance2011/playbot
2 résultats
Sélectionner une révision Git
  • cinch
  • gh-pages
  • master
  • ruby
4 résultats
Afficher les modifications
Validations sur la source (42)
Affichage de
avec 872 ajouts et 658 suppressions
#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use POE;
use PlayBot::sessions::irc;
use PlayBot::sessions::facebook;
#use PlayBot::sessions::facebook;
use PlayBot::sessions::downloader;
# Boucle des events
......
package PlayBot::commands::broken;
use strict;
use warnings;
use utf8;
use PlayBot::utils::db;
use PlayBot::utils::db::get;
use PlayBot::utils::print;
use Try::Tiny;
sub exec {
my ( $chan, $id ) = @_;
my $dbh = PlayBot::utils::db::main_session;
my $query = PlayBot::commands::get::query->new(
chan => $chan,
query => $id,
);
my $db_query = PlayBot::utils::db::get->new();
my $content = $db_query->get($query);
die("La cuillère n'existe pas\n") if ( not $content );
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};
eval "require $site";
my %h = $site->get( $content->{external_id} );
$content_r = \%h;
}
catch {
# mark as broken
# TODO: be more subtil
my $sth = $dbh->prepare( '
UPDATE playbot
SET broken = 1
WHERE type = ? AND 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} );
}
}
catch {
# the content needs an update
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},
);
$dbh->commit;
my $msg = PlayBot::utils::print::print($content);
die "Ça, c’est bon, c’est réparé\n$msg\n";
};
return "http://chezmoicamarche.org/";
}
1;
......@@ -2,8 +2,12 @@ package PlayBot::commands::conf;
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;
......@@ -11,25 +15,21 @@ use PlayBot::utils::db::chan;
our $irc;
sub exec
{
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))
{
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)
{
foreach ( keys %$sites ) {
$_ .= '*' if ( $sites->{$_} );
push @list, $_;
......@@ -37,39 +37,31 @@ sub exec
$msg = join( ' ', @list );
}
elsif ($cmd eq 'add')
{
elsif ( $cmd eq 'add' ) {
add( $chan, @args );
}
elsif ($cmd eq 'remove')
{
elsif ( $cmd eq 'remove' ) {
remove( $chan, @args );
}
else
{
else {
die;
}
$irc->yield( privmsg => $chan => $msg );
}
sub list
{
sub list {
my $chan = shift;
my $chan_conf = PlayBot::utils::db::chan->new($chan);
my $sites = {};
foreach my $site (__PACKAGE__->sites)
{
foreach my $site ( __PACKAGE__->sites ) {
$site = ( split( /::/, $site ) )[-1];
if (grep { $site eq $_ } @{ $chan_conf->sites })
{
if ( grep { $site eq $_ } @{ $chan_conf->sites } ) {
$sites->{$site} = 1;
}
else
{
else {
$sites->{$site} = 0;
}
}
......@@ -77,26 +69,20 @@ sub list
return $sites;
}
sub add
{
sub add {
my ( $chan, @sites ) = @_;
my $chan_conf = PlayBot::utils::db::chan->new($chan);
foreach (@sites)
{
foreach (@sites) {
$chan_conf->add_site($_);
}
}
sub remove
{
sub remove {
my ( $chan, @sites ) = @_;
my $chan_conf = PlayBot::utils::db::chan->new($chan);
foreach (@sites)
{
foreach (@sites) {
$chan_conf->remove_site($_);
}
}
......
......@@ -2,6 +2,7 @@ package PlayBot::commands::fav;
use strict;
use warnings;
use utf8;
our $dbh;
our $log;
......@@ -15,10 +16,13 @@ sub exec {
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.");
$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 (?, ?)');
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 );
}
......
......@@ -2,6 +2,7 @@ package PlayBot::commands::get;
use strict;
use warnings;
use utf8;
use PlayBot::utils::print;
use PlayBot::utils::db;
......@@ -13,11 +14,12 @@ our $irc;
our $log;
sub exec {
my ($chan, $msg, $chan_src) = @_;
my ( $fts, $chan, $msg, $chan_src ) = @_;
my $query = PlayBot::commands::get::query->new(
chan => $chan,
query => ($msg) ? $msg : ''
query => ($msg) ? $msg : '',
fts => $fts,
);
my $db_query = PlayBot::utils::db::get->new();
......@@ -29,7 +31,10 @@ sub exec {
and $rows > 10
and not $query->force )
{
$irc->yield(privmsg => $chan => "trop de résultats ($rows), utiliser -f pour forcer la recherche");
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"
);
return;
}
......@@ -37,6 +42,7 @@ sub exec {
if ( !$content ) {
if ( $rows > 0 ) {
# the request was already executed, there is nothing more
$irc->yield( privmsg => $chan => "Tu tournes en rond, Jack !" );
}
......@@ -44,10 +50,12 @@ sub exec {
$msg = "Je n'ai rien dans ce registre.";
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'
query => $query->query . ' -a',
fts => $fts,
);
my $rows = $db_query->get_rows($q);
......@@ -64,18 +72,21 @@ sub exec {
$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->[0]);
"
);
$sth->execute( $content->{id} );
my @tags;
while ( my $data = $sth->fetch ) {
......@@ -84,15 +95,9 @@ sub exec {
push @tags, $tag;
}
my %content_h;
$content_h{'id'} = $content->[0];
$content_h{'author'} = $content->[1];
$content_h{'title'} = $content->[2];
$content_h{'url'} = $content->[3];
$content_h{'duration'} = $content->[4];
$content_h{'tags'} = \@tags;
$content->{'tags'} = \@tags;
my $irc_msg = PlayBot::utils::print::print(\%content_h);
my $irc_msg = PlayBot::utils::print::print($content);
# if in query
if ( $chan !~ /^#/ ) {
......@@ -106,19 +111,23 @@ sub exec {
$irc->yield( privmsg => $chan => $irc_msg );
# BRUTALE
if ( $content->{'id'} eq 9320 ) {
$irc->yield( privmsg => $chan => 'BRUUUTALEEEEEEEEEEEEEE' );
}
# we save the get like a post
$sth = $dbh->prepare( '
INSERT INTO playbot_chan (content, chan, sender_irc)
VALUES (?,?,?)' );
$log->error("Couldn't prepare querie; aborting") unless ( defined $sth );
$sth->execute($content->[0], $chan, "PlayBot")
$sth->execute( $content->{id}, $chan, "PlayBot" )
or $log->error( "Couldn't finish transaction: " . $dbh->errstr );
$dbh->commit();
return $content->[0];
return $content->{id};
}
1;
......@@ -2,6 +2,7 @@ package PlayBot::commands::get::query;
use strict;
use warnings;
use utf8;
use Moose;
use overload '~~' => \&_equals;
......@@ -19,6 +20,12 @@ has 'chan' => (
required => 1
);
has 'fts' => (
is => 'ro',
isa => 'Bool',
required => 1,
);
has 'is_global' => (
is => 'ro',
isa => 'Bool',
......@@ -67,13 +74,13 @@ has 'date' => (
init_arg => undef,
);
sub _build_is_global {
my $self = shift;
if ( $self->chan !~ /^#/ || $self->query =~ /(^|\s)-a(ll)?($|\s)/ ) {
return 1;
} else {
}
else {
return 0;
}
}
......@@ -81,9 +88,11 @@ sub _build_is_global {
sub _build_force {
my $self = shift;
if ($self->chan !~ /^#/ || $self->query =~ /(^|\s)-f($|\s)/) {
if ( $self->fts || $self->chan !~ /^#/ || $self->query =~ /(^|\s)-f($|\s)/ )
{
return 1;
} else {
}
else {
return 0;
}
}
......@@ -112,7 +121,8 @@ sub _build_id {
if ( looks_like_number( $self->words->[0] ) ) {
return $self->words->[0];
} else {
}
else {
return -1;
}
}
......@@ -134,8 +144,7 @@ sub _equals {
return ( $self->is_global eq $query->is_global
and @tags1 ~~ @tags2
and @words1 ~~ @words2
and $self->id eq $query->id
);
and $self->id eq $query->id );
}
1;
......@@ -2,6 +2,7 @@ package PlayBot::commands::later;
use strict;
use warnings;
use utf8;
our $dbh;
our $log;
......@@ -12,7 +13,8 @@ sub exec {
$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 (?, ?, ?)');
my $sth = $dbh->prepare(
'INSERT INTO playbot_later (content, nick, date) VALUES (?, ?, ?)');
unless ( defined $sth ) {
$log->error("Couldn't prepare querie; aborting");
return;
......
......@@ -2,14 +2,15 @@ package PlayBot::commands::parser;
use strict;
use warnings;
use utf8;
use Try::Tiny;
use PlayBot::commands::conf;
use PlayBot::commands::stats;
use PlayBot::commands::fav;
use PlayBot::commands::later;
use PlayBot::commands::tag;
use PlayBot::commands::get;
use PlayBot::commands::broken;
use PlayBot::commands::stats;
use PlayBot::utils::id;
......@@ -17,7 +18,12 @@ 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;
......@@ -59,7 +65,8 @@ sub exec {
try {
my $id = PlayBot::utils::id::get( $chan, $index );
PlayBot::commands::fav::exec( $nick, $id )
} catch {
}
catch {
$irc->yield( privmsg => $chan => $insultes[ rand @insultes ] );
}
}
......@@ -69,8 +76,10 @@ sub exec {
try {
my $id = PlayBot::utils::id::get( $chan, $index );
PlayBot::commands::later::exec($kernel, $nick, $id, $chan, $time, $unit);
} catch {
PlayBot::commands::later::exec( $kernel, $nick, $id, $chan, $time,
$unit );
}
catch {
$irc->yield( privmsg => $chan => $insultes[ rand @insultes ] );
};
}
......@@ -89,51 +98,99 @@ sub exec {
try {
$id = PlayBot::utils::id::get( $chan, $index );
PlayBot::commands::tag::exec( $id, $tags );
} catch {
}
catch {
$irc->yield( privmsg => $chan => $insultes[ rand @insultes ] );
};
}
elsif ($msg =~ /^( *!get)( +.*)?$/) {
elsif ( $msg =~ /^ *!(get|fts)( +.*)?$/ ) {
my $query = $2;
my @args = ($chan, $query);
my $fts = $1 eq 'fts';
my @args = ( $fts, $chan, $query );
my $id = PlayBot::commands::get::exec(@args);
if ($id) {
$lastID->{$chan} = $id;
}
}
elsif ( $msg =~ /^ *!broken(?: (\S+))? *$/ ) {
my $index = $1;
try {
my $id = PlayBot::utils::id::get( $chan, $index );
my @msg;
try {
@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 ] );
};
}
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]);
}
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 => "!stats [<id>] : informations sur un contenu");
$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 =>
"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 =>
"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.");
$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 ] );
......
......@@ -2,6 +2,7 @@ package PlayBot::commands::stats;
use strict;
use warnings;
use utf8;
use PlayBot::utils::print;
use PlayBot::utils::db;
......@@ -9,7 +10,12 @@ 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 ) = @_;
......@@ -25,5 +31,4 @@ sub exec {
}
}
1;
......@@ -2,6 +2,7 @@ package PlayBot::commands::tag;
use strict;
use warnings;
use utf8;
our $dbh;
our $log;
......@@ -14,18 +15,20 @@ sub exec {
}
}
sub addTag
{
sub addTag {
my ( $id, $tag ) = @_;
# BRUTALE
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 );
eval {
$sth->execute($id, $tag)
};
eval { $sth->execute( $id, $tag ) };
if ($@) {
$log->error( "Couldn't finish transaction: " . $@ );
}
......
......@@ -2,6 +2,7 @@ package PlayBot::sessions::downloader;
use strict;
use warnings;
use utf8;
use JSON;
use POE;
......@@ -16,14 +17,14 @@ open CONF, '<', 'playbot.conf';
my $json = <CONF>;
my $conf = decode_json($json);
if ($conf->{download})
{
if ( $conf->{download} ) {
POE::Session->create(
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_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,
......@@ -32,7 +33,6 @@ if ($conf->{download})
);
}
sub on_start {
my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
$kernel->alias_set('downloader');
......
......@@ -2,6 +2,7 @@ package PlayBot::sessions::downloader::ddl;
use strict;
use warnings;
use utf8;
use JSON;
use POE;
......@@ -37,12 +38,9 @@ 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,
"youtube-dl", "--restrict-filename",
"--get-filename", "-o",
$conf->{save_format}, $url,
],
StdoutEvent => "filename",
StderrEvent => "devnull",
......@@ -57,6 +55,7 @@ sub exec {
# we link wheel id to playbot id
$heap->{ddl}->{wid}->{ $child->ID } = $id;
# we link PID to child object
$heap->{ddl}->{pid}->{ $child->PID } = $child;
}
......@@ -89,10 +88,8 @@ sub signal_filename {
# 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",
......@@ -105,6 +102,7 @@ sub signal_filename {
# we link wheel id to playbot id
$heap->{ddl}->{wid}->{ $child->ID } = $id;
# we link PID to child object
$heap->{ddl}->{pid}->{ $child->PID } = $child;
}
......@@ -119,7 +117,8 @@ sub signal_ddl {
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;
}
......@@ -140,6 +139,7 @@ sub signal_ddl {
# we link wheel id to playbot id
$heap->{ddl}->{wid}->{ $child->ID } = $id;
# we link PID to child object
$heap->{ddl}->{pid}->{ $child->PID } = $child;
}
......@@ -156,13 +156,15 @@ sub signal_move {
$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});
PlayBot::utils::db::set_filename( $id,
$heap->{ddl}->{pb}->{$id}->{filename} );
$kernel->yield( "end_task", $id );
};
if ($a) {
......@@ -180,10 +182,7 @@ sub rm {
my ( $kernel, $heap, $id, $filename ) = @_;
my $child = POE::Wheel::Run->new(
Program => [
"rm",
$filename
],
Program => [ "rm", $filename ],
StdoutEvent => "devnull",
StderrEvent => "devnull",
);
......@@ -194,6 +193,7 @@ sub rm {
# we link wheel id to playbot id
$heap->{ddl}->{wid}->{ $child->ID } = $id;
# we link PID to child object
$heap->{ddl}->{pid}->{ $child->PID } = $child;
}
......
......@@ -7,6 +7,7 @@ package PlayBot::sessions::facebook;
use strict;
use warnings;
use utf8;
use POE;
use POE::Component::IKC::Server;
......@@ -37,7 +38,10 @@ sub on_start {
sub on_fbmsg {
my ( $kernel, $args ) = @_[ KERNEL, ARG0 ];
$kernel->post('bot' => 'irc_public' => $args->[0], ['#nightiies.facebook'], $args->[1]);
$kernel->post(
'bot' => 'irc_public' => $args->[0],
['#nightiies.facebook'], $args->[1]
);
}
1;
......@@ -2,6 +2,7 @@ package PlayBot::sessions::irc;
use strict;
use warnings;
use utf8;
use DBI;
use POE;
......@@ -14,6 +15,7 @@ use Module::Reload;
use PlayBot::utils::Logging;
use PlayBot::sessions::irc::later;
use PlayBot::sites;
use PlayBot::sites::soundcloud;
use PlayBot::commands::parser;
my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 );
......@@ -25,15 +27,19 @@ 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'}, {
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);
}
) or die( "Couldn't connect to database: " . DBI->errstr );
# config
my $serveur = 'IRC.iiens.net';
my $serveur = '193.54.225.86';
my $nick = $conf->{'nick'};
my $port = 6667;
my $ircname = 'nightiies';
......@@ -65,18 +71,15 @@ POE::Session->create(
irc_notice => \&on_notice,
_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 );
### FONCTIONS
sub flux
{
sub flux {
my $kernel = $_[KERNEL];
my $date = strftime( "%Y-%m-%d", localtime( time - 3600 * 24 ) );
......@@ -86,22 +89,25 @@ sub flux
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);
$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);
$irc->yield( privmsg => $_ => $nbr
. ' liens aujourd\'hui : '
. $baseurl
. substr( $_, 1 ) . '/'
. $date );
}
}
$kernel->delay_set( '_flux', 3600 * 24 );
}
sub cycle
{
sub cycle {
my ($arg) = @_;
$log->info("refresh modules");
......@@ -111,16 +117,15 @@ sub cycle
setConf();
}
sub setConf
{
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'};
}
## GESTION EVENTS
# Au démarrage
......@@ -128,7 +133,9 @@ sub bot_start {
my $kernel = $_[KERNEL];
$kernel->alias_set('bot');
$log->info("register all");
$irc->yield( register => "all" );
$log->info("connecting");
$irc->yield(
connect => {
Nick => $nick,
......@@ -140,18 +147,18 @@ sub bot_start {
);
}
# A la connection
sub on_connect
{
sub on_connect {
my $kernel = $_[KERNEL];
setConf();
$irc->yield(privmsg => "NickServ" => "identify ".$conf->{'nickserv_pwd'}) unless ($debug);
$log->info('connected');
setConf();
$irc->yield(
privmsg => "NickServ" => "identify " . $conf->{'nickserv_pwd'} )
unless ($debug);
foreach (@channels) {
$irc->yield(join => $_);
$irc->delay( [ join => $_ ], 20 );
$log->info("join $_");
}
......@@ -161,10 +168,8 @@ sub on_connect
#$kernel->delay_set('_flux', (23-$hour)*3600 + (60-$min)*60);
}
# Discussion privée
sub on_query
{
sub on_query {
my ( $kernel, $user, $msg ) = @_[ KERNEL, ARG0, ARG2 ];
my ($nick) = split( /!/, $user );
......@@ -175,7 +180,8 @@ sub on_query
if ( $msg =~ m/^!/ && $nick eq $admin ) {
my $commande = ( $msg =~ m/^!([^ ]*)/ )[0];
my @params = grep {!/^\s*$/} split(/\s+/, substr($msg, length("!$commande")));
my @params = grep { !/^\s*$/ }
split( /\s+/, substr( $msg, length("!$commande") ) );
foreach ( keys(%commandes_admin) ) {
if ( $commande eq $_ ) {
......@@ -185,6 +191,7 @@ sub on_query
}
}
elsif ( $msg =~ /^PB/ ) {
# on vérifie si le nick est register
push( @nicksToVerify, $nick );
push( @codesToVerify, $msg );
......@@ -193,9 +200,7 @@ sub on_query
}
}
sub on_notice
{
sub on_notice {
my ( $user, $msg ) = @_[ ARG0, ARG2 ];
my ($nick) = split( /!/, $user );
......@@ -211,22 +216,28 @@ sub on_notice
push( @codesToVerify, $code );
}
elsif ( $msg =~ /isn't registered/ ) {
$irc->yield(privmsg => $nickToVerify => "Il faut que ton pseudo soit enregistré auprès de NickServ");
$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);
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);
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>');
$irc->yield( privmsg => $nickToVerify =>
'pour enregistrer un lien dans tes favoris : !fav <id>' );
}
else {
$irc->yield( privmsg => $nickToVerify => "Ce code n'existe pas" );
......@@ -235,8 +246,7 @@ sub on_notice
}
# Quand on m'invite, je join
sub on_invite
{
sub on_invite {
my ( $kernel, $user, $chan ) = @_[ KERNEL, ARG0, ARG1 ];
my ( $nick, $mask ) = split( /!/, $user );
......@@ -246,26 +256,57 @@ sub on_invite
push @channels, $chan;
}
sub external_parse {
my ( $user, $chan, $msg ) = @_;
$msg =~ tr/'"/_/;
my $content = `./PlayBot-cli '$chan' '$user' '$msg'`;
if ( $? >> 8 != 0 ) {
die "Error";
}
my ( $id, $external_id, $url, $title, $author, $duration ) =
split( /\n/, $content );
return (
id => $id,
author => $author,
external_id => $external_id,
duration => $duration,
playlist => 0,
site => 'soundcloud',
title => $title,
url => $url,
);
}
# Quand un user parle
sub on_speak
{
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;
eval {
%content = external_parse($nick, lc $chan->[0], $msg);
$irc->yield(
privmsg => $chan => PlayBot::utils::print::print(\%content) );
};
if ($@) {
# first we check for url
my @processed_str = PlayBot::sites::parse(@args);
# we remove any part processed (url and tags)
foreach (@processed_str) {
$msg =~ s/\Q$_\E// if $_;
}
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 );
}
else {
@args = ( $kernel, $user, lc $chan->[0], $msg );
}
PlayBot::commands::parser::exec(@args);
}
}
1;
......@@ -2,14 +2,14 @@ package PlayBot::sessions::irc::later;
use strict;
use warnings;
use utf8;
use PlayBot::commands::get;
sub consume
{
sub consume {
my ( $nick, $id, $chan_src ) = @_;
my @args = ($nick, $id, $chan_src);
my @args = ( 0, $nick, $id, $chan_src );
PlayBot::commands::get::exec(@args);
}
......
......@@ -2,8 +2,14 @@ package PlayBot::sites;
use strict;
use warnings;
use Module::Pluggable sub_name => 'sites', search_path => ['PlayBot::sites'], require => 1;
use utf8;
use LWP::UserAgent;
use JSON;
use Module::Pluggable
sub_name => 'sites',
search_path => ['PlayBot::sites'],
require => 1;
use Storable qw(dclone);
use PlayBot::utils::db;
......@@ -14,6 +20,7 @@ use PlayBot::commands::parser;
our $irc;
our $log;
our $regex;
our $playbot_api_key;
sub parse {
......@@ -28,19 +35,20 @@ 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 ) {
if ( not grep { $site eq "PlayBot::sites::$_" } @{ $chan_conf->sites } ) {
next;
}
my @args;
if (@args = ($msg =~ $site->regex))
{
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 = $&;
......@@ -56,14 +64,15 @@ sub parse {
}
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 );
......@@ -71,14 +80,10 @@ sub parse {
}
}
return (
$matching_url,
@matching_tags
);
return ( $matching_url, @matching_tags );
}
sub insert_content
{
sub insert_content {
my ( $kernel, $nick, $chan, $content, $msg, $playlist ) = @_;
my $dbh = PlayBot::utils::db::main_session();
my $id;
......@@ -89,38 +94,39 @@ sub insert_content
# insertion de la vidéo dans la bdd
eval {
my $sth = $dbh->prepare( '
INSERT INTO playbot (type, url, sender, title, duration, playlist)
VALUES (?,?,?,?,?,?)
INSERT INTO playbot (type, url, external_id, sender, title, duration, playlist)
VALUES (?,?,?,?,?,?,?)
' );
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$log->error("Couldn't prepare querie; aborting")
unless ( defined $sth );
$sth->execute(
$content->{'site'},
$content->{'url'},
$content->{'author'},
$content->{'title'},
$content->{'duration'},
$content->{'playlist'},
$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( '
UPDATE playbot playbot SET
UPDATE playbot SET
sender = ?,
title = ?,
duration = ?
duration = ?,
external_id = ?
WHERE url = ?
' );
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$log->error("Couldn't prepare querie; aborting")
unless ( defined $sth );
$sth->execute(
$content->{'author'},
$content->{'title'},
$content->{'duration'},
$content->{'url'},
$content->{author}, $content->{title},
$content->{duration}, $content->{external_id},
$content->{url},
);
}
......@@ -128,36 +134,37 @@ sub insert_content
my $sth = $dbh->prepare('SELECT id FROM playbot WHERE url = ?');
$log->error("Couldn't prepare querie; aborting") unless ( defined $sth );
$sth->execute($content->{'url'})
$sth->execute( $content->{url} )
or $log->error( "Couldn't finish transaction: " . $dbh->errstr );
$id = $sth->fetch->[0];
if (defined($playlist))
{
if ( defined($playlist) ) {
# save track in the playlist
$sth = $dbh->prepare( '
INSERT INTO playbot_playlist_content_association (playlist_id, content_id)
VALUES (?,?)' );
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$log->error("Couldn't prepare querie; aborting")
unless ( defined $sth );
eval {
$sth->execute( $playlist, $id );
$dbh->commit;
};
if ($@)
{
if ($@) {
# the association already exists
$dbh->rollback;
}
}
else
{
else {
# insertion du chan
$sth = $dbh->prepare( '
INSERT INTO playbot_chan (content, chan, sender_irc)
VALUES (?,?,?)' );
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$log->error("Couldn't prepare querie; aborting")
unless ( defined $sth );
$sth->execute( $id, $chan, $nick )
or $log->error( "Couldn't finish transaction: " . $dbh->errstr );
......@@ -168,11 +175,14 @@ sub insert_content
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 ) {
......@@ -183,21 +193,24 @@ 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;
$content->{id} = $id;
}
$content->{'tags'} = \@tags;
delete $content->{'url'};
$content->{tags} = \@tags;
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;
......
......@@ -2,16 +2,14 @@ package PlayBot::sites::dailymotion;
use strict;
use warnings;
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;
......@@ -29,7 +27,6 @@ sub get {
1;
__DATA__
__Python__
......
......@@ -2,6 +2,7 @@ package PlayBot::sites::deezer;
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
......@@ -10,8 +11,7 @@ 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_-]+)#;
}
......@@ -23,8 +23,7 @@ sub get {
timeout => 30,
env_proxy => 1,
);
my $response = $ua->get($endpoint
.$id);
my $response = $ua->get( $endpoint . $id );
die( $response->status_line ) unless ( $response->is_success );
my $content = decode_json( $response->decoded_content );
......@@ -38,6 +37,7 @@ sub get {
$infos{'site'} = 'deezer';
$infos{'url'} = 'https://www.deezer.com/track/' . $id;
$infos{'author'} = $content->{'artist'}->{'name'};
$infos{'external_id'} = $id;
return %infos;
}
......
......@@ -2,6 +2,7 @@ package PlayBot::sites::facebook;
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
......@@ -18,9 +19,9 @@ BEGIN {
$conf = decode_json($json);
}
sub regex
{
return qr#(?:^|[^!])https?://(?:www.)?facebook.com/(?: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 {
......@@ -31,9 +32,11 @@ sub get {
timeout => 30,
env_proxy => 1,
);
my $response = $ua->get($endpoint
my $response =
$ua->get( $endpoint
. $id
.'?access_token='.$conf->{'facebook_access_token'}
. '?access_token='
. $conf->{'facebook_access_token'}
. '&fields=title,from,permalink_url,length' );
die( $response->status_line ) unless ( $response->is_success );
......@@ -51,6 +54,7 @@ sub get {
$infos{'site'} = 'facebook';
$infos{'url'} = 'https://www.facebook.com' . $content->{'permalink_url'};
$infos{'author'} = $content->{'from'}->{'name'};
$infos{'external_id'} = $id;
return %infos;
}
......
......@@ -2,22 +2,21 @@ package PlayBot::sites::mixcloud;
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
use Encode;
sub regex
{
return qr#(^|[^!])https?://www.mixcloud.com/([a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+)#;
sub regex {
return qr#(?:^|[^!])https?://www.mixcloud.com/([\w-]+/[\w-]+)#;
}
sub get {
shift;
my $id = shift;
my $url = 'https://api.mixcloud.com/'.$2;
print "$id\n";
my $url = 'https://api.mixcloud.com/' . $id;
my $ua = LWP::UserAgent->new(
timeout => 30,
......