Mattermost/V4/Client.pm

filter: Statementstmt 46.4% 71 / 153 Branchbran 13.3% 4 / 30 Conditioncond 11.7% 2 / 17 MC/DCmcdc 10.0% 1 / 10 Subroutinesub 51.5% 17 / 33 Podpod 0.0% 0 / 3 totaltotal 38.6% 95 / 246 CC 24 SCAR 33.8
CC
24
Cov
38%
_on_message
132.0
_on_non_event
20.0
__ANON__
6.0
CRAP 29.3
« Mattermost/V4/API/Resource/Channel/Member.pm ↑ Summary Mattermost/V4/API/Resource/Channels.pm »
1 package WebService::Mattermost::V4::Client;
2  
3 # ABSTRACT: Perl websocket client for Mattermost.
4  
5 2 ▶use Encode 'encode';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Mojo::JSON qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use MooX::HandlesVia;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use Types::Standard qw(ArrayRef Bool InstanceOf Int Maybe Str);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 extends 'WebService::Mattermost';
13 2 with qw(
14 WebService::Mattermost::Role::Logger
15 WebService::Mattermost::Role::UserAgent
16 Role::EventEmitter
17 );
18  
19 ################################################################################
20  
21 2 has _events => (is => 'ro', isa => ArrayRef, lazy => 1, builder => 1);
22 2 has _ua => (is => 'rw', isa => InstanceOf['Mojo::UserAgent'], lazy => 1, builder => 1);
23 2 has ioloop => (is => 'rw', isa => InstanceOf['Mojo::IOLoop'], lazy => 1, builder => 1);
24 2 has websocket_url => (is => 'ro', isa => Str, lazy => 1, builder => 1);
25  
26 2 has ws => (is => 'rw', isa => Maybe[InstanceOf['Mojo::Base']]);
27  
28 2 has debug => (is => 'ro', isa => Bool, default => 0);
29 2 has ignore_self => (is => 'ro', isa => Bool, default => 1);
30 2 has ping_interval => (is => 'ro', isa => Int, default => 15);
31 2 has reconnection_wait_time => (is => 'ro', isa => Int, default => 2);
32 2 has reauthentication_interval => (is => 'ro', isa => Int, default => 3600);
33  
34 2 has last_seq => (is => 'rw', isa => Int, default => 1,
35 handles_via => 'Number',
36 handles => {
37 inc_last_seq => 'add',
38 });
39  
40 12 ▶has loops => (is => 'rw', isa => ArrayRef[InstanceOf['Mojo::IOLoop']], default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
41 2 handles_via => 'Array',
42 handles => {
43 add_loop => 'push',
44 clear_loops => 'clear',
45 });
46  
47 ################################################################################
48  
49 sub BUILD {
50 12 ▶ my $self = shift;
Subroutine BUILD: called CC=3 SCAR=12.0
Pod undocumented
51  
52 12 $self->authenticate(1);
53 12 $self->next::method(@_);
54  
55 # Set up expected subroutines for a child class to catch. The events can
56 # also be caught raw in a script.
57 12 foreach my $emission (@{$self->_events}) {
58 # Values from events must be set up in child class
59 60 ▶ if ($self->can($emission)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($emission)) 0 60 60
60 0 ▶ $self->on($emission, sub { shift; $self->$emission(@_) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
61 }
62 }
63  
64 12 return 1;
65 }
66  
67 sub start {
68 2 ▶ my $self = shift;
Subroutine start: called CC=2 SCAR=7.0
Pod undocumented
69  
70 2 $self->_connect();
71 2 ▶ $self->ioloop->start unless $self->ioloop->is_running();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->ioloop->is_running 2 0 2
72  
73 2 return;
74 }
75  
76 sub message_has_content {
77 3 ▶ my $self = shift;
Subroutine message_has_content: called CC=2 SCAR=7.0
Pod undocumented
78 3 my $args = shift;
79  
80 3 ▶ return $args->{post_data} && $args->{post_data}->{message};
Condition66%2/3
$args->{'post_data'} && $args->{'post_data'}{'message'}
!ll&&!rl&&r
201
MC/DC50%1/2
$args->{'post_data'} && $args->{'post_data'}{'message'}
$args->{'post_data'} $args->{'post_data'}{'message'}
Truth table66%2/3
A && B
A= $args->{'post_data'}B= $args->{'post_data'}{'message'}
ABresult
0X0
100
111
81 }
82  
83 ################################################################################
84  
85 sub _connect {
86 2 ▶ my $self = shift;
Subroutine _connect: called CC=1 SCAR=3.9
87  
88 2 ▶ $self->_ua->on(start => sub { $self->_on_start(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
89  
90 $self->_ua->websocket($self->websocket_url => sub {
91 0 ▶ my ($ua, $tx) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
92  
93 0 $self->ws($tx);
94  
95 0 ▶ unless ($tx->is_websocket) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tx->is_websocket) 0 0 0
96 0 $self->logger->fatal('WebSocket handshake failed');
97 }
98  
99 0 $self->emit(gw_ws_started => {});
100  
101 0 $self->logger->debug('Adding ping loop');
102  
103 0 ▶ $self->add_loop($self->ioloop->recurring(15 => sub { $self->_ping($tx) }));
Subroutine __ANON__: not called CC=1 SCAR=6.9
104 0 ▶ $self->add_loop($self->ioloop->recurring($self->reauthentication_interval => sub { $self->_reauthenticate() }));
Subroutine __ANON__: not called CC=1 SCAR=6.9
105  
106 0 ▶ $tx->on(error => sub { $self->_on_error(@_) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
107 0 ▶ $tx->on(finish => sub { $self->_on_finish(@_) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
108 0 ▶ $tx->on(message => sub { $self->_on_message(@_) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
109 2 });
110  
111 2 return 1;
112 }
113  
114 sub _ping {
115 0 ▶ my $self = shift;
Subroutine _ping: not called CC=2 SCAR=17.9
116 0 my $tx = shift;
117  
118 0 ▶ if ($self->debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug) 0 0 0
119 0 $self->logger->debugf('[Seq: %d] Sending ping', $self->last_seq);
120 }
121  
122 0 return $tx->send(encode_json({
123 seq => $self->last_seq,
124 action => 'ping',
125 }));
126 }
127  
128 sub _on_start {
129 1 ▶ my $self = shift;
Subroutine _on_start: called CC=2 SCAR=7.2
130 1 my $ua = shift;
131 1 my $tx = shift;
132  
133 1 ▶ if ($self->debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug) 0 1 1
134 0 $self->logger->debugf('UserAgent connected to %s', $tx->req->url->to_string);
135 0 $self->logger->debugf('Auth token: %s', $self->auth_token);
136 }
137  
138 # The methods here are from the UserAgent role
139 1 $tx->req->headers->header('Cookie' => $self->mmauthtoken($self->auth_token));
140 1 $tx->req->headers->header('Authorization' => $self->bearer($self->auth_token));
141 1 $tx->req->headers->header('Keep-Alive' => 1);
142  
143 1 return 1;
144 }
145  
146 sub _on_finish {
147 0 ▶ my $self = shift;
Subroutine _on_finish: not called CC=2 SCAR=17.9
148 0 my $tx = shift;
149 0 my $code = shift;
150 0 ▶ my $reason = shift || 'Unknown';
Condition0%0/2
shift() || 'Unknown'
l!l
00
MC/DC0%0/1
shift() || 'Unknown'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
151  
152 0 $self->logger->infof('WebSocket connection closed: [%d] %s', $code, $reason);
153 0 $self->logger->infof('Reconnecting in %d seconds...', $self->reconnection_wait_time);
154  
155 0 $self->ws->finish;
156 0 $self->emit(gw_ws_finished => { code => $code, reason => $reason });
157  
158 # Delay the reconnection a little
159 Mojo::IOLoop->timer($self->reconnection_wait_time => sub {
160 0 ▶ return $self->_reconnect();
Subroutine __ANON__: not called CC=1 SCAR=6.9
161 0 });
162 }
163  
164 sub _on_message {
165 0 ▶ my $self = shift;
Subroutine _on_message: not called CC=11 SCAR=48.8
166 0 my $tx = shift;
167 0 my $input = shift;
168  
169 0 ▶ return unless $input;
Branch: 1 branch
BranchTrueFalseTotal
unless $input 0 0 0
170  
171 0 my $message = decode_json(encode('utf8', $input));
172  
173 0 ▶ if ($message->{seq}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"seq"}) 0 0 0
174 0 ▶ $self->logger->debugf('[Seq: %d]', $message->{seq}) if $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 0 0
175 0 $self->last_seq($message->{seq});
176 }
177  
178 0 ▶ return $self->_on_non_event($message) unless $message && $message->{event};
Branch: 1 branch
BranchTrueFalseTotal
unless $message and $message->{"event"} 0 0 0
Condition0%0/3
$message and $message->{"event"}
!ll&&!rl&&r
000
MC/DC0%0/2
$message and $message->{"event"}
$message $message->{"event"}
Truth table0%0/3
A and B
A= $messageB= $message->{"event"}
ABresult
0X0
100
111
179  
180 0 my $message_args = { message => $message };
181  
182 0 ▶ if ($message->{data}->{post}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"data"}{"post"}) 0 0 0
183 0 my $post_data = decode_json(encode('utf8', $message->{data}->{post}));
184  
185 # Early return if the message is from the bot's own user ID (to halt
186 # recursion)
187 0 ▶ return if $self->ignore_self && $post_data->{user_id} eq $self->user_id;
Branch: 1 branch
BranchTrueFalseTotal
if $self->ignore_self and $post_data->{"user_id"} eq $self->user_id 0 0 0
Condition0%0/3
$self->ignore_self and $post_data->{"user_id"} eq $self->user_id
!ll&&!rl&&r
000
MC/DC0%0/2
$self->ignore_self and $post_data->{"user_id"} eq $self->user_id
$self->ignore_self $post_data->{"user_id"} eq $self->user_id
Truth table0%0/3
A and B
A= $self->ignore_selfB= $post_data->{"user_id"} eq $self->user_id
ABresult
0X0
100
111
188  
189 0 $message_args->{post_data} = $post_data;
190 }
191  
192 0 $self->emit(gw_message => $message_args);
193  
194 0 ▶ if ($message->{event} eq 'hello') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"event"} eq "hello") 0 0 0
195 0 ▶ if ($self->debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug) 0 0 0
196 0 $self->logger->debug('Received "hello" event, sending authentication challenge');
197 }
198  
199 0 $tx->send(encode_json({
200 seq => 1,
201 action => 'authentication_challenge',
202 data => { token => $self->auth_token },
203 }));
204 }
205  
206 0 return 1;
207 }
208  
209 sub _on_non_event {
210 0 ▶ my $self = shift;
Subroutine _on_non_event: not called CC=4 SCAR=30.0
211 0 my $message = shift;
212  
213 0 ▶ if ($self->debug && $message->{data} && $message->{data}->{text}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug and $message->{"data"} and $message->{"data"}{"text"}) 0 0 0
Condition0%0/6
$self->debug and $message->{"data"} and $message->{"data"}{"text"}
!ll&&!rl&&r
000
$self->debug and $message->{"data"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->debug and $message->{"data"} and $message->{"data"}{"text"}
$self->debug $message->{"data"} $message->{"data"}{"text"}
Truth table0%0/4
A and B and C
A= $self->debugB= $message->{"data"}C= $message->{"data"}{"text"}
ABCresult
0XX0
10X0
1100
1111
214 0 $self->logger->debugf('[Seq: %d] Received %s', $self->last_seq, $message->{data}->{text});
215 }
216  
217 0 return $self->emit(gw_message_no_event => $message);
218 }
219  
220 sub _on_error {
221 0 ▶ my $self = shift;
Subroutine _on_error: not called CC=1 SCAR=6.9
222 0 my $ws = shift;
223 0 my $message = shift;
224  
225 0 $self->emit(gw_ws_error => { message => $message });
226  
227 0 return $ws->finish($message);
228 }
229  
230 sub _reauthenticate {
231 0 ▶ my $self = shift;
Subroutine _reauthenticate: not called CC=1 SCAR=6.9
232  
233 # Mattermost authentication tokens expire after a given (and unknown) amount
234 # of time. By default, the client will reconnect every hour in order to
235 # refresh the token.
236 0 $self->authenticate(1);
237 0 $self->_try_authentication();
238  
239 0 return 1;
240 }
241  
242 sub _reconnect {
243 0 ▶ my $self = shift;
Subroutine _reconnect: not called CC=1 SCAR=6.9
244  
245 # Reset things which have been altered during the course of the last
246 # connection
247 0 $self->last_seq(1);
248 0 $self->_try_authentication();
249 0 $self->_clean_up_loops();
250 0 $self->ws(undef);
251 0 $self->_ua($self->_build__ua);
252  
253 0 return $self->_connect();
254 }
255  
256 sub _clean_up_loops {
257 0 ▶ my $self = shift;
Subroutine _clean_up_loops: not called CC=2 SCAR=17.9
258  
259 0 foreach my $loop (@{$self->loops}) {
260 0 $self->ioloop->remove($loop);
261 }
262  
263 0 return $self->clear_loops();
264 }
265  
266 ################################################################################
267  
268 sub _build__events {
269 12 ▶ return [ qw(
Subroutine _build__events: called CC=1 SCAR=0.0
270 gw_ws_error
271 gw_ws_finished
272 gw_ws_started
273 gw_message
274 gw_message_no_event
275 ) ];
276 }
277  
278 2 ▶sub _build__ua { Mojo::UserAgent->new }
Subroutine _build__ua: called CC=1 SCAR=0.0
279  
280 2 ▶sub _build_ioloop { Mojo::IOLoop->singleton }
Subroutine _build_ioloop: called CC=1 SCAR=0.0
281  
282 sub _build_websocket_url {
283 3 ▶ my $self = shift;
Subroutine _build_websocket_url: called CC=2 SCAR=7.0
284  
285 # Convert the API URL to the WebSocket URL
286 3 my $ws_url = $self->base_url;
287  
288 3 ▶ if ($ws_url !~ /\/$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ws_url =~ m[/$]) 3 0 3
289 3 $ws_url .= '/';
290 }
291  
292 3 $ws_url .= 'websocket';
293 3 $ws_url =~ s/^http(?:s)?/wss/s;
294  
295 3 return $ws_url;
296 }
297  
298 ################################################################################
299  
300 2 1;
301  
302 __END__
303  
304 =pod
305  
306 =encoding UTF-8
307  
308 =head1 NAME
309  
310 WebService::Mattermost::V4::Client - Perl websocket client for Mattermost.
311  
312 =head1 VERSION
313  
314 version 0.28
315  
316 =head1 DESCRIPTION
317  
318 This class connects to Mattermost via the WebSocket gateway and can either be
319 extended in a child class, or used in a script.
320  
321 =head2 USAGE
322  
323 =head3 FROM A SCRIPT
324  
325 use WebService::Mattermost::V4::Client;
326  
327 my $bot = WebService::Mattermost::V4::Client->new({
328 username => 'usernamehere',
329 password => 'password',
330 base_url => 'https://mattermost.server.com/api/v4/',
331  
332 # Optional arguments
333 debug => 1, # Show extra connection information
334 ignore_self => 0, # May cause recursion!
335 });
336  
337 $bot->on(message => sub {
338 my ($bot, $args) = @_;
339  
340 # $args contains the decoded message content
341 });
342  
343 $bot->start(); # Add me last
344  
345 =head3 EXTENSION
346  
347 See L<WebService::Mattermost::V4::Example::Bot>.
348  
349 =head2 EVENTS
350  
351 Events are either available to be caught with C<on> in scripts, or have methods
352 which can be overridden in child classes.
353  
354 =over 4
355  
356 =item C<gw_ws_started>
357  
358 The bot connected to the Mattermost gateway. Can be overridden as
359 C<gw_ws_started()>.
360  
361 =item C<gw_ws_finished>
362  
363 The bot disconnected from the Mattermost gateway. Can be overridden as
364 C<gw_ws_finished()>.
365  
366 =item C<gw_message>
367  
368 The bot received a message. Can be overridden as C<gw_message()>.
369  
370 =item C<gw_ws_error>
371  
372 The bot received an error. Can be overridden as C<gw_error()>.
373  
374 =item C<gw_message_no_event>
375  
376 The bot received a message without an event (which is usually a "ping" item).
377 Can be overridden as C<gw_message_no_event()>.
378  
379 =back
380  
381 =head1 AUTHOR
382  
383 Mike Jones <mike@netsplit.org.uk>
384  
385 =head1 COPYRIGHT AND LICENSE
386  
387 This software is Copyright (c) 2020 by Mike Jones.
388  
389 This is free software, licensed under:
390  
391 The MIT (X11) License
392  
393 =cut
« Mattermost/V4/API/Resource/Channel/Member.pm ↑ Summary Mattermost/V4/API/Resource/Channels.pm »