Backbone/Service/JabberChat.pm untested

filter: Statementstmt 0.0% 0 / 149 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 228 CC 15 SCAR 24.3
CC
15
Cov
0%
got_group_message
42.0
_join_pending_groups
12.0
got_direct_message
12.0
CRAP 11.3
1 package Bot::Backbone::Service::JabberChat;
2 $Bot::Backbone::Service::JabberChat::VERSION = '0.142220';
3 use v5.10;
4 use Bot::Backbone::Service;
5  
6 with qw(
7 Bot::Backbone::Service::Role::Service
8 Bot::Backbone::Service::Role::Dispatch
9 Bot::Backbone::Service::Role::BareMetalChat
10 Bot::Backbone::Service::Role::GroupJoiner
11 );
12  
13 use Bot::Backbone::Message;
14 use AnyEvent::XMPP::Client;
15 use AnyEvent::XMPP::Ext::Disco;
16 use AnyEvent::XMPP::Ext::MUC;
17  
18 # ABSTRACT: Connect and chat with a Jabber server
19  
20  
21 has username => (
22 is => 'ro',
23 isa => 'Str',
24 required => 1,
25 );
26  
27  
28 has domain => (
29 is => 'ro',
30 isa => 'Str',
31 required => 1,
32 );
33  
34  
35 has group_domain => (
36 is => 'ro',
37 isa => 'Str',
38 required => 1,
39 lazy => 1,
40 default => sub {
41 my $self = shift;
42 return join '.', 'conference', $self->domain
43 },
44 );
45  
46  
47 has resource => (
48 is => 'ro',
49 isa => 'Str',
50 required => 1,
51 default => 'backbone-bot',
52 );
53  
54  
55 has password => (
56 is => 'ro',
57 isa => 'Str',
58 required => 1,
59 );
60  
61  
62 has host => (
63 is => 'ro',
64 isa => 'Str',
65 );
66  
67  
68 has port => (
69 is => 'ro',
70 isa => 'Int',
71 );
72  
73  
74 has connection_args => (
75 is => 'ro',
76 isa => 'HashRef',
77 );
78  
79  
80 has debug_client => (
81 is => 'ro',
82 isa => 'Bool',
83 required => 1,
84 default => 0,
85 );
86  
87  
88 has xmpp_debug_send_callback => (
89 is => 'ro',
90 isa => 'CodeRef',
91 predicate => 'has_xmpp_debug_send_callback',
92 );
93  
94 has xmpp_debug_recv_callback => (
95 is => 'ro',
96 isa => 'CodeRef',
97 predicate => 'has_xmpp_debug_recv_callback',
98 );
99  
100  
101 has xmpp_client => (
102 is => 'ro',
103 isa => 'AnyEvent::XMPP::Client',
104 required => 1,
105 lazy_build => 1,
106 );
107  
108 sub _build_xmpp_client {
109 my $self = shift;
110  
111 my $client = AnyEvent::XMPP::Client->new(
112 debug => $self->debug_client,
113 );
114  
115 for my $type (qw( send recv )) {
116 my $has_callback = "has_xmpp_debug_${type}_callback";
117 my $get_callback = "xmpp_debug_${type}_callback";
118  
119 if ($self->$has_callback) {
120 my $callback = $self->$get_callback;
121 $client->reg_cb(
122 "debug_$type" => sub {
123 my ($client, $acc, $data) = @_;
124 $callback->($self, $client, $acc, $data);
125 }
126 );
127 }
128 }
129  
130 return $client;
131 }
132  
133  
134 has xmpp_disco => (
135 is => 'ro',
136 isa => 'AnyEvent::XMPP::Ext::Disco',
137 required => 1,
138 lazy_build => 1,
139 );
140  
141 sub _build_xmpp_disco { AnyEvent::XMPP::Ext::Disco->new }
142  
143  
144 has xmpp_muc => (
145 is => 'ro',
146 isa => 'AnyEvent::XMPP::Ext::MUC',
147 required => 1,
148 lazy_build => 1,
149 );
150  
151 sub _build_xmpp_muc {
152 my $self = shift;
153 AnyEvent::XMPP::Ext::MUC->new( disco => $self->xmpp_disco );
154 }
155  
156  
157 has session_ready => (
158 is => 'rw',
159 isa => 'Bool',
160 required => 1,
161 default => 0,
162 );
163  
164  
165 has group_options => (
166 is => 'rw',
167 isa => 'ArrayRef[HashRef]',
168 required => 1,
169 default => sub { [] },
170 traits => [ 'Array' ],
171 handles => {
172 all_group_options => 'elements',
173 add_group_options => 'push',
174 },
175 );
176  
177  
178 has error_callback => (
179 is => 'rw',
180 isa => 'CodeRef',
181 lazy_build => 1,
182 );
183  
184 sub _build_error_callback {
185 return sub {
186 my ($self, $message) = @_;
187 warn "XMPP Error: ", $message, "\n";
188 }
189 }
190  
191  
192 sub jid {
193 my $self = shift;
194 return $self->username
195 . '@' . $self->domain
196 . '/' . $self->resource;
197 }
198  
199  
200 sub group_jid {
201 my ($self, $name) = @_;
202 return $name . '@' . $self->group_domain,
203 }
204  
205  
206 sub xmpp_account {
207 my $self = shift;
208 return $self->xmpp_client->get_account($self->jid);
209 }
210  
211  
212 sub xmpp_connection {
213 my $self = shift;
214 return $self->xmpp_account->connection;
215 }
216  
217  
218 sub xmpp_room {
219 my ($self, $name) = @_;
220 return $self->xmpp_muc->get_room(
221 $self->xmpp_connection,
222 $self->group_jid($name),
223 );
224 }
225  
226  
227 sub xmpp_contact {
228 my ($self, $name) = @_;
229 return $self->xmpp_connection->get_roster->get_contact($name);
230 }
231  
232  
233 sub initialize {
234 my $self = shift;
235  
236 # Make the connection
237 $self->xmpp_client->add_account(
238 $self->jid,
239 $self->password,
240 $self->host,
241 $self->port,
242 $self->connection_args,
243 );
244  
245 # TODO These messages should really verify that they are intended for us by
246 # checking that the account passed is the account expected. Otherwise, if
247 # someone were to setup multiple JabberChat connections using the same
248 # client (which we ought to expect), all JabberChats will react to all
249 # connections simultaneously... which is bad.
250  
251 # Register the IM message callback
252 $self->xmpp_client->reg_cb(
253 session_ready => sub {
254  
255 # Register the extensions we use
256 $self->xmpp_connection->add_extension($self->xmpp_disco);
257 $self->xmpp_connection->add_extension($self->xmpp_muc);
258  
259 $self->session_ready(1);
260 $self->_join_pending_groups;
261 },
262 message => sub { $self->got_direct_message(@_) },
263  
264 # TODO Need more robust logging
265 error => sub {
266 my ($client, $account, $error) = @_;
267 $self->error_callback->($self, $error->string);
268 },
269 );
270  
271 # Register the group message callback
272 $self->xmpp_muc->reg_cb(
273 message => sub { $self->got_group_message(@_) },
274 );
275  
276 # Start the client
277 $self->xmpp_client->start;
278 }
279  
280  
281 sub _join_pending_groups {
282 my $self = shift;
283  
284 # Perform join from either the params or list of group options
285 my @pending_group_options;
286 if (@_) {
287 @pending_group_options = @_;
288 }
289 else {
290 @pending_group_options = $self->all_group_options;
291 }
292  
293 my $account = $self->xmpp_account;
294 my $conn = $self->xmpp_connection;
295  
296 # Join each group requested
297 for my $group_options (@pending_group_options) {
298 my $nickname = $account->nickname_for_jid($self->jid);
299 $nickname = $group_options->{nickname}
300 if defined $group_options->{nickname};
301  
302 $self->xmpp_muc->join_room(
303 $conn,
304 $self->group_jid($group_options->{group}),
305 $nickname,
306 );
307 }
308 }
309  
310 sub join_group {
311 my ($self, $options) = @_;
312  
313 $self->add_group_options($options);
314 $self->_join_pending_groups($options) if $self->session_ready;
315 }
316  
317  
318 sub _identity_from_jid {
319 my ($self, $jid) = @_;
320  
321 my $contact = $self->xmpp_contact($jid);
322  
323 if (defined $contact) {
324 return Bot::Backbone::Identity->new(
325 username => $contact->jid,
326 nickname => $contact->name // $contact->jid,
327 me => $contact->is_me,
328 );
329 }
330 else {
331 return Bot::Backbone::Identity->new(
332 username => $jid,
333 nickname => $jid,
334 me => 0,
335 );
336 }
337 }
338  
339 sub got_direct_message {
340 my ($self, $client, $account, $xmpp_message) = @_;
341  
342 return unless defined $xmpp_message->body;
343  
344 my $to_contact = $self->xmpp_contact($xmpp_message->to);
345 my $from_contact = $self->xmpp_contact($xmpp_message->from);
346  
347 my $message = Bot::Backbone::Message->new({
348 chat => $self,
349 from => $self->_identity_from_jid($xmpp_message->to),
350 to => $self->_identity_from_jid($xmpp_message->from),
351 group => undef,
352 text => $xmpp_message->body,
353 });
354  
355 $self->resend_message($message);
356 if ($self->has_dispatcher) {
357 $self->dispatch_message($message);
358 }
359 }
360  
361  
362 sub is_to_me {
363 my ($self, $me_user, $text) = @_;
364  
365 my $me_nick = $me_user->nick;
366 return scalar($$text =~ s/^ $me_nick \s* [:,\-]
367 | , \s* $me_nick [.]? $
368 | , \s* $me_nick \s* ,
369 //x);
370 }
371  
372  
373 sub got_group_message {
374 my ($self, $client, $room, $xmpp_message, $is_echo) = @_;
375  
376 # Ignore messages echoed back to the bot
377 return if $is_echo;
378  
379 # Ignore messages from the room itself
380 return unless defined $xmpp_message->from_nick;
381  
382 # Ignore delayed messages (e.g., received as a replay of recent room discussion)
383 return if $xmpp_message->is_delayed;
384  
385 # Figure out which group this is
386 my $group_domain = $self->group_domain;
387 my $group = $room->jid;
388 $group =~ s/\@$group_domain$//;
389  
390 # Figure out who sent this message
391 my $from_user = $room->get_user($xmpp_message->from_nick);
392  
393 # Prefer the real JID as the username
394 my $from_username = $from_user->real_jid // $from_user->in_room_jid;
395 my $from_nickname = $from_user->nick;
396  
397 # This will never actually be true right now, but in case I decide
398 # handling echos is a good thing someday...
399 my $me_user = $room->get_me;
400 my $is_me = $me_user->in_room_jid eq $from_user->in_room_jid;
401  
402 # See if the group message is talking to us...
403 my $to_identity;
404 my $text = $xmpp_message->body;
405 if ($self->is_to_me($me_user, \$text)) {
406 $to_identity = Bot::Backbone::Identity->new(
407 username => $me_user->real_jid // $me_user->in_room_jid,
408 nickname => $me_user->nick,
409 me => 1,
410 );
411 }
412  
413 # Is this a message sent privately within the room?
414 my $private = $xmpp_message->is_private;
415 my $volume = $private ? 'whisper' : 'spoken';
416  
417 # Build the message
418 my $message = Bot::Backbone::Message->new({
419 chat => $self,
420 from => Bot::Backbone::Identity->new(
421 username => $from_username,
422 nickname => $from_nickname,
423 me => $is_me,
424 ),
425 to => $to_identity,
426 group => $group,
427 text => $text,
428 volume => $volume,
429 });
430  
431 # Pass it on
432 $self->resend_message($message);
433 $self->dispatch_message($message);
434 }
435  
436  
437 sub send_message {
438 my ($self, $params) = @_;
439  
440 my $to = $params->{to};
441 my $group = $params->{group};
442 my $text = $params->{text};
443 my $contact;
444  
445 # Select a group to receive the message
446 if (defined $group) {
447 $contact = $self->xmpp_room($group);
448 }
449  
450 # Select a contect to receive the message
451 else {
452 $contact = $self->xmpp_contact($to);
453 }
454  
455 unless (defined $contact) {
456 Carp::carp("JabberChat: no contact found for $to/$group to send $text\n");
457 return;
458 }
459  
460 $contact->make_message(body => $text)->send;
461 }
462  
463 __PACKAGE__->meta->make_immutable;
464  
465 __END__
466  
467 =pod
468  
469 =encoding UTF-8
470  
471 =head1 NAME
472  
473 Bot::Backbone::Service::JabberChat - Connect and chat with a Jabber server
474  
475 =head1 VERSION
476  
477 version 0.142220
478  
479 =head1 SYNOPSIS
480  
481 service jabber_chat => (
482 service => 'JabberChat',
483 username => 'bot',
484 domain => 'example.com',
485 resource => 'coolbot',
486 password => 'secret',
487 );
488  
489 =head1 DESCRIPTION
490  
491 Connects to and chats directly with other users and chat groups using a Jabber
492 (XMPP) server.
493  
494 =head1 ATTRIBUTES
495  
496 =head2 username
497  
498 This is the username (or localpart in XMPP parlance) to use when connecting to the Jabber server. E.g., if your bot's login name is C<bot@example.com>, the username is "bot".
499  
500 =head2 domain
501  
502 This is the domain (or domainpart) to use when connecting to the Jabber server. E.g., f your bot's login mame is C<bot@example.com>, the domain is "example.com".
503  
504 =head2 group_domain
505  
506 This is the domain to contact for group chats. Normally, this is the same as L</domain>, but with "conference." tacked on at the front.
507  
508 =head2 resource
509  
510 This is a the resourcepart of your login name. You may not really care what this is set to, but it shows up in some chat clients. By default it will be set to "backbone-bot", but you can set it something else, if you like.
511  
512 =head2 password
513  
514 This is the password to use when logging in to the Jabber server.
515  
516 =head2 host
517  
518 This is the host to contact to login. If not set, the L</domain> will be used.
519  
520 If you run your bot on Google Talk, you will probably want this set to L<talk.google.com>.
521  
522 =head2 port
523  
524 This is the port to connect. If you do not set it to anything, the default of 5222 will be used.
525  
526 =head2 connection_args
527  
528 These are additional connection arguments to pass to the XMPP connector. See
529 L<AnyEvent::XMPP::Connection> for a list of available options.
530  
531 =head2 debug_client
532  
533 Set to true if you want to enable debugging. This uses the built-in debug option
534 of L<AnyEvent::XMPP::Client>. If you want more control over how debugging is
535 handled, see L</xmpp_debug_recv_callback> and L</xmpp_debug_send_callback>.
536  
537 =head2 xmpp_debug_send_callback
538  
539 =head2 xmpp_debug_recv_callback
540  
541 These attributes may be set to a code reference that will be called with every
542 message received from the XMPP server. This could be useful for troubleshooting
543 certain kinds of problems in cases where you'd like more control over the output
544 than you get from L</debug>.
545  
546 Each will be called like this:
547  
548 $callback->($service, $xmpp_client, $account, $data);
549  
550 The C<$service> is this object. The C<$xmpp_client> will be the same object as
551 is returned by L</xmpp_client>. The C<$account> is the
552 L<AnyEvent::XMPP::Account> the bot has connected as (useful for getting the
553 jid). And the C<$data> is the raw XML being sent or received.
554  
555 =head2 xmpp_client
556  
557 This is the XMPP client object for organizing connections.
558  
559 =head2 xmpp_disco
560  
561 This is the XMPP discovery extension helper.
562  
563 =head2 xmpp_muc
564  
565 This is the XMPP multi-user chat extension helper.
566  
567 =head2 session_ready
568  
569 Once the connection has been made and is ready to start sending and receiving
570 messages, this will be set to true.
571  
572 =head2 group_options
573  
574 This is a list of multi-user chat groups the bot has joined or intends to join
575 once L</session_ready> becomes true.
576  
577 =head2 error_callback
578  
579 This callback is executed in case of an error. It will receive two arguments
580 like so:
581  
582 $callback->($service, $message);
583  
584 The first argument is the L<Bot::Backbone::Service::JabberChat> object and the
585 second is the error message the server sent. The default handler uses warn to
586 log the message to the console.
587  
588 =head1 METHODS
589  
590 =head2 jid
591  
592 This assembles a full JID (Jabber ID) using the L</username>, L</domain>, and
593 L</resource>.
594  
595 =head2 group_jid
596  
597 my $group_jid = $chat->group_jid('bar');
598  
599 Given a short group name, returns the bare JID for that group.
600  
601 =head2 xmpp_account
602  
603 Returns the XMPP account object.
604  
605 =head2 xmpp_connection
606  
607 Returns teh XMPP connection object.
608  
609 =head2 xmpp_room
610  
611 my $xmpp_room = $chat->xmpp_room('qux');
612  
613 Returns the XMPP room object for the named room.
614  
615 =head2 xmpp_contact
616  
617 my $xmpp_contact = $chat->xmpp_contact('user@example.com/blah');
618  
619 Given a JID, returns the XMPP contact object for that user.
620  
621 =head2 initialize
622  
623 Connects to the Jabber server and registers the events for receiving messages
624 from it.
625  
626 =head2 join_group
627  
628 Asks to join the named multi-user chat groups on the Jabber server. If L</session_ready> is false, the chat service will only record a desire to join the group. No actual join will take place. Once the session becomes ready, all pending groups will be joined.
629  
630 If the session is ready already, then the group will be joined immediately.
631  
632 =head1 EVENT HANDLERS
633  
634 =head2 got_direct_message
635  
636 Whenever someone sends the bot a direct message throught eh Jabber server, this
637 handler is called. It builds a L<Bot::Backbone::Message> and then passes that
638 message on the associated chat consumers and the dispatcher.
639  
640 =head2 is_to_me
641  
642 my $bool = $self->is_to_me($user, \$text);
643  
644 Given the user that identifies the bot in a group chat and text that was just
645 sent to the chat, this detects if the message was directed at the bot. Normally,
646 this includes messages that start with the following:
647  
648 nick: ...
649 nick, ...
650 nick- ...
651  
652 It also includes suffix references like this:
653  
654 ..., nick.
655 ..., nick
656  
657 and infix references like this:
658  
659 ..., nick, ...
660  
661 If you want something different, you may subclass service and override this
662 method.
663  
664 Note that the text is sent as a reference and can be modified, usually to remove
665 the nick from the message so the bot does not have to worry about that.
666  
667 =head2 got_group_message
668  
669 Whenever someone posts to a conference room that the bot has joined, this method
670 will be called to create a L<Bot::Backbone::Message> and pass that message on to
671 chat consumers and the dispatcher.
672  
673 =head2 send_message
674  
675 Sends a message to the Jabber server for a direct chat or group.
676  
677 =head1 AUTHOR
678  
679 Andrew Sterling Hanenkamp <hanenkamp@cpan.org>
680  
681 =head1 COPYRIGHT AND LICENSE
682  
683 This software is copyright (c) 2014 by Qubling Software LLC.
684  
685 This is free software; you can redistribute it and/or modify it under
686 the same terms as the Perl 5 programming language system itself.
687  
688 =cut