source: gsdl/trunk/perllib/downloaders/OAIDownload.pm@ 17537

Last change on this file since 17537 was 17207, checked in by kjdon, 16 years ago

BasDownload renamed to BaseDownload, also tidied up the constructors

  • Property svn:keywords set to Author Date Id Revision
File size: 15.9 KB
Line 
1###########################################################################
2#
3# WebDownload.pm -- base class for all the import plugins
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26package OAIDownload;
27
28eval {require bytes};
29
30# suppress the annoying "subroutine redefined" warning that various
31# plugins cause under perl 5.6
32$SIG{__WARN__} = sub {warn($_[0]) unless ($_[0] =~ /Subroutine\s+\S+\sredefined/)};
33
34use strict;
35
36use WgetDownload;
37use XMLParser;
38
39use POSIX qw(tmpnam);
40use util;
41
42sub BEGIN {
43 @OAIDownload::ISA = ('WgetDownload');
44}
45
46my $arguments =
47 [ { 'name' => "url",
48 'disp' => "{OAIDownload.url_disp}",
49 'desc' => "{OAIDownload.url}",
50 'type' => "string",
51 'reqd' => "yes"},
52 { 'name' => "metadata_prefix",
53 'disp' => "{OAIDownload.metadata_prefix_disp}",
54 'desc' => "{OAIDownload.metadata_prefix}",
55 'type' => "string",
56 'deft' => "oai_dc",
57 'reqd' => "no"},
58 { 'name' => "set",
59 'disp' => "{OAIDownload.set_disp}",
60 'desc' => "{OAIDownload.set}",
61 'type' => "string",
62 'reqd' => "no"},
63 { 'name' => "get_doc",
64 'disp' => "{OAIDownload.get_doc_disp}",
65 'desc' => "{OAIDownload.get_doc}",
66 'type' => "flag",
67 'reqd' => "no"},
68 { 'name' => "get_doc_exts",
69 'disp' => "{OAIDownload.get_doc_exts_disp}",
70 'desc' => "{OAIDownload.get_doc_exts}",
71 'type' => "string",
72 'deft' => "doc,pdf,ppt",
73 'reqd' => "no"},
74 { 'name' => "max_records",
75 'disp' => "{OAIDownload.max_records_disp}",
76 'desc' => "{OAIDownload.max_records}",
77 'type' => "int",
78 'deft' => "500",
79 'range' => "1,",
80 'reqd' => "no"} ];
81
82my $options = { 'name' => "OAIDownload",
83 'desc' => "{OAIDownload.desc}",
84 'abstract' => "no",
85 'inherits' => "yes",
86 'args' => $arguments };
87
88##my $self;
89
90#### my $strWgetOptions="";
91
92sub new
93{
94 my ($class) = shift (@_);
95 my ($getlist,$inputargs,$hashArgOptLists) = @_;
96 push(@$getlist, $class);
97
98 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
99 push(@{$hashArgOptLists->{"OptList"}},$options);
100
101 my $self = new WgetDownload($getlist,$inputargs,$hashArgOptLists);
102
103 if ($self->{'info_only'}) {
104 # don't worry about any options etc
105 return bless $self, $class;
106 }
107
108 my $parser = new XML::Parser('Style' => 'Stream',
109 'PluginObj' => $self,
110 'Handlers' => {'Char' => \&Char,
111 'Start' => \&OAI_StartTag,
112 'End' => \&OAI_EndTag
113 });
114 $self->{'parser'} = $parser;
115
116 # make sure the tmp directory that we will use later exists
117 my $tmp_dir = "$ENV{GSDLHOME}/tmp";
118 if (! -e $tmp_dir) {
119 &util::mk_dir($tmp_dir);
120 }
121
122
123 # set up hashmap for individual items in get_doc_exts
124 # to make testing for matches easier
125
126 $self->{'lookup_exts'} = {};
127 my $get_doc_exts = $self->{'get_doc_exts'};
128
129 if ((defined $get_doc_exts) && ($get_doc_exts ne "")) {
130 my @exts = split(/,\s*/,$get_doc_exts);
131 foreach my $e (@exts) {
132 $self->{'lookup_exts'}->{lc($e)} = 1;
133 }
134 }
135
136
137 return bless $self, $class;
138}
139
140sub download
141{
142 my ($self) = shift (@_);
143 my ($hashGeneralOptions) = @_;
144
145## my $cmdWget = $strWgetOptions;
146
147 my $strOutputDir ="";
148 $strOutputDir = $hashGeneralOptions->{"cache_dir"};
149 my $strBasURL = $self->{'url'};
150 my $intMaxRecords = $self->{'max_records'};
151 my $blnDownloadDoc = $self->{'get_doc'};
152
153 print STDERR "<<Defined Maximum>>\n";
154
155 my $strIDs = $self->getOAIIDs($strBasURL);
156
157 if($strIDs eq "")
158 {
159 print STDERR "Error: No IDs found\n";
160 return 0;
161 }
162
163 my $aryIDs = $self->parseOAIIDs($strIDs);
164 my $intIDs = 0;
165 if($self->{'max_records'} < scalar(@$aryIDs))
166 {
167 $intIDs = $self->{'max_records'};
168 }
169 else
170 {
171 $intIDs = scalar(@$aryIDs);
172 }
173 print STDERR "<<Total number of record(s):$intIDs>>\n";
174
175 $self->getOAIRecords($aryIDs, $strOutputDir, $strBasURL, $intMaxRecords, $blnDownloadDoc);
176
177# my $tmp_file = &util::filename_cat($ENV{'GSDLHOME'},"tmp","oai.tmp");
178# &util::rm($tmp_file);
179
180 return 1;
181}
182
183sub getOAIIDs
184{
185 my ($self,$strBasURL) = @_;
186## my ($cmdWget);
187
188 my $wgetOptions = $self->getWgetOptions();
189
190 my $cmdWget = $wgetOptions;
191
192 print STDERR "Gathering OAI identifiers.....\n";
193
194 my $metadata_prefix = $self->{'metadata_prefix'};
195 $cmdWget .= " -q -O - \"$strBasURL?verb=ListIdentifiers&metadataPrefix=$metadata_prefix";
196
197 # if $set specified, add it in to URL
198 my $set = $self->{'set'};
199 $cmdWget .= "&set=$set" if ($set ne "");
200
201 $cmdWget .= "\" ";
202
203 my $accumulated_strIDs = "";
204 my $strIDs = $self->useWget($cmdWget);
205
206 if (!defined $strIDs or $strIDs eq "" ){
207 print STDERR "Server information is unavailable.\n";
208 print STDERR "<<Finished>>\n";
209 return;
210 }
211
212 print STDERR "<<Download Information>>\n";
213
214 $self->parse_xml($strIDs);
215
216 $accumulated_strIDs = $strIDs;
217
218 while ($strIDs =~ m/<resumptionToken.*?>\s*(.*?)\s*<\/resumptionToken>/) {
219 # top up list with further requests for IDs
220
221 my $resumption_token = $1;
222
223 $cmdWget = $wgetOptions;
224
225 $cmdWget .= " -q -O - \"$strBasURL?verb=ListIdentifiers&resumptionToken=$resumption_token\"";
226
227 $strIDs = $self->useWget($cmdWget);
228
229 $self->parse_xml($strIDs);
230
231 $accumulated_strIDs .= $strIDs;
232
233 my @accumulated_identifiers
234 = ($accumulated_strIDs =~ m/<identifier>(.*?)<\/identifier>/sg);
235
236 my $num_acc_identifiers = scalar(@accumulated_identifiers);
237 if ($num_acc_identifiers > $self->{'max_records'}) {
238 last;
239 }
240 }
241
242 return $accumulated_strIDs;
243}
244
245sub parseOAIIDs
246{
247 my ($self,$strIDs) = @_;
248
249 print STDERR "Parsing OAI identifiers.....\n";
250 $strIDs =~ s/^.*?<identifier>/<identifier>/s;
251 $strIDs =~ s/^(.*<\/identifier>).*$/$1/s;
252
253 my @aryIDs = ();
254
255 while ($strIDs =~ m/<identifier>(.*?)<\/identifier>(.*)$/s)
256 {
257 $strIDs = $2;
258 push(@aryIDs,$1);
259 }
260
261 return \@aryIDs;
262}
263
264sub dirFileSplit
265{
266 my ($self,$strFile) = @_;
267
268 my @aryDirs = split("[/\]",$strFile);
269
270 my $strLocalFile = pop(@aryDirs);
271 my $strSubDirs = join("/",@aryDirs);
272
273 return ($strSubDirs,$strLocalFile);
274}
275
276sub getOAIDoc
277{
278 my ($self,$strRecord, $oai_rec_filename) = @_;
279
280 print STDERR "Gathering source documents.....\n";
281 # look out for identifier tag in metadata section
282
283 if ($strRecord =~ m/<metadata>(.*)<\/metadata>/s)
284 {
285 my $strMetaTag = $1;
286 my $had_valid_url = 0;
287
288 while ($strMetaTag =~ s/<(dc:)?identifier>(.*?)<\/(dc:)?identifier>//is)
289 {
290 my $doc_id_url = $2;
291
292 next if ($doc_id_url !~ m/^(https?|ftp):\/\//);
293
294 my $orig_doc_id_url = $doc_id_url;
295 $had_valid_url = 1;
296
297 my ($doc_dir_url_prefix,$doc_id_tail) = ($doc_id_url =~ m/^(.*)\/(.*?)$/);
298 my $faked_ext = 0;
299 my $primary_doc_match = 0;
300
301 my ($id_file_ext) = ($doc_id_tail =~ m/\.([^\.]+)$/);
302
303 if (defined $id_file_ext) {
304 # cross-check this filename extension with get_doc_exts option
305 # if provided
306 my $lookup_exts = $self->{'lookup_exts'};
307
308 if (defined $lookup_exts->{lc($id_file_ext)}) {
309 # this initial URL matches requirement
310 $primary_doc_match = 1;
311 }
312 }
313 else {
314 $faked_ext = 1;
315 $id_file_ext = "html";
316 }
317
318
319 if ((!$primary_doc_match) && ($id_file_ext =~ m/^html?$/i)) {
320 # Download this doc if HTML, scan through it looking for a link
321 # that does match get_doc_exts
322
323
324 # 1. Generate a tmp name
325 my $tmp_filename = &util::get_tmp_filename();
326
327 # 2. Download it
328 my $wget_opts2 = $self->getWgetOptions();
329 my $wget_cmd2 = "$wget_opts2 --convert-links -O \"$tmp_filename\" \"$doc_id_url\"";
330
331 my ($stdout_and_err2,$error2,$follow2) = $self->useWgetMonitored($wget_cmd2);
332
333 if($error2 ne "")
334 {
335 print STDERR "Error occured while retrieving OAI source documents: $error2\n";
336 exit(-1);
337 }
338
339 if (defined $follow2) {
340 # src url was "redirected" to another place
341 # => pick up on this and make it the new doc_id_url
342 $doc_id_url = $follow2;
343 }
344
345 my $primary_doc_html = "";
346 if (open(HIN,"<$tmp_filename")) {
347 my $line;
348 while (defined ($line = <HIN>)) {
349 $primary_doc_html .= $line;
350 }
351 close(HIN);
352
353 # 3. Scan through it looking for match
354 #
355 # if got match, change $doc_id_url to this new URL and
356 # $id_file_ext to 'match'
357
358 my @href_links = ($primary_doc_html =~ m/href="(.*?)"/gsi);
359
360 my $lookup_exts = $self->{'lookup_exts'};
361
362 foreach my $href (@href_links) {
363 my ($ext) = ($href =~ m/\.([^\.]+)$/);
364
365 if ((defined $ext) && (defined $lookup_exts->{$ext})) {
366
367 if ($href !~ m/^(https?|ftp):\/\//) {
368 # link is within current site
369 my ($site_domain) = ($doc_id_url =~ m/^((?:https?|ftp):\/\/.*?)\//);
370
371 $href = "$site_domain$href";
372 }
373
374 $doc_id_url = $href;
375 $id_file_ext = $ext;
376 last;
377 }
378 }
379 }
380 else {
381 print STDERR "Error occurred while retrieving OAI source documents:\n";
382 print STDERR "$!\n";
383 }
384
385 if (-e $tmp_filename) {
386 &util::rm($tmp_filename);
387 }
388 }
389
390 my $download_doc_filename = $oai_rec_filename;
391 $download_doc_filename =~ s/\.oai$/\.$id_file_ext/;
392
393 my ($unused,$download_doc_file) = $self->dirFileSplit($download_doc_filename);
394
395 my $wget_opts = $self->getWgetOptions();
396 my $wget_cmd = "$wget_opts --convert-links -O \"$download_doc_filename\" \"$doc_id_url\"";
397
398 my ($stdout_and_err,$errors,$follow) = $self->useWgetMonitored($wget_cmd);
399
400 if($errors ne "")
401 {
402 print STDERR "Error occured while retriving OAI souce documents:\n";
403 print STDERR "$errors\n";
404 exit(-1);
405 }
406
407
408 $strRecord =~ s/<metadata>(.*?)<(dc:)?identifier>$orig_doc_id_url<\/(dc:)?identifier>(.*?)<\/metadata>/<metadata>$1<${2}identifier>$orig_doc_id_url<\/${2}identifier>\n <gi.Sourcedoc>$download_doc_file<\/gi.Sourcedoc>$4<\/metadata>/s;
409 }
410
411 if (!$had_valid_url)
412 {
413 print STDERR "\tNo souce document URL is specified in the OAI record (No (dc:)?identifier is provided)\n";
414 }
415 }
416 else
417 {
418 print STDERR "\tNo souce document URL is specified in the OAI record (No metadata field is provided)\n";
419 }
420
421 return $strRecord;
422}
423
424sub getOAIRecords
425{
426 my ($self,$aryIDs, $strOutputDir, $strBasURL, $intMaxRecords, $blnDownloadDoc) = @_;
427
428 my $intDocCounter = 0;
429
430 my $metadata_prefix = $self->{'metadata_prefix'};
431
432 foreach my $strID ( @$aryIDs)
433 {
434 print STDERR "Gathering OAI record with ID $strID.....\n";
435
436 my $wget_opts = $self->getWgetOptions();
437 my $cmdWget= "$wget_opts -q -O - \"$strBasURL?verb=GetRecord&metadataPrefix=$metadata_prefix&identifier=$strID\"";
438
439 my $strRecord = $self->useWget($cmdWget);
440
441 my @fileDirs = split(":",$strID);
442 my $local_id = pop @fileDirs;
443
444 # setup directories
445
446 $strOutputDir =~ s/"//g; #"
447
448 my $host =$self->{'url'};
449
450 $host =~ s/https?:\/\///g;
451
452 $host =~ s/:.*//g;
453
454 my $strFileURL = "$strOutputDir/$host/$local_id.oai";
455
456
457 # prepare subdirectory for record (if needed)
458 my ($strSubDirPath,$unused) = ("", "");
459
460 ($strSubDirPath,$unused) = $self->dirFileSplit($strFileURL);
461
462 &util::mk_all_dir($strSubDirPath);
463
464 my $ds = &util::get_dirsep();
465
466 if($blnDownloadDoc)
467 {
468 $strRecord = $self->getOAIDoc($strRecord,$strFileURL);
469 }
470
471 # save record
472 open (OAIOUT,">$strFileURL")
473 || die "Unable to save oai metadata record: $!\n";
474 print OAIOUT $strRecord;
475 close(OAIOUT);
476
477 print STDERR "Saving records to $strFileURL\n";
478 print STDERR "<<Done>>\n";
479 $intDocCounter ++;
480 last if ($intDocCounter >= $intMaxRecords);
481 }
482
483 ($intDocCounter >= $intMaxRecords) ?
484 print STDERR "Reached maximum download records, use -max_records to set the maximum.\n":
485 print STDERR "Complete download meta record from $strBasURL\n";
486
487 print STDERR "<<Finished>>\n";
488}
489
490sub url_information
491{
492 my ($self) = shift (@_);
493 if(!defined $self){ die "System Error: No \$self defined for url_information in OAIDownload\n";}
494
495 my $wgetOptions = $self->getWgetOptions();
496 my $strBaseCMD = $wgetOptions." -q -O - \"$self->{'url'}?_OPTS_\"";
497
498 my $strIdentify = "verb=Identify";
499 my $strListSets = "verb=ListSets";
500 my $strListMdFormats = "verb=ListMetadataFormats";
501
502 my $strIdentifyCMD = $strBaseCMD;
503 $strIdentifyCMD =~ s/_OPTS_/$strIdentify/;
504
505 my $strIdentifyText = $self->useWget($strIdentifyCMD);
506
507 if (!defined $strIdentifyText or $strIdentifyText eq "" ){
508 print STDERR "Server information is unavailable.\n";
509 print STDERR "<<Finished>>\n";
510 return;
511 }
512
513 print STDERR "General information:\n";
514 $self->parse_xml($strIdentifyText);
515 print STDERR "\n";
516
517 print STDERR "=" x 10, "\n";
518 print STDERR "Metadata Format Information (metadataPrefix):\n";
519 print STDERR "=" x 10, "\n";
520
521 my $strListMdFormatsCMD = $strBaseCMD;
522 $strListMdFormatsCMD =~ s/_OPTS_/$strListMdFormats/;
523 my $strListMdFormatsText = $self->useWget($strListMdFormatsCMD);
524
525 $self->parse_xml($strListMdFormatsText);
526 print STDERR "\n";
527
528 print STDERR "=" x 10, "\n";
529 print STDERR "List Information:\n";
530 print STDERR "=" x 10, "\n";
531
532 my $strListSetCMD = $strBaseCMD;
533 $strListSetCMD =~ s/_OPTS_/$strListSets/;
534 my $strListSetsText = $self->useWget($strListSetCMD);
535
536 $self->parse_xml($strListSetsText);
537}
538
539sub parse_xml
540{
541 my ($self) = shift (@_);
542 my ($xml_text) = @_;
543
544 #### change this to work directly from $xml_text
545
546 #Open a temporary file to store OAI information, and store the information to the temp file
547 my $name = &util::filename_cat($ENV{GSDLHOME},"tmp","oai.tmp");
548
549 open(*OAIOUT,"> $name");
550
551 print OAIOUT $xml_text;
552 close(OAIOUT);
553
554 $self->{'temp_file_name'} = $name;
555
556## print STDERR "**** xml text = $xml_text\n";
557
558 eval {
559 $self->{'parser'}->parsefile("$name");
560## $self->{'parser'}->parse($xml_text);
561 };
562
563 if ($@) {
564 die "OAI: Parsed file $name is not a well formed XML file ($@)\n";
565## die "OAI: Parsed text is not a well formed XML file ($@)\n";
566 }
567
568 unlink($self->{'temp_file_name'}) or die "Could not unlink $self->{'temp_file_name'}: $!";
569}
570
571####END
572#{
573# if($self->{'info'})
574# {
575# unlink($self->{'temp_file_name'}) or die "Could not unlink $self->{'temp_file_name'}: $!";
576# }
577#}
578
579# This Char function overrides the one in XML::Parser::Stream to overcome a
580# problem where $expat->{Text} is treated as the return value, slowing
581# things down significantly in some cases.
582sub Char {
583 use bytes; # Necessary to prevent encoding issues with XML::Parser 2.31+
584 $_[0]->{'Text'} .= $_[1];
585
586 my $self = $_[0]->{'PluginObj'};
587 if ((defined $self->{'subfield'} && ($self->{'subfield'} ne ""))) {
588 $self->{'text'} .= $_[1];
589 $self->{'text'} =~ s/[\n]|([ ]{2,})//g;
590 if($self->{'text'} ne "")
591 {
592 print STDERR " $self->{'subfield'}:($self->{'text'})\n";
593 }
594 }
595 return undef;
596}
597
598sub OAI_StartTag
599{
600 my ($expat, $element, %attr) = @_;
601
602 my $self = $expat->{'PluginObj'};
603 $self->{'subfield'} = $element;
604
605}
606
607sub OAI_EndTag
608{
609 my ($expat, $element) = @_;
610
611 my $self = $expat->{'PluginObj'};
612 $self->{'text'} = "";
613 $self->{'subfield'} = "";
614}
615
616sub error
617{
618 my ($self,$strFunctionName,$strError) = @_;
619 {
620 print "Error occoured in OAIDownload.pm\n".
621 "In Function:".$strFunctionName."\n".
622 "Error Message:".$strError."\n";
623 exit(-1);
624 }
625}
626
627
628
6291;
Note: See TracBrowser for help on using the repository browser.