blib/lib/App/TimeTracker/Command/TellSlack.pm untested

filter: Statementstmt 0.0% 0 / 66 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 105 CC 6 SCAR 27.8
CC
6
Cov
0%
_post_to_slack
42.0
BEGIN
2.0
BEGIN
2.0
CRAP 16.1
1 package App::TimeTracker::Command::TellSlack;
2 use strict;
3 use warnings;
4 use 5.010;
5  
6 # ABSTRACT: App::TimeTracker plugin for posting to slack.com
7  
8 our $VERSION = '1.001';
9  
10 use Moose::Role;
11 use LWP::UserAgent;
12 use Digest::SHA qw(sha1_hex);
13 use URI::Escape;
14 use App::TimeTracker::Utils qw(error_message);
15 use Encode;
16 use JSON::XS qw(encode_json);
17  
18 has 'tell_slack' => (
19 is => 'ro',
20 isa => 'Bool',
21 default => 1,
22 documentation => 'Post to slack',
23 traits => ['Getopt'],
24 );
25  
26 after [ 'cmd_start', 'cmd_continue' ] => sub {
27 my $self = shift;
28 return unless $self->tell_slack;
29 my $task = $self->_current_task;
30 $self->_post_to_slack( start => $task );
31 };
32  
33 after 'cmd_stop' => sub {
34 my ($self, $dont_exit) = @_;
35 return unless $self->tell_slack;
36 return unless $self->_current_command eq 'cmd_stop';
37 my $cfg = $self->config->{tell_slack} || {};
38 return if $dont_exit && $cfg->{ignore_stop_when_starting};
39  
40 my $task = App::TimeTracker::Data::Task->previous( $self->home );
41 $self->_post_to_slack( stop => $task );
42 };
43  
44 sub _post_to_slack {
45 my ( $self, $status, $task ) = @_;
46 my $cfg = $self->config->{tell_slack};
47 return unless $cfg;
48  
49 unless ($cfg->{url}) {
50 error_message( 'tell_slack.url not defined in config, cannot post to slack' );
51 return;
52 }
53  
54 my $ua = LWP::UserAgent->new( timeout => 3 );
55 my $message
56 = $task->user
57 . ( $status eq 'start' ? ' is now' : ' stopped' )
58 . ' working on '
59 . $task->say_project_tags;
60 my $request = HTTP::Request->new(POST=>$cfg->{url});
61  
62 my $payload = {
63 text=>$message
64 };
65 $payload->{username} = $cfg->{username} if $cfg->{username};
66  
67 $request->content(decode_utf8(encode_json($payload)));
68 my $res = $ua->request($request);
69 unless ( $res->is_success ) {
70 error_message( 'Could not post to slack: %s',
71 $res->status_line );
72 }
73 }
74  
75 no Moose::Role;
76 1;
77  
78 __END__