| 1 | package Jenkins::NotificationListener; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | our $VERSION = '0.06'; | ||
| 5 | |||
| 6 | use Net::Jenkins; | ||
| 7 | use Net::Jenkins::Job; | ||
| 8 | use Net::Jenkins::Job::Build; | ||
| 9 | use Jenkins::Notification; | ||
| 10 | use AnyEvent::Socket; | ||
| 11 | use Moose; | ||
| 12 | use methods; | ||
| 13 | use JSON::XS; | ||
| 14 | |||
| 15 | our @ISA = ( 'Moose::Object', 'Exporter' ); | ||
| 16 | our @EXPORT = qw(parse_jenkins_notification); | ||
| 17 | |||
| 18 | has host => (is => 'rw'); | ||
| 19 | |||
| 20 | has port => (is => 'rw', isa => 'Int'); | ||
| 21 | |||
| 22 | has on_notify => (is => 'rw'); | ||
| 23 | |||
| 24 | has on_error => (is => 'rw', default => sub { | ||
| 25 | return sub { warn @_; }; | ||
| 26 | }); | ||
| 27 | |||
| 28 | sub parse_jenkins_notification { | ||
| 29 | my $json = shift; | ||
| 30 | my $args = decode_json $json; | ||
| 31 | return Jenkins::Notification->new( %$args , raw_json => $json ); | ||
| 32 | } | ||
| 33 | |||
| 34 | method start ($prepare_cb) { | ||
| 35 | return tcp_server $self->host, $self->port , sub { | ||
| 36 | my ($fh, $host, $port) = @_; | ||
| 37 | my $json = ''; | ||
| 38 | my $buf = ''; | ||
| 39 | while( my $bytes = sysread $fh, $buf, 1024 ) { | ||
| 40 | $json .= $buf; | ||
| 41 | } | ||
| 42 | eval { | ||
| 43 | if( $json ) { | ||
| 44 | $self->on_notify->( | ||
| 45 | parse_jenkins_notification($json) | ||
| 46 | ); | ||
| 47 | } else { | ||
| 48 | die 'Request body is empty.'; | ||
| 49 | } | ||
| 50 | }; | ||
| 51 | if ( $@ ) { | ||
| 52 | $self->on_error->( $@ ); | ||
| 53 | } | ||
| 54 | }, $prepare_cb; | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; | ||
| 58 | __END__ |