10 Commits
v1.0 ... master

13 changed files with 183 additions and 93 deletions

View File

@@ -1,3 +1,19 @@
#!/usr/bin/env perlcritic
# Задействованные модули критика:
#
# Perl::Critic::More
# Perl::Critic::Pulp
# Perl::Critic::TooMuchCode
# Perl::Critic::Lax
# Perl::Critic::CognitiveComplexity
# Perl::Critic::Policy::CompileTime
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::Dynamic::NoIndirect
# Perl::Critic::StricterSubs
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::CodeLayout::RequireUseUTF8
[-ControlStructures::ProhibitUnlessBlocks] [-ControlStructures::ProhibitUnlessBlocks]
# oh. c'mon. just a little bit # oh. c'mon. just a little bit
@@ -51,4 +67,26 @@
# just shut the fuck up # just shut the fuck up
[-Subroutines::ProhibitSubroutinePrototypes] [-Subroutines::ProhibitSubroutinePrototypes]
# i like it! # i like it!
[-TooMuchCode::ProhibitUnnecessaryUTF8Pragma]
[-CodeLayout::RequireUseUTF8]
[-Miscellanea::ProhibitUnrestrictedNoCritic]
[-Editor::RequireEmacsFileVariables]
[-CodeLayout::RequireASCII]
[-TooMuchCode::ProhibitDuplicateLiteral]
[-ErrorHandling::RequireUseOfExceptions]
[-ValuesAndExpressions::RequireConstantOnLeftSideOfEquality]
[-Lax::RequireConstantOnLeftSideOfEquality::ExceptEq]
[-Lax::ProhibitEmptyQuotes::ExceptAsFallback]
[-ValuesAndExpressions::RestrictLongStrings]

9
README
View File

@@ -9,7 +9,7 @@ aleesa-phrases
Механика работы Механика работы
----------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------
Сервис подписан на канал phrases. В этот канал пишет другой демоночек - aleesa-misc. А ещё aleesa-cron (чтобы фортунки Сервис подписан на канал phrases. В этот канал пишет другой демоночек - aleesa-misc. А ещё aleesa-cron (чтобы фортунки
по утрам рассылать) по утрам рассылать).
Ответ направляется в redis-канал, указанный в поле plugin входящего сообщения. Ответ направляется в redis-канал, указанный в поле plugin входящего сообщения.
@@ -32,6 +32,7 @@ aleesa-phrases
В каталоге contrib находится скрипт для alpine linux, системы инициализации openrc. Этот скрипт достаточно положить В В каталоге contrib находится скрипт для alpine linux, системы инициализации openrc. Этот скрипт достаточно положить В
/etc/init.d/aleesa-misc сконфигурить сервис по инструкции выше и после этого сервис запускается командой: /etc/init.d/aleesa-misc сконфигурить сервис по инструкции выше и после этого сервис запускается командой:
service aleesa-misc start service aleesa-phrases start
в автозагрузку его можно прописать через команду
rc-update add aleesa-misc default в автозагрузку его можно прописать через команду:
rc-update add aleesa-phrases default

View File

@@ -1,6 +1,6 @@
#!/usr/bin/perl #!/usr/bin/perl
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
@@ -29,9 +29,10 @@ no Cwd;
use Cwd::utf8 qw (chdir abs_path); use Cwd::utf8 qw (chdir abs_path);
use File::Basename qw (basename dirname); use File::Basename qw (basename dirname);
use File::Path qw (make_path); use File::Path qw (make_path);
use File::Spec qw ();
use Log::Any qw ($log); use Log::Any qw ($log);
use Log::Any::Adapter; use Log::Any::Adapter ();
use Log::Any::For::Std; use Log::Any::For::Std ();
use POSIX qw (setgid setuid setsid); use POSIX qw (setgid setuid setsid);
use Conf qw (LoadConf); use Conf qw (LoadConf);
@@ -70,8 +71,8 @@ if ($UID == 0) {
make_path ( make_path (
$piddir, { $piddir, {
uid => $uid, uid => $uid,
group => $gid group => $gid,
} },
); );
} }
@@ -82,8 +83,8 @@ if ($UID == 0) {
make_path ( make_path (
$logdir, { $logdir, {
uid => $uid, uid => $uid,
group => $gid group => $gid,
} },
) or die "Unable to create $logdir: $OS_ERROR\n"; ) or die "Unable to create $logdir: $OS_ERROR\n";
} }
} }
@@ -98,7 +99,7 @@ if ($UID == 0) {
if (defined $logfile) { if (defined $logfile) {
Log::Any::Adapter->set ('File', $logfile, log_level => $loglevel); Log::Any::Adapter->set ('File', $logfile, log_level => $loglevel);
} else { } else {
Log::Any::Adapter->set ('File', '/dev/null'); Log::Any::Adapter->set ('File', File::Spec->devnull);
} }
# По-умолчанию, демонизируемся, если явно не указано, что этого делать не надо # По-умолчанию, демонизируемся, если явно не указано, что этого делать не надо
@@ -114,7 +115,7 @@ my $apath = abs_path $PROGRAM_NAME;
unless (defined $apath) { unless (defined $apath) {
$log->fatal ("[FATAL] Unable to get abs_path: $OS_ERROR\n"); $log->fatal ("[FATAL] Unable to get abs_path: $OS_ERROR\n");
exit 1; exit 1;
}; }
my $pidfile = sprintf '%s/%s.pid', $piddir, basename $apath; my $pidfile = sprintf '%s/%s.pid', $piddir, basename $apath;
$log->info ("[INFO] Creating pidfile at $pidfile"); $log->info ("[INFO] Creating pidfile at $pidfile");
@@ -142,7 +143,7 @@ $PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::Re
# И запустим уже наш сервис # И запустим уже наш сервис
RunPhrases (); RunPhrases ();
if (-f $pidfile) { if (-e $pidfile) {
unlink $pidfile; unlink $pidfile;
} }
@@ -150,11 +151,11 @@ exit 0;
sub daemonize { sub daemonize {
__fork (); __fork ();
POSIX::setsid (); setsid ();
open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen) open STDIN, '<', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
# we handle STDOUT && STDERR via Log::Any::For::Std, so do not close them explicitly # we handle STDOUT && STDERR via Log::Any::For::Std, so do not close them explicitly
#open STDOUT, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen) #open STDOUT, '>', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
#open STDERR, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen) #open STDERR, '>', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
__fork (); __fork ();
umask 0; umask 0;
return; return;
@@ -178,7 +179,7 @@ sub __fork {
sub __signal_handler { sub __signal_handler {
$log->info ("[INFO] Caught a signal $OS_ERROR"); $log->info ("[INFO] Caught a signal $OS_ERROR");
if (-f $pidfile) { if (-e $pidfile) {
unlink $pidfile; unlink $pidfile;
} }

View File

@@ -1,6 +1,6 @@
#!/usr/bin/perl #!/usr/bin/perl
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;

View File

@@ -1,6 +1,6 @@
#!/usr/bin/perl #!/usr/bin/perl
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;

View File

@@ -1,6 +1,6 @@
#!/usr/bin/perl #!/usr/bin/perl
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;

View File

@@ -1,14 +1,17 @@
## no critic
requires 'Carp', '==1.50'; requires 'Carp', '==1.50';
requires 'Clone', '==0.45'; requires 'Clone', '==0.45';
requires 'CHI', '==0.61'; requires 'CHI', '==0.61';
requires 'CHI::Driver::BerkeleyDB', '==0.05' ; requires 'CHI::Driver::BerkeleyDB', '==0.05';
requires 'Cwd', '==3.75';
requires 'Cwd::utf8', '==0.011'; requires 'Cwd::utf8', '==0.011';
requires 'Data::Dumper', '==2.183'; requires 'Data::Dumper', '==2.183';
requires 'Encode', '==3.16'; requires 'Encode', '==3.16';
requires 'English', '==1.11'; requires 'English', '==1.11';
requires 'EV', '==4.33'; requires 'EV', '==4.33';
requires 'File::Basename', '0'; requires 'File::Basename', '==2.85';
requires 'File::Path', '==2.18'; requires 'File::Path', '==2.18';
requires 'File::Spec', '==3.75';
requires 'JSON', '==4.03'; requires 'JSON', '==4.03';
requires 'JSON::XS', '==4.03'; requires 'JSON::XS', '==4.03';
requires 'local::lib', '==2.000028'; requires 'local::lib', '==2.000028';
@@ -21,9 +24,9 @@ requires 'Mojo::IOLoop', '0';
requires 'Mojo::IOLoop::Signal', '==0.003'; requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'Mojo::Redis', '==3.27'; requires 'Mojo::Redis', '==3.27';
requires 'Mojo::Util', '0'; requires 'Mojo::Util', '0';
requires 'open', '0'; requires 'open', '==1.12';
requires 'POSIX', '0'; requires 'POSIX', '0';
requires 'Protocol::Redis::XS', '0'; requires 'Protocol::Redis::XS', '0';
requires 'SQLite_File', '==0.1006'; requires 'SQLite_File', '==0.1006';
requires 'utf8', '0'; requires 'utf8', '0';
requires 'version', '0'; requires 'version', '==0.9929';

View File

@@ -1,14 +1,13 @@
package Conf; package Conf;
# Загружает конфиг # Загружает конфиг файл
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use English qw ( -no_match_vars ); use English qw ( -no_match_vars );
use Encode qw (encode decode); use JSON::XS ();
use JSON::XS;
use version; our $VERSION = qw (1.0); use version; our $VERSION = qw (1.0);
use Exporter qw (import); use Exporter qw (import);
@@ -16,17 +15,26 @@ our @EXPORT_OK = qw (LoadConf);
sub LoadConf { sub LoadConf {
my $c = 'data/config.json'; my $c = 'data/config.json';
open my $CH, '<', $c or die "[FATAL] No conf at $c: $OS_ERROR\n"; my $CH;
my $json;
unless (open $CH, '<', $c) {
die "[FATAL] No conf at $c: $OS_ERROR\n";
}
my $len = (stat $c) [7]; my $len = (stat $c) [7];
my $json;
my $readlen = read $CH, $json, $len; my $readlen = read $CH, $json, $len;
$json = encode 'UTF-8', $json;
unless ($readlen) { unless ($readlen) {
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
die "[FATAL] Unable to read $c: $OS_ERROR\n"; die "[FATAL] Unable to read $c: $OS_ERROR\n";
} }
if ($readlen != $len) {
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
die "[FATAL] File $c is $len bytes on disk, but we read only $readlen bytes\n";
}
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
my $j = JSON::XS->new->utf8->relaxed; my $j = JSON::XS->new->utf8->relaxed;
return $j->decode ($json); return $j->decode ($json);

View File

@@ -1,17 +1,18 @@
package Fortune; package Fortune;
# Прокатят любые источники из fortune_mod. Текстовой файл с разделителем "\n%\n" мнжду фразами. # Прокатят любые источники из fortune_mod. Текстовой файл с разделителем "\n%\n" мнжду фразами.
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use Encode qw (decode);
use English qw ( -no_match_vars ); use English qw ( -no_match_vars );
use Carp qw (cluck croak); use Carp qw (croak);
use File::Path qw (make_path); use File::Path qw (make_path);
use Log::Any qw ($log); use Log::Any qw ($log);
use Math::Random::Secure qw (irand); use Math::Random::Secure qw (irand);
use SQLite_File; use SQLite_File ();
use Conf qw (LoadConf); use Conf qw (LoadConf);
@@ -30,7 +31,7 @@ sub Seed () {
my $backingfile = sprintf '%s/fortune.sqlite', $dir; my $backingfile = sprintf '%s/fortune.sqlite', $dir;
if (-f $backingfile) { if (-e $backingfile) {
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR"; unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR";
} }
@@ -41,7 +42,7 @@ sub Seed () {
while (my $fortunefile = readdir $srcdirhandle) { while (my $fortunefile = readdir $srcdirhandle) {
my $srcfile = sprintf '%s/%s', $srcdir, $fortunefile; my $srcfile = sprintf '%s/%s', $srcdir, $fortunefile;
unless (-f $srcfile) { unless (-e $srcfile) {
next; next;
} }
@@ -77,7 +78,7 @@ sub Fortune () {
my $phrase = $array[irand ($#array + 1)]; my $phrase = $array[irand ($#array + 1)];
# decode? # decode?
utf8::decode $phrase; $phrase = decode 'UTF-8', $phrase;
untie @array; untie @array;
return $phrase; return $phrase;
} }

View File

@@ -1,17 +1,18 @@
package Friday; package Friday;
# Данные модуля спёрты с https://raw.githubusercontent.com/isida/vi/master/data/friday.txt # Данные модуля спёрты с https://raw.githubusercontent.com/isida/vi/master/data/friday.txt
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use Encode qw (decode);
use English qw ( -no_match_vars ); use English qw ( -no_match_vars );
use Carp qw (cluck croak); use Carp qw (croak);
use File::Path qw (make_path); use File::Path qw (make_path);
use Log::Any qw ($log); use Log::Any qw ($log);
use Math::Random::Secure qw (irand); use Math::Random::Secure qw (irand);
use SQLite_File; use SQLite_File ();
use Conf qw (LoadConf); use Conf qw (LoadConf);
@@ -34,7 +35,7 @@ sub Seed () {
for (0..$#dow) { for (0..$#dow) {
my $backingfile = sprintf '%s/%s.sqlite', $dir, $dow[$_]; my $backingfile = sprintf '%s/%s.sqlite', $dir, $dow[$_];
if (-f $backingfile) { if (-e $backingfile) {
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR\n"; unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR\n";
} }
@@ -87,7 +88,7 @@ sub Friday () {
}; };
my $phrase = $array[irand ($#array + 1)]; my $phrase = $array[irand ($#array + 1)];
utf8::decode $phrase; $phrase = decode 'UTF-8', $phrase;
untie @array; untie @array;
return $phrase; return $phrase;
} }

View File

@@ -1,15 +1,15 @@
package Karma; package Karma;
# Хранит и выдаёт карму фразы
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use English qw ( -no_match_vars ); use English qw ( -no_match_vars );
use Carp qw (cluck); use CHI ();
use CHI; use CHI::Driver::BerkeleyDB ();
use CHI::Driver::BerkeleyDB;
use Log::Any qw ($log); use Log::Any qw ($log);
use Mojo::Util qw (trim); use Mojo::Util qw (trim);
@@ -23,22 +23,26 @@ my $c = LoadConf ();
my $cachedir = $c->{cachedir}; my $cachedir = $c->{cachedir};
my $max = 5; my $max = 5;
# swallow phrase and return answer
sub KarmaSet (@) { sub KarmaSet (@) {
my $chatid = shift; my $chatid = shift;
my $phrase = shift; my $phrase = shift;
my $action = shift; my $action = shift;
unless (defined $phrase) {
$phrase = '';
}
$phrase = trim ($phrase); $phrase = trim ($phrase);
if ((! defined $phrase) || $phrase eq '') { # Костылёк для кармы пустоты
if ($phrase eq '') {
$phrase = ' '; $phrase = ' ';
} }
my $cache = CHI->new ( my $cache = CHI->new (
driver => 'BerkeleyDB', driver => 'BerkeleyDB',
root_dir => $cachedir, root_dir => $cachedir,
namespace => __PACKAGE__ . '_' . $chatid namespace => __PACKAGE__ . '_' . $chatid,
); );
my $score = $cache->get ($phrase); my $score = $cache->get ($phrase);
@@ -81,16 +85,21 @@ sub KarmaGet (@) {
my $chatid = shift; my $chatid = shift;
my $phrase = shift; my $phrase = shift;
unless (defined $phrase) {
$phrase = '';
}
$phrase = trim ($phrase); $phrase = trim ($phrase);
if ((! defined $phrase) || $phrase eq '') { # Костылёк для кармы пустоты
if ($phrase eq '') {
$phrase = ' '; $phrase = ' ';
} }
my $cache = CHI->new ( my $cache = CHI->new (
driver => 'BerkeleyDB', driver => 'BerkeleyDB',
root_dir => $cachedir, root_dir => $cachedir,
namespace => __PACKAGE__ . '_' . $chatid namespace => __PACKAGE__ . '_' . $chatid,
); );
my $score = $cache->get ($phrase); my $score = $cache->get ($phrase);

View File

@@ -1,7 +1,7 @@
package Phrases; package Phrases;
# Общие модули - синтаксис, кодировки итд # Общие модули - синтаксис, кодировки итд
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
@@ -12,12 +12,12 @@ use Clone qw (clone);
use Log::Any qw ($log); use Log::Any qw ($log);
use Math::Random::Secure qw (irand); use Math::Random::Secure qw (irand);
# Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis # Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis
use Protocol::Redis::XS; use Protocol::Redis::XS ();
use Mojo::Redis; use Mojo::Redis ();
use Mojo::IOLoop; use Mojo::IOLoop ();
use Mojo::IOLoop::Signal; use Mojo::IOLoop::Signal ();
use Mojo::Util qw (trim); use Mojo::Util qw (trim);
use Data::Dumper; use Data::Dumper qw (Dumper);
use Conf qw (LoadConf); use Conf qw (LoadConf);
use Fortune qw (Fortune); use Fortune qw (Fortune);
@@ -67,11 +67,14 @@ my $parse_message = sub {
$answer->{misc}->{msg_format} = 0; $answer->{misc}->{msg_format} = 0;
} }
$answer->{userid} = 0 + $m->{userid};
$answer->{chatid} = 0 + $m->{chatid};
$log->debug ('[DEBUG] Incoming message ' . Dumper ($m)); $log->debug ('[DEBUG] Incoming message ' . Dumper ($m));
# Нормальная команда # Нормальная команда
if (substr ($m->{message}, 0, 1) eq $answer->{misc}->{csign}) { if (substr ($m->{message}, 0, length ($answer->{misc}->{csign})) eq $answer->{misc}->{csign}) {
my $cmd = substr ($m->{message}, 1); my $cmd = substr $m->{message}, length ($answer->{misc}->{csign});
if ($cmd eq 'friday' || $cmd eq 'пятница') { if ($cmd eq 'friday' || $cmd eq 'пятница') {
$reply = Friday (); $reply = Friday ();
@@ -94,36 +97,60 @@ my $parse_message = sub {
} else { } else {
$reply = trim (Fortune ()); $reply = trim (Fortune ());
} }
} elsif ($cmd =~ /^(karma|карма)\s(.+)/su) { } elsif (length ($cmd) >= length ('karma ') && substr ($cmd, 0, length ('karma ')) eq 'karma ') {
# TODO: избавиться от регулярки в пользу манипуляци со строкой через substr # По-умолчанию достаём карму пустоты
$reply = KarmaGet ($m->{chatid}, $2); my $text = undef;
if (length ($cmd) > length ('karma ')) {
$text = substr $cmd, length ('karma ');
}
$reply = KarmaGet ($m->{chatid}, $text);
} elsif (length ($cmd) >= length ('карма ') && substr ($cmd, 0, length ('карма ')) eq 'карма ') {
# По-умолчанию достаём карму пустоты
my $text = undef;
if (length ($cmd) > length ('карма ')) {
$text = substr $cmd, length ('карма ');
}
$reply = KarmaGet ($m->{chatid}, $text);
# Достаём карму пустоты :)
} elsif ($cmd eq 'karma') {
$reply = KarmaGet ($m->{chatid}, undef);
# Достаём карму пустоты :)
}elsif ($cmd eq 'карма') {
$reply = KarmaGet ($m->{chatid}, undef);
} }
# Скорее всего изменение кармы, но это не точно # Скорее всего изменение кармы, но это не точно
} elsif (substr ($m->{message}, -2) eq '++' || substr ($m->{message}, -2) eq '--') { } elsif (length ($m->{message}) > length ('++')) {
my @arr = split /\n/s, $m->{message}; if (substr ($m->{message}, 0 - length ('++')) eq '++' || substr ($m->{message}, 0 - length ('--')) eq '--') {
my @arr = split /\n/s, $m->{message};
# Предполагается, что фраза - это только одна строка # Предполагается, что фраза - это только одна строка
if ($#arr < 1) { if ($#arr < 1) {
$reply = KarmaSet ( $reply = KarmaSet (
$m->{chatid}, $m->{chatid},
trim (substr $m->{message}, 0, -2), trim (substr $m->{message}, 0, 0 - length ('++')),
substr $m->{message}, -2 substr $m->{message}, 0 - length ('++'),
); );
# Если у нас более одной строки - пусть с этим разбирается craniac, у него есть *мозги* # Если у нас более одной строки - пусть с этим разбирается craniac, у него есть *мозги*
} else { } else {
$send_to = 'craniac'; $send_to = 'craniac';
$reply = $m->{message}; $reply = $m->{message};
}
} }
} }
$log->debug ("[DEBUG] Sending message to channel $send_to " . Dumper ($answer));
if (defined $reply && $answer->{misc}->{answer}) { if (defined $reply && $answer->{misc}->{answer}) {
$answer->{message} = $reply; $answer->{message} = $reply;
$log->debug ("[DEBUG] Sending message to channel $send_to " . Dumper ($answer));
$self->json ($send_to)->notify ( $self->json ($send_to)->notify (
$send_to => $answer $send_to => $answer,
); );
} else {
$log->debug ('[DEBUG] No reply generated, skip sending message.');
} }
return; return;
@@ -133,7 +160,7 @@ my $__signal_handler = sub {
my ($self, $name) = @_; my ($self, $name) = @_;
$log->info ("[INFO] Caught a signal $name"); $log->info ("[INFO] Caught a signal $name");
if (defined $main::pidfile && -f $main::pidfile) { if (defined $main::pidfile && -e $main::pidfile) {
unlink $main::pidfile; unlink $main::pidfile;
} }
@@ -146,7 +173,7 @@ sub RunPhrases {
$log->info ("[INFO] Connecting to $c->{server}, $c->{port}"); $log->info ("[INFO] Connecting to $c->{server}, $c->{port}");
my $redis = Mojo::Redis->new ( my $redis = Mojo::Redis->new (
sprintf 'redis://%s:%s/1', $c->{server}, $c->{port} sprintf 'redis://%s:%s/1', $c->{server}, $c->{port},
); );
$log->info ('[INFO] Registering connection-event callback'); $log->info ('[INFO] Registering connection-event callback');
@@ -163,11 +190,11 @@ sub RunPhrases {
my ($conn, $error) = @_; my ($conn, $error) = @_;
$log->error ("[ERROR] Redis connection error: $error"); $log->error ("[ERROR] Redis connection error: $error");
return; return;
} },
); );
return; return;
} },
); );
my $pubsub = $redis->pubsub; my $pubsub = $redis->pubsub;
@@ -178,13 +205,13 @@ sub RunPhrases {
$log->debug ("[DEBUG] Subscribing to $channel"); $log->debug ("[DEBUG] Subscribing to $channel");
$sub->{$channel} = $pubsub->json ($channel)->listen ( $sub->{$channel} = $pubsub->json ($channel)->listen (
$channel => sub { $parse_message->(@_); } $channel => sub { $parse_message->(@_); },
); );
} }
Mojo::IOLoop::Signal->on ( Mojo::IOLoop::Signal->on (
TERM => $__signal_handler, TERM => $__signal_handler,
INT => $__signal_handler INT => $__signal_handler,
); );
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running; do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;

View File

@@ -1,18 +1,19 @@
package Proverb; package Proverb;
# Пословицы и поговорки # Пословицы и поговорки
use 5.018; use 5.018; ## no critic (ProhibitImplicitImport)
use strict; use strict;
use warnings; use warnings;
use utf8; use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use Encode qw (decode);
use English qw ( -no_match_vars ); use English qw ( -no_match_vars );
use Carp qw (cluck croak); use Carp qw (croak);
use File::Path qw (make_path); use File::Path qw (make_path);
use Log::Any qw ($log); use Log::Any qw ($log);
use Math::Random::Secure qw (irand); use Math::Random::Secure qw (irand);
use Mojo::Util qw (trim); use Mojo::Util qw (trim);
use SQLite_File; use SQLite_File ();
use Conf qw (LoadConf); use Conf qw (LoadConf);
@@ -31,7 +32,7 @@ sub Seed () {
my $backingfile = sprintf '%s/proverb.sqlite', $dir; my $backingfile = sprintf '%s/proverb.sqlite', $dir;
if (-f $backingfile) { if (-e $backingfile) {
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR"; unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR";
} }
@@ -41,7 +42,7 @@ sub Seed () {
while (my $proverbfile = readdir $srcdirhandle) { while (my $proverbfile = readdir $srcdirhandle) {
my $srcfile = sprintf '%s/%s', $srcdir, $proverbfile; my $srcfile = sprintf '%s/%s', $srcdir, $proverbfile;
unless (-f $srcfile) { unless (-e $srcfile) {
next; next;
} }
@@ -79,7 +80,7 @@ sub Proverb () {
my $phrase = $array[irand ($#array + 1)]; my $phrase = $array[irand ($#array + 1)];
# decode? # decode?
utf8::decode $phrase; $phrase = decode 'UTF-8', $phrase;
untie @array; untie @array;
return $phrase; return $phrase;
} }