Debian Codegraph @

lib/Catmandu/Importer/OAI.pm

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package Catmandu::Importer::OAI;
2
3 use Catmandu::Sane;
4 use Catmandu::Util qw(:is);
5 use Moo;
6 use Scalar::Util qw(blessed);
7 use HTTP::OAI;
8 use Carp;
9 use Catmandu::Error;
10 use URI;
11
12 our $VERSION = '0.21';
13
14 with 'Catmandu::Importer';
15
16 has url => (is => 'ro', required => 1);
17 has identifier => (is => 'ro');
18 has metadataPrefix => (is => 'ro', default => sub { "oai_dc" });
19 has set => (is => 'ro');
20 has from => (is => 'ro');
21 has until => (is => 'ro');
22 has resumptionToken => (is => 'ro');
23
24 has strict => (is => 'ro');
25
26 has identify => (is => 'ro');
27 has listIdentifiers => (is => 'ro');
28 has listRecords => (is => 'ro');
29 has listSets => (is => 'ro');
30 has listMetadataFormats => (is => 'ro');
31 has getRecord => (is => 'ro');
32
33 has oai => (is => 'ro', lazy => 1, builder => 1);
34 has dry => (is => 'ro');
35 has handler => (is => 'rw', lazy => 1 , builder => 1, coerce => \&_coerce_handler );
36 has xslt => (is => 'ro', coerce => \&_coerce_xslt );
37 has sleep => ( is => 'ro', default => sub { 0 } );
38 has max_retries => ( is => 'ro', default => sub { 0 } );
39 has _retried => ( is => 'rw', default => sub { 0; } );
40 has _xml_handlers => ( is => 'ro', default => sub { +{} } );
41 has realm => ( is => 'ro', predicate => 1 );
42 has username => ( is => 'ro', predicate => 1 );
43 has password => ( is => 'ro', predicate => 1 );
44
45 sub _build_handler {
46 my ($self) = @_;
47 if ($self->metadataPrefix eq 'oai_dc') {
48 return 'oai_dc';
49 }
50 elsif ($self->metadataPrefix eq 'marcxml') {
51 return 'marcxml';
52 }
53 elsif ($self->metadataPrefix eq 'mods') {
54 return 'mods';
55 }
56 else {
57 return 'struct';
58 }
59 }
60
61 sub _coerce_handler {
62 my ($handler) = @_;
63
64 return $handler if is_invocant($handler) or is_code_ref($handler);
65
66 if (is_string($handler) && !is_number($handler)) {
67 my $class = $handler =~ /^\+(.+)/ ? $1
68 : "Catmandu::Importer::OAI::Parser::$handler";
69
70 my $handler;
71 eval {
72 $handler = Catmandu::Util::require_package($class)->new;
73 };
74 if ($@) {
75 croak $@;
76 } else {
77 return $handler;
78 }
79 }
80
81 return sub { return { _metadata => readXML($_[0]) } };
82 }
83
84 sub _coerce_xslt {
85 eval {
86 Catmandu::Util::require_package('Catmandu::XML::Transformer')
87 ->new( stylesheet => $_[0] )
88 } or croak $@;
89 }
90
91 sub _build_oai {
92 my ($self) = @_;
93 my $agent = HTTP::OAI::Harvester->new(baseURL => $self->url, resume => 0, keep_alive => 1);
94 if( $self->has_username && $self->has_password ) {
95 my $uri = URI->new( $self->url );
96 my @credentials = (
97 $uri->host_port,
98 $self->realm || undef,
99 $self->username,
100 $self->password
101 );
102 $agent->credentials( @credentials );
103 }
104 $agent->env_proxy;
105 $agent;
106 }
107
108 sub _xml_handler_for_node {
109 my ( $self, $node ) = @_;
110 my $ns = $node->namespaceURI();
111
112 my $type;
113
114 if( $ns eq "http://www.openarchives.org/OAI/2.0/oai_dc/" ){
115
116 $type = "oai_dc";
117
118 }
119 elsif( $ns eq "http://www.loc.gov/MARC21/slim" ){
120
121 $type = "marcxml";
122
123 }
124 elsif( $ns eq "http://www.loc.gov/mods/v3" ){
125
126 $type = "mods";
127
128 }
129 else{
130
131 $type = "struct";
132
133 }
134
135 $self->_xml_handlers()->{$type} ||= Catmandu::Util::require_package( "Catmandu::Importer::OAI::Parser::$type" )->new();
136 }
137
138 sub _map_set {
139 my ($self, $rec) = @_;
140
141 +{
142 _id => $rec->setSpec(),
143 setSpec => $rec->setSpec(),
144 setName => $rec->setName(),
145 setDescription => [ map {
146
147 #root: 'setDescription'
148 my @root = $_->dom()->childNodes();
149 #child: oai_dc, marcxml, mods..
150 my @children = $root[0]->childNodes();
151 $self->_xml_handler_for_node( $children[0] )->parse( $children[0] );
152
153 } $rec->setDescription() ]
154 };
155 }
156
157 sub _map_format {
158 my ($self, $rec) = @_;
159
160 +{
161 _id => $rec->metadataPrefix,
162 metadataPrefix => $rec->metadataPrefix(),
163 metadataNamespace => $rec->metadataNamespace(),
164 schema => $rec->schema()
165 };
166 }
167
168 sub _map_identify {
169 my ($self, $rec) = @_;
170
171 my @description;
172
173 if ($rec->description) {
174 for my $desc ($rec->description) {
175 push @description , $desc->dom->toString;
176 }
177 }
178
179 +{
180 _id => $rec->baseURL,
181 baseURL => $rec->baseURL,
182 granularity => $rec->granularity,
183 deletedRecord => $rec->deletedRecord,
184 earliestDatestamp => $rec->earliestDatestamp,
185 adminEmail => $rec->adminEmail,
186 protocolVersion => $rec->protocolVersion,
187 repositoryName => $rec->repositoryName,
188 description => \@description
189 };
190 }
191
192 sub _map_record {
193 my ($self, $rec) = @_;
194
195 my $sets = [ $rec->header->setSpec ];
196 my $identifier = $rec->identifier;
197 my $datestamp = $rec->datestamp;
198 my $status = $rec->status // "";
199 my $dom = $rec->metadata ? $rec->metadata->dom->nonBlankChildNodes->[0]->nonBlankChildNodes->[0] : undef;
200 my $about = [];
201
202 for ($rec->about) {
203 push(@$about , $_->dom->nonBlankChildNodes->[0]->nonBlankChildNodes->[0]->toString);
204 }
205
206 my $values = $self->handle_record($dom) // { };
207
208 my $data = {
209 _id => $identifier ,
210 _identifier => $identifier ,
211 _datestamp => $datestamp ,
212 _status => $status ,
213 _setSpec => $sets ,
214 _about => $about ,
215 %$values
216 };
217
218 $data;
219 }
220
221 sub _args {
222 my $self = $_[0];
223
224 my %args = (
225 identifier => $self->identifier,
226 metadataPrefix => $self->metadataPrefix,
227 set => $self->set ,
228 from => $self->from ,
229 until => $self->until ,
230 force => !$self->strict ,
231 );
232
233 for( keys %args ) {
234 delete $args{$_} if !defined($args{$_}) || !length($args{$_});
235 }
236
237 return %args;
238 }
239
240 sub _verb {
241 my $self = $_[0];
242
243 if ($self->identify) {
244 return 'Identify';
245 }
246 elsif ($self->listIdentifiers) {
247 return 'ListIdentifiers';
248 }
249 elsif ($self->listSets) {
250 return 'ListSets';
251 }
252 elsif ($self->getRecord) {
253 return 'GetRecord';
254 }
255 elsif ($self->listMetadataFormats) {
256 return 'ListMetadataFormats';
257 }
258 elsif ($self->listRecords) {
259 return 'ListRecords';
260 }
261 else {
262 return 'ListRecords';
263 }
264 }
265
266 sub handle_record {
267 my ($self, $dom) = @_;
268 return unless $dom;
269
270 $dom = $self->xslt->transform($dom) if $self->xslt;
271 return blessed($self->handler)
272 ? $self->handler->parse($dom)
273 : $self->handler->($dom);
274 }
275
276 sub dry_run {
277 my ($self) = @_;
278 sub {
279 state $called = 0;
280 return if $called;
281 $called = 1;
282 # TODO: make sure that HTTP::OAI does not change this internal method
283 return +{
284 url => $self->oai->_buildurl(
285 $self->_args(),
286 verb => $self->_verb()
287 )
288 };
289 };
290 }
291
292 sub _retry {
293 my ( $self, $sub ) = @_;
294
295 $self->_retried( 0 );
296
297 my $res;
298
299 while ( 1 ) {
300
301 $res = $sub->();
302
303 if ($res->is_error && ref($res) ne 'HTTP::OAI::Response') {
304
305 my $max_retries = $self->max_retries();
306 my $_retried = $self->_retried();
307
308 if ( $max_retries > 0 && $_retried < $max_retries ){
309
310 $_retried++;
311
312 #exponential backoff: [0 .. 2^c [
313 my $n_seconds = int( 2**$_retried );
314 $self->log->error("failed, retrying after $n_seconds");
315 sleep $n_seconds;
316 $self->_retried( $_retried );
317 next;
318 }
319 else {
320 my $err_msg = $self->url . " : " . $res->message." (stopped after ".$self->_retried()." retries)";
321 $self->log->error( $err_msg );
322 Catmandu::Error->throw( $err_msg );
323 }
324 }
325
326 last;
327 }
328
329 $res;
330 }
331
332 sub _list_records {
333 my $self = $_[0];
334 my $args = $_[1];
335 sub {
336 state $stack = [];
337 state $resumptionToken = $self->resumptionToken;
338 state $resumptionData = {};
339 state $done = 0;
340
341 my $fill_stack = sub {
342 push @$stack , shift;
343 };
344
345 if (@$stack <= 1 && $done == 0) {
346 my %args = $args ? %$args : $self->_args;
347
348 # Use the resumptionToken if one found on the last run, or if it was
349 # undefined (last record)
350 if (defined $resumptionToken) {
351 my $verb = $args{verb};
352 %args = (verb => $verb , resumptionToken => $resumptionToken);
353 }
354
355 my $sub = $self->listIdentifiers() ?
356 sub { $self->oai->ListIdentifiers( %args , onRecord => $fill_stack ); } :
357 sub { $self->oai->ListRecords( %args , onRecord => $fill_stack ); };
358
359 my $res = $self->_retry( $sub );
360 if (defined $res->resumptionToken) {
361 $resumptionToken = $res->resumptionToken->resumptionToken;
362
363 $resumptionData->{token} = $resumptionToken;
364 $resumptionData->{expirationDate} = $res->resumptionToken->expirationDate;
365 $resumptionData->{completeListSize} = $res->resumptionToken->completeListSize;
366 $resumptionData->{cursor} = $res->resumptionToken->cursor;
367 }
368 else {
369 $resumptionToken = undef;
370 }
371
372 unless (defined $resumptionToken && length $resumptionToken) {
373 $done = 1;
374 }
375
376 if ($self->sleep) {
377 sleep $self->sleep;
378 }
379 }
380
381 if (my $rec = shift @$stack) {
382 if ($rec->isa('HTTP::OAI::Record')) {
383 my $rec = $self->_map_record($rec);
384
385 $rec->{_resumptionToken} = $resumptionToken if defined($resumptionToken);
386 $rec->{_resumption} = $resumptionData if defined($resumptionData);
387
388 return $rec;
389 }
390 else {
391 my $rec = {
392 _id => $rec->identifier,
393 _datestamp => $rec->datestamp,
394 _status => $rec->status // "",
395 };
396
397 $rec->{_resumptionToken} = $resumptionToken if defined($resumptionToken);
398 $rec->{_resumption} = $resumptionData if defined($resumptionData);
399
400 return $rec;
401 }
402 }
403
404 return undef;
405 };
406 }
407
408 sub _list_sets {
409 my $self = $_[0];
410 sub {
411 state $stack = [];
412 state $done = 0;
413
414 my $fill_stack = sub {
415 push @$stack , shift;
416 };
417
418 if (@$stack <= 1 && $done == 0) {
419 my $sub = sub { $self->oai->ListSets( onRecord => $fill_stack ); };
420
421 my $res = $self->_retry( $sub );
422 $done = 1;
423 }
424
425 if (my $rec = shift @$stack) {
426 return $self->_map_set($rec);
427 }
428
429 return undef;
430 };
431 }
432
433 sub _get_record {
434 my $self = $_[0];
435 my $args = $_[1];
436 sub {
437 state $stack = [];
438 state $done = 0;
439
440 my $fill_stack = sub {
441 push @$stack , shift;
442 };
443
444 if (@$stack <= 1 && $done == 0) {
445 my %args = $args ? %$args : $self->_args;
446 my $sub = sub { $self->oai->GetRecord(%args , onRecord => $fill_stack) };
447 my $res = $self->_retry( $sub );
448 $done = 1;
449 }
450
451 if (my $rec = shift @$stack) {
452 if ($rec->isa('HTTP::OAI::Record')) {
453 return $self->_map_record($rec);
454 }
455 else {
456 return {
457 _id => $rec->identifier,
458 _datestamp => $rec->datestamp,
459 _status => $rec->status // "",
460 }
461 }
462 }
463
464 return undef;
465 };
466 }
467
468 sub _list_metadata_formats {
469 my $self = $_[0];
470 my $args = $_[1];
471 sub {
472 state $stack = [];
473 state $done = 0;
474
475 my $fill_stack = sub {
476 push @$stack , shift;
477 };
478
479 if (@$stack <= 1 && $done == 0) {
480 my %args = $args ? %$args : $self->_args;
481 delete $args{metadataPrefix};
482
483 my $sub = sub { $self->oai->ListMetadataFormats( %args ); };
484
485 my $res = $self->_retry( $sub );
486
487 while( my $mdf = $res->next ) {
488 $fill_stack->($mdf);
489 }
490
491 $done = 1;
492 }
493
494 if (my $rec = shift @$stack) {
495 return $self->_map_format($rec);
496 }
497
498 return undef;
499 };
500 }
501
502 sub _identify {
503 my $self = $_[0];
504 sub {
505 state $stack = [];
506 state $done = 0;
507
508 my $fill_stack = sub {
509 push @$stack , shift;
510 };
511
512 if (@$stack <= 1 && $done == 0) {
513 my $sub = sub { $self->oai->Identify( onRecord => $fill_stack) };
514 my $res = $self->_retry( $sub );
515
516 $fill_stack->($res);
517
518 $done = 1;
519 }
520
521 if (my $rec = shift @$stack) {
522 return $self->_map_identify($rec);
523 }
524
525 return undef;
526 };
527 }
528
529 sub oai_run {
530 my ($self) = @_;
531
532 if ($self->identify) {
533 return $self->_identify;
534 }
535 elsif ($self->listIdentifiers) {
536 return $self->_list_records;
537 }
538 elsif ($self->listSets) {
539 return $self->_list_sets
540 }
541 elsif ($self->getRecord) {
542 return $self->_get_record;
543 }
544 elsif ($self->listMetadataFormats) {
545 return $self->_list_metadata_formats;
546 }
547 elsif ($self->listRecords) {
548 return $self->_list_records
549 }
550 else {
551 return $self->_list_records
552 }
553 }
554
555 sub generator {
556 my ($self) = @_;
557
558 return $self->dry ? $self->dry_run : $self->oai_run;
559 }
560
561 1;
562 __END__
563
564 =head1 NAME
565
566 Catmandu::Importer::OAI - Package that imports OAI-PMH feeds
567
568 =head1 SYNOPSIS
569
570 # From the command line
571
572 # Harvest records
573 $ catmandu convert OAI --url http://myrepo.org/oai
574 $ catmandu convert OAI --url http://myrepo.org/oai --metadataPrefix didl --handler raw
575
576 # Harvest repository description
577 $ catmandu convert OAI --url http://myrepo.org/oai --identify 1
578
579 # Harvest identifiers
580 $ catmandu convert OAI --url http://myrepo.org/oai --listIdentifiers 1
581
582 # Harvest sets
583 $ catmandu convert OAI --url http://myrepo.org/oai --listSets 1
584
585 # Harvest metadataFormats
586 $ catmandu convert OAI --url http://myrepo.org/oai --listMetadataFormats 1
587
588 # Harvest one record
589 $ catmandu convert OAI --url http://myrepo.org/oai --getRecord 1 --identifier oai:myrepo:1234
590
591 =head1 DESCRIPTION
592
593 L<Catmandu::Importer::OAI> is an L<Catmandu> importer to harvest metadata records
594 from an OAI-PMH endpoint.
595
596 =head1 CONFIGURATION
597
598 =over
599
600 =item url
601
602 OAI-PMH Base URL.
603
604 =item metadataPrefix
605
606 Metadata prefix to specify the metadata format. Set to C<oai_dc> by default.
607
608 =item handler( sub {} | $object | 'NAME' | '+NAME' )
609
610 Handler to transform each record from XML DOM (L<XML::LibXML::Element>) into
611 Perl hash.
612
613 Handlers can be provided as function reference, an instance of a Perl
614 package that implements 'parse', or by a package NAME. Package names should
615 be prepended by C<+> or prefixed with C<Catmandu::Importer::OAI::Parser>. E.g
616 C<foobar> will create a C<Catmandu::Importer::OAI::Parser::foobar> instance.
617
618 By default the handler L<Catmandu::Importer::OAI::Parser::oai_dc> is used for
619 metadataPrefix C<oai_dc>, L<Catmandu::Importer::OAI::Parser::marcxml> for
620 C<marcxml>, L<Catmandu::Importer::OAI::Parser::mods> for
621 C<mods>, and L<Catmandu::Importer::OAI::Parser::struct> for other formats.
622 In addition there is L<Catmandu::Importer::OAI::Parser::raw> to return the XML
623 as it is.
624
625 =item identifier
626
627 Option return only results for this particular identifier
628
629 =item set
630
631 An optional set for selective harvesting.
632
633 =item from
634
635 An optional datetime value (YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ) as lower bound
636 for datestamp-based selective harvesting.
637
638 =item until
639
640 An optional datetime value (YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ) as upper bound
641 for datestamp-based selective harvesting.
642
643 =item identify
644
645 Harvest the repository description instead of all records.
646
647 =item getRecord
648
649 Harvest one record instead of all records.
650
651 =item listIdentifiers
652
653 Harvest identifiers instead of full records.
654
655 =item listRecords
656
657 Harvest full records. Default operation.
658
659 =item listSets
660
661 Harvest sets instead of records.
662
663 =item listMetadataFormats
664
665 Harvest metadata formats of records
666
667 =item resumptionToken
668
669 An optional resumptionToken to start harvesting from.
670
671 =item dry
672
673 Don't do any HTTP requests but return URLs that data would be queried from.
674
675 =item strict
676
677 Optional validate all parameters first against the OAI 2 spefications before
678 sending it to an OAI server. Default: undef.
679
680 =item xslt
681
682 Preprocess XML records with XSLT script(s) given as comma separated list or
683 array reference. Requires L<Catmandu::XML>.
684
685 =item max_retries
686
687 When an oai request fails, the importer will retry this number of times.
688 Set to '0' by default.
689
690 Internally the exponential backoff algorithm is used
691 for this. This means that after every failed request the importer
692 will choose a random number between 0 and 2^collision (excluded),
693 and wait that number of seconds. So the actual ammount of time before
694 the importer stops can differ:
695
696 first retry:
697 wait [ 0..2^1 [ seconds
698 second retry:
699 wait [ 0..2^2 [ seconds
700 third retry:
701 wait [ 0..2^3 [ seconds
702
703 ..
704
705 =item sleep
706
707 Sleep a number of seconds between OAI-PMH calls to the endpoint (default 0).
708
709 =item realm
710
711 An optional realm value. This value is used when the importer harvests from a
712 repository which is secured with basic authentication through Integrated Windows
713 Authentication (NTLM or Kerberos).
714
715 =item username
716
717 An optional username value. This value is used when the importer harvests from a
718 repository which is secured with basic authentication.
719
720 =item password
721
722 An optional password value. This value is used when the importer harvests from a
723 repository which is secured with basic authentication.
724
725 =back
726
727 =head1 METHOD
728
729 Every Catmandu::Importer is a L<Catmandu::Iterable> all its methods are
730 inherited. The Catmandu::Importer::OAI methods are not idempotent: OAI-PMH
731 feeds can only be read once.
732
733 In addition to methods inherited from L<Catmandu::Iterable>, this module
734 provides the following public methods:
735
736 =head2 handle_record( $dom )
737
738 Process an XML DOM as with xslt and handler as configured and return the
739 result.
740
741 =head1 ENVIRONMENT
742
743 If you are connected to the internet via a proxy server you need to set the
744 coordinates to this proxy in your environment:
745
746 export http_proxy="http://localhost:8080"
747
748 If you are connecting to a HTTPS server and don't want to verify the validity
749 of certificates of the peer you can set the PERL_LWP_SSL_VERIFY_HOSTNAME to
750 false in your environment. This maybe required to connect to broken SSL servers:
751
752 export PERL_LWP_SSL_VERIFY_HOSTNAME=0
753
754 =head1 SEE ALSO
755
756 L<Catmandu> ,
757 L<Catmandu::Importer>
758
759 =head1 AUTHOR
760
761 Nicolas Steenlant, C<< <nicolas.steenlant at ugent.be> >>
762
763 =head1 CONTRIBUTOR
764
765 Patrick Hochstenbach, C<< <patrick.hochstenbach at ugent.be> >>
766
767 Jakob Voss, C<< <nichtich at cpan.org> >>
768
769 Nicolas Franck, C<< <nicolas.franck at ugent.be> >>
770
771 =head1 LICENSE AND COPYRIGHT
772
773 Copyright 2016 Ghent University Library
774
775 This program is free software; you can redistribute it and/or modify it
776 under the terms of either: the GNU General Public License as published
777 by the Free Software Foundation; or the Artistic License.
778
779 See http://dev.perl.org/licenses/ for more information.
780
781 =cut