7 Commits

4 changed files with 75 additions and 91 deletions

View File

@@ -14,8 +14,6 @@
# Perl::Critic::Policy::ProhibitImplicitImport
# Perl::Critic::Policy::CodeLayout::RequireUseUTF8
severity = 5
verbose = 8
# minorify some of warnings that are not really critical
[-InputOutput::RequireCheckedClose]
@@ -131,3 +129,5 @@ lib_sections = NAME | VERSION | DESCRIPTION | AUTHOR | LICENSE AND COPYRIGHT
max_length = 256
[-Miscellanea::ProhibitUnrestrictedNoCritic]
[-RegularExpressions::ProhibitFixedStringMatches]

View File

@@ -47,7 +47,10 @@ my $runAsUid = $UID;
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
my $C = LoadConf ();
my $loglevel = $C->{'loglevel'} // 'notice';
my $loglevel = 'notice';
$loglevel = $C->{'loglevel'} if defined $C->{'loglevel'};
my $logfile;
if (defined $C->{'log'}) {
@@ -136,6 +139,7 @@ close $MYPID; ## no critic (InputOutput::
# подстраховка на случай ядерной войны.
local $SIG{INT} = \&__signal_handler;
local $SIG{TERM} = \&__signal_handler;
local $SIG{QUIT} = \&__signal_handler;
# Поставим правильное имя процесса в proctitle
$PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars)
@@ -152,7 +156,7 @@ exit 0;
sub daemonize {
__fork ();
setsid ();
open STDIN, '<', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
open STDIN, '<', File::Spec->devnull; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
__fork ();
umask 0;
return;

View File

@@ -5,7 +5,6 @@ requires 'Cwd', '==3.75';
requires 'Cwd::utf8', '==0.011';
requires 'Data::Dumper', '==2.183';
requires 'Digest::SHA', '==6.02';
requires 'Encode', '==3.16';
# Part of perl
requires 'English', '0';
requires 'File::Basename', '==2.85';
@@ -18,15 +17,13 @@ requires 'Log::Any', '==1.710';
requires 'Log::Any::Adapter', '==1.710';
requires 'Log::Any::For::Std', '==0.05';
requires 'Math::Random::Secure', '==0.080001';
requires 'Mojolicious', '==9.24';
requires 'Mojolicious', '==9.26';
# Part of Mojolicious
requires 'Mojo::IOLoop', '0';
requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'Mojo::Redis', '==3.27';
requires 'Mojo::Redis', '==3.29';
# Part of perl
requires 'POSIX', '0';
# Buggy, latest version works, as pub-sub, but fails tests
requires 'Protocol::Redis::XS', '0';
requires 'Text::Fuzzy', '==0.29';
# Part of perl
requires 'utf8', '0';

View File

@@ -19,15 +19,12 @@ use English qw ( -no_match_vars );
# Модули для работы приложения
use Clone qw (clone);
use Data::Dumper qw (Dumper);
use Digest::SHA qw (sha1_base64);
use Encode qw (encode_utf8);
use Digest::SHA qw (sha256_hex);
use File::Spec ();
use Hailo ();
use Log::Any qw ($log);
use Mojo::IOLoop ();
use Mojo::IOLoop::Signal ();
# Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis
use Protocol::Redis::XS ();
use Mojo::Redis ();
use Math::Random::Secure qw (irand);
use Text::Fuzzy qw (distance_edits);
@@ -40,13 +37,16 @@ use Exporter qw (import);
our @EXPORT_OK = qw (RunCraniac);
sub RandomCommonPhrase ();
sub utf2sha1 ($);
sub fmatch (@);
sub brains (@);
sub RunCraniac ();
my $c = LoadConf ();
my $fwd_cnt = $c->{'forward_max'} // 5;
my $fwd_cnt = 5;
if (defined $c->{'forward_max'}) {
$fwd_cnt = $c->{'forward_max'};
}
my $hailo;
@@ -69,17 +69,6 @@ sub RandomCommonPhrase () {
return $myphrase[irand ($#myphrase + 1)];
}
sub utf2sha1 ($) {
my $string = shift;
if ($string eq '') {
return sha1_base64 '';
}
my $bytes = encode_utf8 $string;
return sha1_base64 $bytes;
}
sub fmatch (@) {
my $srcphrase = shift;
my $answer = shift;
@@ -97,30 +86,27 @@ sub fmatch (@) {
# Ленивая инициализация мозга. Создаём/открываем мозг только если нам надо "подумать" а не на каждую входящую фразу.
sub brains (@) {
my $chatid = shift;
my $telegram = shift // 0;
my $plugin = shift;
my $cid = shift;
unless (defined $hailo->{$chatid}) {
my $cid = $chatid;
unless (defined $hailo->{$cid}) {
my $brainname;
# Костыль, чтобы не портировать данные из телеграммных мозгов и не заниматься переименованием
unless ($telegram) {
$cid = utf2sha1 ($chatid);
$cid =~ s/\//-/xmsg;
$brainname = sprintf '%s/%s.sqlite', $c->{braindir}, $cid;
} else {
if ($plugin eq 'telegram') {
$brainname = sprintf '%s/%s.brain.sqlite', $c->{braindir}, $cid;
} else {
$brainname = sprintf '%s/%s.sqlite', $c->{braindir}, $cid;
}
$hailo->{$chatid} = eval {
$hailo->{$cid} = eval {
Hailo->new (
brain => $brainname,
order => 3,
);
};
if (defined $hailo->{$chatid}) {
if (defined $hailo->{$cid}) {
$log->info (sprintf '[INFO] Lazy init brain: %s', $brainname);
} else {
$log->error ("[ERROR] $EVAL_ERROR");
@@ -146,49 +132,49 @@ my $parse_message = sub {
my $reply;
if (defined $answer->{misc}) {
unless (defined $answer->{misc}->{answer}) {
$answer->{misc}->{answer} = 1;
}
unless (defined $answer->{misc}->{bot_nick}) {
$answer->{misc}->{bot_nick} = '';
}
unless (defined $answer->{misc}->{csign}) {
$answer->{misc}->{csign} = $c->{csign};
}
unless (defined $answer->{misc}->{fwd_cnt}) {
$answer->{misc}->{fwd_cnt} = 1;
} else {
if ($answer->{misc}->{fwd_cnt} > $fwd_cnt) {
$log->error ('[ERROR] Forward loop detected, discarding message.');
$log->debug (Dumper $m);
return;
} else {
$answer->{misc}->{fwd_cnt}++;
}
}
unless (defined $answer->{misc}->{good_morning}) {
$answer->{misc}->{good_morning} = 0;
}
unless (defined $answer->{misc}->{msg_format}) {
$answer->{misc}->{msg_format} = 0;
}
unless (defined $answer->{misc}->{username}) {
$answer->{misc}->{username} = 'user';
}
} else {
unless (defined $answer->{misc}->{answer}) {
$answer->{misc}->{answer} = 1;
}
unless (defined $answer->{misc}->{bot_nick}) {
$answer->{misc}->{bot_nick} = '';
}
unless (defined $answer->{misc}->{csign}) {
$answer->{misc}->{csign} = $c->{csign};
}
unless (defined $answer->{misc}->{fwd_cnt}) {
$answer->{misc}->{fwd_cnt} = 1;
} else {
if ($answer->{misc}->{fwd_cnt} > $fwd_cnt) {
$log->error ('[ERROR] Forward loop detected, discarding message.');
$log->debug (Dumper $m);
return;
} else {
$answer->{misc}->{fwd_cnt}++;
}
}
unless (defined $answer->{misc}->{good_morning}) {
$answer->{misc}->{good_morning} = 0;
}
unless (defined $answer->{misc}->{msg_format}) {
$answer->{misc}->{msg_format} = 0;
}
unless (defined $answer->{misc}->{username}) {
$answer->{misc}->{username} = 'user';
}
} else {
$answer->{misc}->{answer} = 1;
$answer->{misc}->{bot_nick} = '';
$answer->{misc}->{csign} = $c->{csign};
$answer->{misc}->{fwd_cnt} = 1;
$answer->{misc}->{good_morning} = 0;
$answer->{misc}->{msg_format} = 0;
$answer->{misc}->{username} = 'user';
}
my $csign = $answer->{misc}->{csign};
@@ -357,20 +343,21 @@ my $parse_message = sub {
}
}
# Попадаем сюда только если входящая фраза не распознана ранее как ключевая.
# Попадаем сюда только если входящая фраза не распознана ранее как ключевая.
my $cid;
if ($m->{plugin} eq 'telegram') {
$cid = $chatid;
} else {
$cid = sha256_hex (sprintf '%s/%s', $m->{plugin}, $chatid);
}
if ($m->{misc}->{answer}) {
# Пытаемся что-то генерировать, если фраза длиннее 3-х букв.
if (length ($m->{message}) > 3) {
my $telegram = 0;
# Костыль для совместимости со старым наименованием "мозгов".
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
# Lazy brain init
if (brains ($chatid, $telegram)) {
$reply = $hailo->{$chatid}->learn_reply ($m->{message});
if (brains ($m->{plugin}, $cid)) {
$reply = $hailo->{$cid}->learn_reply ($m->{message});
# Если из реактора вернулся undef выдаём "общую" фразу из словаря.
unless (defined $reply) {
@@ -397,14 +384,9 @@ my $parse_message = sub {
} else {
# Пытаемся что-то запоминать, если фраза длиннее 3-х букв
if (length ($m->{message}) > 3) {
my $telegram = 0;
if ($m->{plugin} eq 'telegram') {
$telegram = 1;
}
if (brains ($chatid, $telegram)) {
$hailo->{$chatid}->learn ($m->{message});
# Lazy brain init
if (brains ($m->{plugin}, $cid)) {
$hailo->{$cid}->learn ($m->{message});
}
}
}
@@ -468,6 +450,7 @@ sub RunCraniac () {
Mojo::IOLoop::Signal->on (TERM => $__signal_handler);
Mojo::IOLoop::Signal->on (INT => $__signal_handler);
Mojo::IOLoop::Signal->on (QUIT => $__signal_handler);
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;
return;