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

Cible

Sélectionner le projet cible
  • morignot2011/playbot.old
  • defrance2011/playbot
2 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,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;
}
}
......@@ -77,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($_);
}
}
......
......@@ -2,25 +2,29 @@ package PlayBot::commands::fav;
use strict;
use warnings;
use utf8;
our $dbh;
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 );
}
}
......
......@@ -2,6 +2,7 @@ package PlayBot::commands::get;
use strict;
use warnings;
use utf8;
use PlayBot::utils::print;
use PlayBot::utils::db;
......@@ -13,112 +14,120 @@ 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 : ''
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 )
{
$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;
}
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'
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->[0]);
"
);
$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;
}
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 !~ /^#/) {
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' );
}
# 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->[0], $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->[0];
return $content->{id};
}
1;
......@@ -2,78 +2,85 @@ package PlayBot::commands::get::query;
use strict;
use warnings;
use utf8;
use Moose;
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,
);
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;
}
}
......@@ -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;
}
}
......@@ -93,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;
}
}
......@@ -122,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;
......@@ -2,25 +2,27 @@ package PlayBot::commands::later;
use strict;
use warnings;
use utf8;
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;
......@@ -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,126 +18,182 @@ 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 )
}
catch {
$irc->yield( privmsg => $chan => $insultes[ rand @insultes ] );
}
}
elsif ($msg =~ /^ *!later(?: (\S+))?(?: in (\d+)(h|m|s)?)? *$/) {
}
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)( +.*)?$/) {
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 =~ /^ *!stats(?: (\S+))? *$/) {
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]);
my $id = PlayBot::utils::id::get( $chan, $index );
PlayBot::commands::stats::exec( $chan, $id )
}
}
elsif ($msg =~ /^ *!conf +(.*)/) {
my @args = split(/ +/, $1);
PlayBot::commands::conf::exec($chan, $nick, @args);
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 => "---");
$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 =~ /^ *!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;
......@@ -147,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;
}
......
......@@ -2,6 +2,7 @@ package PlayBot::commands::stats;
use strict;
use warnings;
use utf8;
use PlayBot::utils::print;
use PlayBot::utils::db;
......@@ -9,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;
......@@ -2,32 +2,35 @@ package PlayBot::commands::tag;
use strict;
use warnings;
use utf8;
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 ) {
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: " . $@ );
}
}
......
......@@ -2,6 +2,7 @@ package PlayBot::sessions::downloader;
use strict;
use warnings;
use utf8;
use JSON;
use POE;
......@@ -9,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} = [];
......
......@@ -2,6 +2,7 @@ package PlayBot::sessions::downloader::ddl;
use strict;
use warnings;
use utf8;
use JSON;
use POE;
......@@ -10,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 {
......@@ -22,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;
}
......@@ -36,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;
}
......@@ -127,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($@);
......@@ -171,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] );
}
}
......
......@@ -7,13 +7,14 @@ package PlayBot::sessions::facebook;
use strict;
use warnings;
use utf8;
use POE;
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',
......@@ -21,7 +22,7 @@ POE::Component::IKC::Server->spawn(
);
POE::Session->create(
inline_states => {
inline_states => {
_start => \&on_start,
fbmsg => \&on_fbmsg
}
......@@ -30,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;
......@@ -2,6 +2,7 @@ package PlayBot::sessions::irc;
use strict;
use warnings;
use utf8;
use DBI;
use POE;
......@@ -14,33 +15,38 @@ 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);
my $log = PlayBot::utils::Logging->new( 'STDOUT', 1 );
local $/;
open CONF, '<', 'playbot.conf';
my $json = <CONF>;
my $conf = decode_json($json);
## CONNEXION
## 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 = 'IRC.iiens.net';
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;
......@@ -48,79 +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::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,144 +133,180 @@ sub bot_start {
my $kernel = $_[KERNEL];
$kernel->alias_set('bot');
$irc->yield(register => "all");
$irc->yield(
connect => {
Nick => $nick,
Username => $username,
Ircname => $ircname,
Server => $serveur,
Port => $port,
}
);
$log->info("register all");
$irc->yield( register => "all" );
$log->info("connecting");
$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');
setConf();
$irc->yield(privmsg => "NickServ" => "identify ".$conf->{'nickserv_pwd'}) unless ($debug);
$log->info('connected');
$irc->yield(
privmsg => "NickServ" => "identify " . $conf->{'nickserv_pwd'} )
unless ($debug);
foreach (@channels) {
$irc->yield(join => $_);
$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 external_parse {
my ( $user, $chan, $msg ) = @_;
$msg =~ tr/'"/_/;
my ($nick,$mask) = split(/!/,$user);
my %content;
my $content = `./PlayBot-cli '$chan' '$user' '$msg'`;
if ( $? >> 8 != 0 ) {
die "Error";
}
# first we check for url
my @processed_str = PlayBot::sites::parse(@args);
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,
);
}
# we remove any part processed (url and tags)
foreach (@processed_str) {
$msg =~ s/\Q$_\E// if $_;
# Quand un user parle
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
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);
}
# and we check for command
@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
{
my ($nick, $id, $chan_src) = @_;
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,11 +20,12 @@ use PlayBot::commands::parser;
our $irc;
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 $chan_conf = PlayBot::utils::db::chan->new($chan);
......@@ -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))
{
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 = $&;
......@@ -51,131 +59,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('
INSERT INTO playbot (type, url, sender, title, duration, playlist)
VALUES (?,?,?,?,?,?)
');
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$sth->execute(
$content->{'site'},
$content->{'url'},
$content->{'author'},
$content->{'title'},
$content->{'duration'},
$content->{'playlist'},
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},
$content->{playlist},
);
};
if ($@) {
# seems to be already present in database
# seems to be already present in database
$new = 0;
my $sth = $dbh->prepare('
UPDATE playbot playbot SET
my $sth = $dbh->prepare( '
UPDATE playbot SET
sender = ?,
title = ?,
duration = ?
duration = ?,
external_id = ?
WHERE url = ?
');
$log->error("Couldn't prepare querie; aborting") unless (defined $sth);
$sth->execute(
$content->{'author'},
$content->{'title'},
$content->{'duration'},
$content->{'url'},
' );
$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;
......@@ -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,34 +2,31 @@ 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;
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__
......
......@@ -2,6 +2,7 @@ package PlayBot::sites::deezer;
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
......@@ -10,36 +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{'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;
......@@ -2,6 +2,7 @@ package PlayBot::sites::facebook;
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
......@@ -18,39 +19,42 @@ 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 {
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;
return %infos;
}
......
......@@ -2,40 +2,39 @@ 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;
my $id = shift;
print "$id\n";
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;