join the dots so server starts on reload_config
[scpubgit/Clifton.git] / lib / App / Clifton / Tower / IRC.pm
1 package App::Clifton::Tower::IRC;
2
3 use aliased 'Net::Async::IRC' => 'IRC_Client';
4 use aliased 'App::Clifton::Chain';
5 use Log::Contextual qw(:log);
6 use Moo;
7              
8 extends 'App::Clifton::Component';
9
10 has server => (is => 'ro', required => 1, weak_ref => 1);
11 has irc_server => (is => 'ro', required => 1);
12 has irc_nick => (is => 'ro', required => 1);
13 has irc_client => (is => 'lazy');
14 has chains => (is => 'ro', default => sub { {} });
15
16 sub _build_irc_client { shift->_new_child(IRC_Client, {}) }
17
18 sub BUILD {
19   my ($self, $args) = @_;
20   my $on_setup = $args->{on_setup};
21   $self->irc_client->configure(
22     on_message_text => $self->_replace_weakself('receive_irc_message')
23   );
24   $self->irc_client->login(
25     nick => $self->irc_nick, host => $self->irc_server,
26     on_login => $self->_capture_weakself(sub {
27       my $self = shift;
28       $self->server->irc_towers->{$self->irc_server}{$self->irc_nick}
29         = $self;
30       $on_setup->($self);
31     }),
32   );
33 }
34
35 sub start_chain {
36   my ($self, $args) = @_;
37   $self->irc_client->send_message('JOIN', undef, $args->{irc_channel});
38   my $new = $self->_new_child(Chain, {
39     %$args, irc_tower => $self,
40   });
41   $self->chains->{$args->{irc_channel}} = $new;
42   # I note here that actually we should make the Chain do
43   # setup (JOIN) and confirm that first, but oh well
44   $args->{on_finished}->({
45     chain => $new,
46     message => 'SUCCESS'
47   });
48 }
49
50 sub send_irc_message {
51   my ($self, $args) = @_;
52   $self->irc_client->send_message('PRIVMSG', undef, @{$args}{qw(to text)});
53 }
54
55 sub receive_irc_message {
56   my ($self, $message, $hints) = @_;
57   return if $hints->{prefix_is_me};
58   if (my $chain = $self->chains->{$hints->{target_name}}) {
59     $chain->handle_irc_message($message, $hints);
60   }
61 }
62
63 1;