Bug 22417: Switch to STOMP
[koha.git] / Koha / BackgroundJob.pm
1 package Koha::BackgroundJob;
2
3 use Modern::Perl;
4 use JSON qw( encode_json decode_json );
5 use Carp qw( croak );
6 use Net::Stomp;
7
8 use C4::Context;
9 use Koha::DateUtils qw( dt_from_string );
10 use Koha::BackgroundJobs;
11
12 use base qw( Koha::Object );
13
14 sub connect {
15     my ( $self );
16     my $stomp = Net::Stomp->new( { hostname => 'localhost', port => '61613' } );
17     $stomp->connect( { login => 'guest', passcode => 'guest' } );
18     return $stomp;
19 }
20
21 sub enqueue {
22     my ( $self, $params ) = @_;
23
24     my $job_type = $params->{job_type};
25     my $job_size = $params->{job_size};
26     my $job_args = $params->{job_args};
27
28     my $borrowernumber = C4::Context->userenv->{number}; # FIXME Handle non GUI calls
29     my $json_args = encode_json $job_args;
30     $self->set({
31         status => 'new',
32         type => $job_type,
33         size => $job_size,
34         data => $json_args,
35         enqueued_on => dt_from_string,
36         borrowernumber => $borrowernumber,
37     })->store;
38
39     my $job_id = $self->id;
40     $job_args->{job_id} = $job_id;
41     $json_args = encode_json $job_args,
42
43     my $conn = $self->connect;
44     $conn->send({destination => $job_type, body => $json_args});
45
46     return $job_id;
47 }
48
49 sub process { croak "This method must be subclassed" }
50
51 sub messages {
52     my ( $self ) = @_;
53
54     my @messages;
55     my $data_dump = decode_json $self->data;
56     if ( exists $data_dump->{messages} ) {
57         @messages = @{ $data_dump->{messages} };
58     }
59
60     return @messages;
61 }
62
63 sub report {
64     my ( $self ) = @_;
65
66     my $data_dump = decode_json $self->data;
67     return $data_dump->{report};
68 }
69
70 sub cancel {
71     my ( $self ) = @_;
72     $self->status('cancelled')->store;
73 }
74
75 sub _type {
76     return 'BackgroundJob';
77 }
78
79 1;