blib/lib/BZ/Client.pm untested

filter: Statementstmt 0.0% 0 / 138 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 40 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 279 CC 33 SCAR 32.7
CC
33
Cov
0%
_api_call
90.0
login
30.0
logout
30.0
CRAP 26.3
1 #!/bin/false
2 # ABSTRACT: A client for the Bugzilla web services API.
3 # PODNAME: BZ::Client
4  
5 use strict;
6 use warnings 'all';
7  
8 package BZ::Client;
9 $BZ::Client::VERSION = '4.4001';
10  
11 use BZ::Client::XMLRPC;
12 use BZ::Client::Exception;
13 use HTTP::CookieJar;
14  
15 sub new {
16 my $class = shift;
17 my $self = {@_};
18 bless( $self, ref($class) || $class );
19 return $self
20 }
21  
22 sub url {
23 my $self = shift;
24 if (@_) {
25 $self->{'url'} = shift;
26 }
27 else {
28 return $self->{'url'};
29 }
30 }
31  
32 sub api_key {
33 my $self = shift;
34 if (@_) {
35 $self->{'api_key'} = shift;
36 }
37 else {
38 return $self->{'api_key'};
39 }
40 }
41  
42 sub user {
43 my $self = shift;
44 if (@_) {
45 $self->{'user'} = shift;
46 }
47 else {
48 return $self->{'user'};
49 }
50 }
51  
52 sub password {
53 my $self = shift;
54 if (@_) {
55 $self->{'password'} = shift;
56 }
57 else {
58 return $self->{'password'};
59 }
60 }
61  
62 sub autologin {
63 my $self = shift;
64 if (@_) {
65 $self->{'autologin'} = shift;
66 }
67 else {
68 $self->{'autologin'} = 1
69 unless defined($self->{'autologin'});
70 return $self->{'autologin'};
71 }
72 }
73  
74 sub error {
75 my ( $self, $message, $http_code, $xmlrpc_code ) = @_;
76 BZ::Client::Exception->throw(
77 message => $message,
78 http_code => $http_code,
79 xmlrpc_code => $xmlrpc_code
80 );
81 }
82  
83 sub log {
84 my ( $self, $level, $msg ) = @_;
85 my $logger = $self->logger();
86 if ($logger) {
87 &$logger( $level, $msg );
88 }
89 }
90  
91 # FIXME nothing actually uses this?
92 sub logger {
93 my $self = shift;
94 if (@_) {
95 my $logger = shift;
96 $self->error('Cannot set logger to non-coderef.')
97 unless ref $logger eq 'CODE';
98 $self->{'logger'} = $logger;
99 }
100 else {
101 return $self->{'logger'};
102 }
103 }
104  
105 sub logDirectory {
106 my $self = shift;
107 if (@_) {
108 $self->{'logDirectory'} = shift;
109 }
110 else {
111 return $self->{'logDirectory'};
112 }
113 }
114  
115 sub xmlrpc {
116 my $self = shift;
117 if (@_) {
118 $self->{'xmlrpc'} = shift;
119 }
120 else {
121 my $xmlrpc = $self->{'xmlrpc'};
122 if ( !$xmlrpc ) {
123 my $url = $self->url()
124 || $self->error('The Bugzilla servers URL is not set.');
125 $xmlrpc = BZ::Client::XMLRPC->new(
126 url => $url,
127 connect => $self->{'connect'} );
128 $xmlrpc->logDirectory( $self->logDirectory() );
129 $xmlrpc->logger( $self->logger() );
130 $self->xmlrpc($xmlrpc);
131 }
132 return $xmlrpc;
133 }
134 }
135  
136 sub login {
137 my $self = shift;
138  
139 if ($self->api_key()) {
140 $self->log( 'debug', 'BZ::Client::login, no need for User.login call when using api_key' );
141 return 1
142 }
143  
144 my $rl = BZ::Client::XMLRPC::boolean->new($self->{'restrictlogin'} ? 1 : 0);
145 my %params = (
146 'remember' => BZ::Client::XMLRPC::boolean->FALSE, # dropped in 4.4 as cookies no longer used
147 'restrictlogin' => $rl, # added in 3.6
148 'restrict_login' => $rl, # added in 4.4 for tokens
149 );
150  
151 # FIXME username and password can be provided to any function and it will be ok
152 my $user = $self->user()
153 or $self->error('The Bugzilla servers user name is not set.');
154 my $password = $self->password()
155 or $self->error('The Bugzilla servers password is not set.');
156  
157 $params{login} = $user;
158 $params{password} = $password;
159 $self->log( 'debug', 'BZ::Client::login, going to log in with username and password' );
160  
161 my $cookies = HTTP::CookieJar->new();
162 my $response = $self->_api_call( 'User.login', \%params, { cookies => $cookies } );
163 if ( not defined( $response->{'id'} )
164 or $response->{'id'} !~ m/^\d+$/s )
165 {
166 $self->error('Server did not return a valid user ID.');
167 }
168 $self->log( 'debug', 'BZ::Client::login, got ID ' . $response->{'id'} );
169 if ( my $token = $response->{'token'} ) { # for 4.4.3 onward
170 $self->{'token'} = $token;
171 $self->log( 'debug', 'BZ::Client::login, got token ' . $token );
172 }
173 else {
174 $self->{'cookies'} = $cookies;
175 }
176 return 1
177 }
178  
179 sub logout {
180 my $self = shift;
181 return 1 unless $self->is_logged_in;
182 my $response = 1; # if have not cookie or token, return 1
183 my $cookies = $self->{'cookies'};
184 my $token = $self->{'token'};
185 if ($cookies or $token) {
186 my %params;
187 $params{'token'} = $self->{'token'}
188 if $self->{'token'};
189 # Note: A good response from User.logout is empty so, empty_response_ok => 1
190 $response = $self->_api_call( 'User.logout', \%params, { empty_response_ok => 1 } );
191 $cookies->clear() if $cookies;
192 delete $self->{'token'};
193 delete $self->{'cookies'};
194 }
195 return $response
196 }
197  
198 sub is_logged_in {
199 my $self = shift;
200 return 1 if $self->{'cookies'};
201 return 1 if $self->{'token'};
202 return 1 if $self->{'api_key'};
203 return
204 }
205  
206 sub api_call {
207  
208 my ( $self, $methodName, $params, $options ) = @_;
209  
210 $params ||= {};
211 $options ||= {};
212  
213 if ( $self->autologin && not $self->is_logged_in() ) {
214 $self->login();
215 }
216  
217 return $self->_api_call( $methodName, $params, $options )
218 }
219  
220 sub _api_call {
221  
222 my ( $self, $methodName, $params, $options ) = @_;
223  
224 $self->log( 'debug',
225 "BZ::Client::_api_call, sending request for method $methodName to "
226 . $self->url() );
227  
228 my $xmlrpc = $self->xmlrpc();
229  
230 if ($options->{cookies}) {
231 $xmlrpc->web_agent->{cookie_jar} = $options->{cookies};
232 }
233  
234 $params->{Bugzilla_token} = $self->{'token'}
235 if ($self->{'token'}
236 and not $params->{token}
237 and not $params->{Bugzilla_token});
238  
239 $params->{Bugzilla_api_key} = $self->api_key()
240 if ($self->api_key()
241 and not $params->{Bugzilla_token}
242 and not $params->{Bugzilla_api_key});
243  
244 my $response =
245 $xmlrpc->request( 'methodName' => $methodName, params => [$params] );
246  
247 if ($options->{empty_response_ok}) {
248  
249 if ( ref $response and ref($response) ne 'HASH' ) {
250 $self->error("Invalid response from server: $response");
251 }
252  
253 if ($response) {
254 $self->log( 'debug',
255 "BZ::Client::_api_call, got response for method $methodName" );
256 }
257 else {
258 $self->log( 'debug',
259 "BZ::Client::_api_call, got empty response for method $methodName but thats OK" );
260 $response = 1
261 }
262  
263 }
264 else {
265  
266 if ( not $response ) {
267 $self->error('Empty response from server.');
268 }
269  
270 if ( ref($response) ne 'HASH' ) {
271 $self->error("Invalid response from server: $response");
272 }
273  
274 $self->log( 'debug',
275 "BZ::Client::_api_call, got response for method $methodName" );
276  
277 }
278  
279  
280 return $response
281 }
282  
283 1;
284  
285 __END__
286  
287 =pod
288  
289 =encoding UTF-8
290  
291 =head1 NAME
292  
293 BZ::Client - A client for the Bugzilla web services API.
294  
295 =head1 VERSION
296  
297 version 4.4001
298  
299 =head1 SYNOPSIS
300  
301 my $client = BZ::Client->new( url => $url,
302 user => $user,
303 password => $password,
304 autologin => 0 );
305 $client->login();
306  
307 =head1 BUGZILLA VERSIONS
308  
309 Please note that this L<BZ::Client> module is aimed at the XMLRPC API available in Bugzilla 5.0 and earlier.
310  
311 For 5.1 and later, which have a totally different REST API, please see L<Net::Bugzilla>.
312  
313 As such, I welcome all patches (via pull request) for functionality relating to 5.0 and earlier.
314  
315 I will only actively hunt down bugs relating to the 'maintained' Bugzilla server softwares. Please upgrade
316 your server and duplicate the problem, or see the above commitment to accept patches to fix for older
317 versions.
318  
319 =head1 CLASS METHODS
320  
321 This section lists the class methods of BZ::Client.
322  
323 =head2 new
324  
325 my $client = BZ::Client->new( url => $url,
326 user => $user,
327 password => $password );
328  
329 my $client = BZ::Client->new( url => $url,
330 api_key => $api_key );
331  
332 The new method constructs a new instance of BZ::Client. Whenever you
333 want to connect to the Bugzilla server, you must first create a
334 Bugzilla client. The methods input is a hash of parameters.
335  
336 For debugging, you can pass in a subref named C<logger> which will be
337 fed debugging information as the client works. Also the C<logDirectory>
338 option is a directory where the raw http content will be dumped.
339  
340 =head3 Parameters
341  
342 =over
343  
344 =item url
345  
346 The Bugzilla servers URL, for example C<https://bugzilla.mozilla.org/>.
347  
348 =item api_key
349  
350 API keys were introduced in 5.0.
351  
352 An API Key can be obtained in the web interface of your Bugzilla server,
353 with the following steps:
354  
355 =over 4
356  
357 =item 1. Click 'Preferences' link
358  
359 =item 2. Click 'API Keys' tab
360  
361 =item 3. Click the checkbox next to 'Generate a new API key...'
362  
363 =item 4. If you like, add some description in the textbox
364  
365 =item 5. Click the 'Submit Changes' button
366  
367 =item 6. Key appears in the table under the 'Existing API keys' subheading
368  
369 =back
370  
371 =item user
372  
373 The user name to use when logging in to the Bugzilla server. Typically,
374 this will be your email address.
375  
376 =item password
377  
378 The password to use when logging in to the Bugzilla server.
379  
380 =item autologin
381  
382 If set to C<1> (true), will try to log in (if not already logged in) when
383 the first API call is made. This is default.
384  
385 If set to C<0>, will try APi calls without logging in. You can
386 still call $client->login() to log in manually.
387  
388 Note: once you're logged in, you'll stay that way until you call L</logout>
389  
390 =item restrictlogin
391  
392 If set to C<1> (true), will ask Bugzilla to restrict logins to your IP only.
393 Generally this is a good idea, but may caused problems if you are using
394 a loadbalanced forward proxy.
395  
396 Default: C<0>
397  
398 =item connect
399  
400 A hashref with options for L<HTTP::Tiny>, this is passed through so the
401 bellow are for reference only:
402  
403 =over 4
404  
405 =item http_proxy, https_proxy, proxy
406  
407 Nominates a proxy for HTTP, HTTPS or both, respectively.
408  
409 You might also use C<$ENV{all_proxy}>, C<$ENV{http_proxy}>, C<$ENV{https_proxy}>
410 or C<$ENV{all_proxy}>.
411  
412 =item timeout
413  
414 Request timeout in seconds (default is C<60>)
415  
416 =item verify_SSL
417  
418 A boolean that indicates whether to validate the SSL certificate of an
419 "https" connection (default is false)
420  
421 =back
422  
423 =back
424  
425 =head3 Connect Via Socks Proxy
426  
427 Try something like:
428  
429 use HTTP::Tiny; # load this manually
430 use IO::Socket::Socks::Wrapper (
431 'HTTP::Tiny::Handle::connect()' => {
432 ProxyAddr => 'localhost',
433 ProxyPort => 1080,
434 SocksVersion => 4,
435 Timeout => 15
436 }
437 );
438 use BZ::Client ...etc
439  
440 =head1 INSTANCE METHODS
441  
442 This section lists the methods, which an instance of BZ::Client can
443 perform.
444  
445 =head2 url
446  
447 $url = $client->url();
448 $client->url( $url );
449  
450 Returns or sets the Bugzilla servers URL.
451  
452 =head2 user
453  
454 $user = $client->user();
455 $client->user( $user );
456  
457 Returns or sets the user name to use when logging in to the Bugzilla
458 server. Typically, this will be your email address.
459  
460 =head2 password
461  
462 $password = $client->password();
463 $client->password( $password );
464  
465 Returns or sets the password to use when logging in to the Bugzilla server.
466  
467 =head2 autologin
468  
469 If L<login> is automatically called, or not.
470  
471 =head2 login
472  
473 Used to login to the Bugzilla server. By default, there is no need to call
474 this method explicitly: It is done automatically, whenever required.
475  
476 If L<autologin> is set to C<0>, call this to log in.
477  
478 =head2 is_logged_in
479  
480 Returns C<1> if logged in, otherwise C<0>.
481  
482 =head2 logout
483  
484 Deletes local cookies and calls Bugzilla's logout function
485  
486 =head2 logger
487  
488 Sets or gets the logging function. Argument is a coderef. Returns C<undef> if none.
489  
490 $logger = $client->logger();
491  
492 $client->logger(
493 sub {
494 my ($level, $msg) = @_;
495 print STDERR "$level $message\n";
496 return 1
497 });
498  
499 Also can be set via L</new>, e.g.
500  
501 $client = BZ::Client->new( logger => sub { },
502 url => $url
503 user => $user,
504 password => $password );
505  
506 =head2 log
507  
508 $client->log( $level, $message );
509  
510 Sends log messages to whatever is loaded via L</logger>.
511  
512 =head2 api_call
513  
514 $response = $client->api_call( $methodName, $params, $options );
515  
516 Used by subclasses of L<BZ::Client::API> to invoke methods of the Bugzilla
517 API. The method name and the hash ref of parameters are sent to the Bugzilla server.
518 The options hash ref adjusts the behaviour of this function when calls are made.
519  
520 The params and options hash refs are optional, although certain param values may be required
521 depending on the method name being called. This client library relies upon the Bugzilla
522 server to enforce any method parameter requirements, so insufficient requests will still be
523 sent to the server for it to then reject them.
524  
525 Returns a hash ref of named result objects.
526  
527 =head3 Options
528  
529 =over 4
530  
531 =item empty_response_ok
532  
533 With this set, an empty response is not considered an error. In this case, api_call returns 1 to indicate
534 success.
535  
536 =item cookies
537  
538 This is used internally to set cookies with the log in functions. Don't touch this.
539  
540 =back
541  
542 =head1 EXCEPTION HANDLING
543  
544 See L<BZ::Client::Exception>
545  
546 =head1 ERROR CODES
547  
548 =head2 300 (Invalid Username or Password)
549  
550 The username does not exist, or the password is wrong.
551  
552 =head2 301 (Login Disabled)
553  
554 The ability to login with this account has been disabled. A reason may be specified with the error.
555  
556 =head2 305 (New Password Required)
557  
558 The current password is correct, but the user is asked to change his password.
559  
560 =head2 50 (Param Required)
561  
562 A login or password parameter was not provided.
563  
564 =head1 TESTING
565  
566 Bugzilla maintains demos of all supported versions and trunk at L<https://landfill.bugzilla.org>
567  
568 You might consider using that for testing against live versions.
569  
570 =head1 SEE ALSO
571  
572 L<BZ::Client::Exception>
573  
574 =head1 AUTHORS
575  
576 =over 4
577  
578 =item *
579  
580 Dean Hamstead <dean@bytefoundry.com.au>
581  
582 =item *
583  
584 Jochen Wiedmann <jochen.wiedmann@gmail.com>
585  
586 =back
587  
588 =head1 COPYRIGHT AND LICENSE
589  
590 This software is copyright (c) 2017 by Dean Hamstad.
591  
592 This is free software; you can redistribute it and/or modify it under
593 the same terms as the Perl 5 programming language system itself.
594  
595 =cut