]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Ingest.pm
Remove serial ingest references and services
[working/Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Ingest.pm
1 package OpenILS::Application::Ingest;
2 use OpenILS::Application;
3 use base qw/OpenILS::Application/;
4
5 use Unicode::Normalize;
6 use OpenSRF::EX qw/:try/;
7
8 use OpenSRF::AppSession;
9 use OpenSRF::Utils::SettingsClient;
10 use OpenSRF::Utils::Logger qw/:level/;
11
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::ScriptRunner;
14 use OpenILS::Utils::Fieldmapper;
15 use OpenSRF::Utils::JSON;
16
17 use OpenILS::Utils::Fieldmapper;
18
19 use XML::LibXML;
20 use XML::LibXSLT;
21 use Time::HiRes qw(time);
22
23 our %supported_formats = (
24     mods33    => {ns => 'http://www.loc.gov/mods/v3'},
25     mods32    => {ns => 'http://www.loc.gov/mods/v3'},
26     mods3    => {ns => 'http://www.loc.gov/mods/v3'},
27     mods    => {ns => 'http://www.loc.gov/mods/'},
28     marcxml    => {ns => 'http://www.loc.gov/MARC21/slim'},
29     srw_dc    => {ns => 'info:srw/schema/1/dc-schema'},
30     oai_dc    => {ns => 'http://www.openarchives.org/OAI/2.0/oai_dc/'},
31     rdf_dc    => {ns => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'},
32     atom    => {ns => 'http://www.w3.org/2005/Atom'},
33     rss091    => {ns => 'http://my.netscape.com/rdf/simple/0.9/'},
34     rss092    => {ns => ''},
35     rss093    => {ns => ''},
36     rss094    => {ns => ''},
37     rss10    => {ns => 'http://purl.org/rss/1.0/'},
38     rss11    => {ns => 'http://purl.org/net/rss1.1#'},
39     rss2    => {ns => ''},
40 );
41
42
43 my $log = 'OpenSRF::Utils::Logger';
44
45 my  $parser = XML::LibXML->new();
46 my  $xslt = XML::LibXSLT->new();
47
48 my  $mods_sheet;
49 my  $mads_sheet;
50 my  $xpathset = {};
51 sub initialize {}
52 sub child_init {}
53
54 sub post_init {
55
56     unless (keys %$xpathset) {
57         $log->debug("Running post_init", DEBUG);
58
59         my $xsldir = OpenSRF::Utils::SettingsClient->new->config_value(dirs => 'xsl');
60
61         unless ($supported_formats{mods}{xslt}) {
62             $log->debug("Loading MODS XSLT", DEBUG);
63              my $xslt_doc = $parser->parse_file( $xsldir . "/MARC21slim2MODS.xsl");
64             $supported_formats{mods}{xslt} = $xslt->parse_stylesheet( $xslt_doc );
65         }
66
67         unless ($supported_formats{mods3}{xslt}) {
68             $log->debug("Loading MODS v3 XSLT", DEBUG);
69              my $xslt_doc = $parser->parse_file( $xsldir . "/MARC21slim2MODS3.xsl");
70             $supported_formats{mods3}{xslt} = $xslt->parse_stylesheet( $xslt_doc );
71         }
72
73         unless ($supported_formats{mods32}{xslt}) {
74             $log->debug("Loading MODS v32 XSLT", DEBUG);
75              my $xslt_doc = $parser->parse_file( $xsldir . "/MARC21slim2MODS32.xsl");
76             $supported_formats{mods32}{xslt} = $xslt->parse_stylesheet( $xslt_doc );
77         }
78
79         unless ($supported_formats{mods33}{xslt}) {
80             $log->debug("Loading MODS v33 XSLT", DEBUG);
81              my $xslt_doc = $parser->parse_file( $xsldir . "/MARC21slim2MODS33.xsl");
82             $supported_formats{mods33}{xslt} = $xslt->parse_stylesheet( $xslt_doc );
83         }
84
85         my $req = OpenSRF::AppSession
86                 ->create('open-ils.cstore')
87                 
88                 # XXX testing new metabib field use for faceting
89                 #->request( 'open-ils.cstore.direct.config.metabib_field.search.atomic', { id => { '!=' => undef } } )
90                 ->request( 'open-ils.cstore.direct.config.metabib_field.search.atomic', { search_field => 't' } )
91
92                 ->gather(1);
93
94         if (ref $req and @$req) {
95             for my $f (@$req) {
96                 $xpathset->{ $f->field_class }->{ $f->name }->{xpath} = $f->xpath;
97                 $xpathset->{ $f->field_class }->{ $f->name }->{id} = $f->id;
98                 $xpathset->{ $f->field_class }->{ $f->name }->{format} = $f->format;
99                 $log->debug("Loaded XPath from DB: ".$f->field_class." => ".$f->name." : ".$f->xpath, DEBUG);
100             }
101         }
102     }
103 }
104
105 # --------------------------------------------------------------------------------
106 # Biblio ingest
107
108 package OpenILS::Application::Ingest::Biblio;
109 use base qw/OpenILS::Application::Ingest/;
110 use Unicode::Normalize;
111
112 sub rw_biblio_ingest_single_object {
113     my $self = shift;
114     my $client = shift;
115     my $bib = shift;
116
117     my ($blob) = $self->method_lookup("open-ils.ingest.full.biblio.object.readonly")->run($bib);
118     return undef unless ($blob);
119
120     $bib->fingerprint( $blob->{fingerprint}->{fingerprint} );
121     $bib->quality( $blob->{fingerprint}->{quality} );
122
123     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
124
125     my $xact = $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
126     my $tmp;
127
128     # update uri stuff ...
129
130     # gather URI call numbers for this record
131     my $uri_cns = $u->{call_number} = $cstore->request(
132         'open-ils.cstore.direct.asset.call_number.id_list.atomic' => { record => $bib->id, label => '##URI##' }
133     )->gather(1);
134
135     if (@$uri_cns) {
136         # gather the maps for those call numbers
137         my $uri_maps = $u->{call_number} = $cstore->request(
138             'open-ils.cstore.direct.asset.uri_call_number_map.id_list.atomic' => { call_number => $uri_cns }
139         )->gather(1);
140     
141         # delete the old maps
142         $cstore->request( 'open-ils.cstore.direct.asset.uri_call_number_map.delete' => $_ )->gather(1) for (@$uri_maps);
143     
144         # and delete the call numbers if there are no more URIs
145         if (!@{ $blob->{uri} }) {
146             $cstore->request( 'open-ils.cstore.direct.asset.call_number.delete' => $_ )->gather(1) for (@$uri_cns);
147         }
148     }
149
150     # now, add CNs, URIs and maps
151     my %new_cns_by_owner;
152     my %new_uris_by_owner;
153     for my $u ( @{ $blob->{uri} } ) {
154
155         my $owner = $u->{call_number}->owning_lib;
156
157         if ($u->{call_number}->isnew) {
158             if ($new_cns_by_owner{$owner}) {
159                 $u->{call_number} = $new_cns_by_owner{$owner};
160             } else {
161                 $u->{call_number}->clear_id;
162                 $u->{call_number} = $new_cns_by_owner{$owner} = $cstore->request(
163                     'open-ils.cstore.direct.asset.call_number.create' => $u->{call_number}
164                 )->gather(1);
165             }
166         }
167
168         if ($u->{uri}->isnew) {
169             if ($new_uris_by_owner{$owner}) {
170                 $u->{uri} = $new_uris_by_owner{$owner};
171             } else {
172                 $u->{uri} = $new_uris_by_owner{$owner} = $cstore->request(
173                     'open-ils.cstore.direct.asset.uri.create' => $u->{uri}
174                 )->gather(1);
175             }
176         }
177
178         # Check for an existing CN-URI map
179         $tmp = $cstore->request(
180             'open-ils.cstore.direct.asset.uri_call_number_map.id_list',
181             { call_number => $u->{call_number}->id, uri => $u->{uri}->id }
182         )->gather(1);
183
184         next if ($tmp);
185
186         my $umap = Fieldmapper::asset::uri_call_number_map->new;
187         $umap->uri($u->{uri}->id);
188         $umap->call_number($u->{call_number}->id);
189
190         $cstore->request( 'open-ils.cstore.direct.asset.uri_call_number_map.create' => $umap )->gather(1);
191     }
192
193     # update full_rec stuff ...
194     $tmp = $cstore->request(
195         'open-ils.cstore.direct.metabib.full_rec.id_list.atomic',
196         { record => $bib->id }
197     )->gather(1);
198
199     $cstore->request( 'open-ils.cstore.direct.metabib.full_rec.delete' => $_ )->gather(1) for (@$tmp);
200     $cstore->request( 'open-ils.cstore.direct.metabib.full_rec.create' => $_ )->gather(1) for (@{ $blob->{full_rec} });
201
202     # update rec_descriptor stuff ...
203     $tmp = $cstore->request(
204         'open-ils.cstore.direct.metabib.record_descriptor.id_list.atomic',
205         { record => $bib->id }
206     )->gather(1);
207
208     $cstore->request( 'open-ils.cstore.direct.metabib.record_descriptor.delete' => $_ )->gather(1) for (@$tmp);
209     $cstore->request( 'open-ils.cstore.direct.metabib.record_descriptor.create' => $blob->{descriptor} )->gather(1);
210
211     # deal with classed fields...
212     for my $class ( qw/title author subject keyword series/ ) {
213         $tmp = $cstore->request(
214             "open-ils.cstore.direct.metabib.${class}_field_entry.id_list.atomic",
215             { source => $bib->id }
216         )->gather(1);
217
218         $cstore->request( "open-ils.cstore.direct.metabib.${class}_field_entry.delete" => $_ )->gather(1) for (@$tmp);
219     }
220     for my $obj ( @{ $blob->{field_entries} } ) {
221         my $class = $obj->class_name;
222         $class =~ s/^Fieldmapper:://o;
223         $class =~ s/::/./go;
224         $cstore->request( "open-ils.cstore.direct.$class.create" => $obj )->gather(1);
225     }
226
227     # update MR map ...
228
229     $tmp = $cstore->request(
230         'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
231         { source => $bib->id }
232     )->gather(1);
233
234     $cstore->request( 'open-ils.cstore.direct.metabib.metarecord_source_map.delete' => $_->id )->gather(1) for (@$tmp);
235
236     # get the old MRs
237     my $old_mrs = $cstore->request(
238         'open-ils.cstore.direct.metabib.metarecord.search.atomic' => { id => [map { $_->metarecord } @$tmp] }
239     )->gather(1) if (@$tmp);
240
241     $old_mrs = [] if (!ref($old_mrs));
242
243     my $mr;
244     for my $m (@$old_mrs) {
245         if ($m->fingerprint eq $bib->fingerprint) {
246             $mr = $m;
247         } else {
248             my $others = $cstore->request(
249                 'open-ils.cstore.direct.metabib.metarecord_source_map.id_list.atomic' => { metarecord => $m->id }
250             )->gather(1);
251
252             if (!@$others) {
253                 $cstore->request(
254                     'open-ils.cstore.direct.metabib.metarecord.delete' => $m->id
255                 )->gather(1);
256             }
257
258             $m->isdeleted(1);
259         }
260     }
261
262     my $holds;
263     if (!$mr) {
264         # Get the matchin MR, if any.
265         $mr = $cstore->request(
266             'open-ils.cstore.direct.metabib.metarecord.search',
267             { fingerprint => $bib->fingerprint }
268         )->gather(1);
269
270         $holds = $cstore->request(
271             'open-ils.cstore.direct.action.hold_request.search.atomic',
272             { hold_type => 'M', target => [ map { $_->id } grep { $_->isdeleted } @$old_mrs ] }
273         )->gather(1) if (@$old_mrs);
274
275         if ($mr) {
276             for my $h (@$holds) {
277                 $h->target($mr);
278                 $cstore->request( 'open-ils.cstore.direct.action.hold_request.update' => $h )->gather(1);
279                 $h->ischanged(1);
280             }
281         }
282     }
283
284     if (!$mr) {
285         $mr = new Fieldmapper::metabib::metarecord;
286         $mr->fingerprint( $bib->fingerprint );
287         $mr->master_record( $bib->id );
288         $mr->id(
289             $cstore->request(
290                 "open-ils.cstore.direct.metabib.metarecord.create",
291                 $mr => { quiet => 'true' }
292             )->gather(1)
293         );
294
295         for my $h (grep { !$_->ischanged } @$holds) {
296             $h->target($mr);
297             $cstore->request( 'open-ils.cstore.direct.action.hold_request.update' => $h )->gather(1);
298         }
299     } else {
300         my $mrm = $cstore->request(
301             'open-ils.cstore.direct.metabib.metarecord_source_map.search.atomic',
302             { metarecord => $mr->id }
303         )->gather(1);
304
305         if (@$mrm) {
306             my $best = $cstore->request(
307                 "open-ils.cstore.direct.biblio.record_entry.search",
308                 { id => [ map { $_->source } @$mrm ] },
309                 { 'select'    => { bre => [ qw/id quality/ ] },
310                   order_by    => { bre => "quality desc" },
311                   limit        => 1,
312                 }
313             )->gather(1);
314
315             if ($best->quality > $bib->quality) {
316                 $mr->master_record($best->id);
317             } else {
318                 $mr->master_record($bib->id);
319             }
320         } else {
321             $mr->master_record($bib->id);
322         }
323
324         $mr->clear_mods;
325
326         $cstore->request( 'open-ils.cstore.direct.metabib.metarecord.update' => $mr )->gather(1);
327     }
328
329     my $mrm = new Fieldmapper::metabib::metarecord_source_map;
330     $mrm->source($bib->id);
331     $mrm->metarecord($mr->id);
332
333     $cstore->request( 'open-ils.cstore.direct.metabib.metarecord_source_map.create' => $mrm )->gather(1);
334     $cstore->request( 'open-ils.cstore.direct.biblio.record_entry.update' => $bib )->gather(1);
335
336     $cstore->request( 'open-ils.cstore.json_query.atomic' => { from => [ 'reporter.simple_rec_update', $bib->id ] } )->gather(1);
337
338     $cstore->request( 'open-ils.cstore.transaction.commit' )->gather(1) || return undef;;
339     $cstore->disconnect;
340
341     return $bib->id;
342 }
343 __PACKAGE__->register_method(  
344     api_name    => "open-ils.ingest.full.biblio.object",
345     method        => "rw_biblio_ingest_single_object",
346     api_level    => 1,
347     argc        => 1,
348 );                      
349
350 sub rw_biblio_ingest_single_record {
351     my $self = shift;
352     my $client = shift;
353     my $rec = shift;
354
355     OpenILS::Application::Ingest->post_init();
356     my $cstore = OpenSRF::AppSession->connect( 'open-ils.cstore' );
357     $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
358
359     my $r = $cstore->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rec )->gather(1);
360
361     $cstore->request('open-ils.cstore.transaction.rollback')->gather(1);
362     $cstore->disconnect;
363
364     return undef unless ($r and @$r);
365
366     return ($self->method_lookup("open-ils.ingest.full.biblio.object")->run($r))[0];
367 }
368 __PACKAGE__->register_method(  
369     api_name    => "open-ils.ingest.full.biblio.record",
370     method        => "rw_biblio_ingest_single_record",
371     api_level    => 1,
372     argc        => 1,
373 );                      
374
375 sub rw_biblio_ingest_record_list {
376     my $self = shift;
377     my $client = shift;
378     my @rec = ref($_[0]) ? @{ $_[0] } : @_ ;
379
380     OpenILS::Application::Ingest->post_init();
381     my $cstore = OpenSRF::AppSession->connect( 'open-ils.cstore' );
382     $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
383
384     my $r = $cstore->request( 'open-ils.cstore.direct.biblio.record_entry.search.atomic' => { id => \@rec } )->gather(1);
385
386     $cstore->request('open-ils.cstore.transaction.rollback')->gather(1);
387     $cstore->disconnect;
388
389     return undef unless ($r and @$r);
390
391     my $count = 0;
392     for (@$r) {
393         if (($self->method_lookup("open-ils.ingest.full.biblio.object")->run($_))[0]) {
394             $count++
395         }
396     }
397     return $count;
398 }
399 __PACKAGE__->register_method(  
400     api_name    => "open-ils.ingest.full.biblio.record_list",
401     method        => "rw_biblio_ingest_record_list",
402     api_level    => 1,
403     argc        => 1,
404 );                      
405
406 sub ro_biblio_ingest_single_object {
407     my $self = shift;
408     my $client = shift;
409     my $bib = shift;
410     my $xml = OpenILS::Application::AppUtils->entityize($bib->marc);
411     my $max_cn = shift;
412     my $max_uri = shift;
413
414     my $cstore = OpenSRF::AppSession->connect( 'open-ils.cstore' );
415
416     if (!$max_cn) {
417         my $cn = $cstore->request( 'open-ils.cstore.direct.asset.call_number.search' => { id => { '!=' => undef } }, { limit => 1, order_by => { acn => 'id desc' } } )->gather(1);
418         $max_cn = int($cn->id) + 1000;
419     }
420
421     if (!$max_uri) {
422         my $cn = $cstore->request( 'open-ils.cstore.direct.asset.call_number.search' => { id => { '!=' => undef } }, { limit => 1, order_by => { acn => 'id desc' } } )->gather(1);
423         $max_uri = int($cn->id) + 1000;
424     }
425
426     $cstore->disconnect;
427
428     my $document = $parser->parse_string($xml);
429
430     my @uris = $self->method_lookup("open-ils.ingest.856_uri.object")->run($bib, $max_cn, $max_uri);
431     my @mfr = $self->method_lookup("open-ils.ingest.flat_marc.biblio.xml")->run($document);
432     my @mXfe = $self->method_lookup("open-ils.ingest.extract.field_entry.all.xml")->run($document);
433     my ($fp) = $self->method_lookup("open-ils.ingest.fingerprint.xml")->run($xml);
434     my ($rd) = $self->method_lookup("open-ils.ingest.descriptor.xml")->run($xml);
435
436     $_->source($bib->id) for (@mXfe);
437     $_->record($bib->id) for (@mfr);
438     $rd->record($bib->id) if ($rd);
439
440     return { full_rec => \@mfr, field_entries => \@mXfe, fingerprint => $fp, descriptor => $rd, uri => \@uris };
441 }
442 __PACKAGE__->register_method(  
443     api_name    => "open-ils.ingest.full.biblio.object.readonly",
444     method        => "ro_biblio_ingest_single_object",
445     api_level    => 1,
446     argc        => 1,
447 );                      
448
449 sub ro_biblio_ingest_single_xml {
450     my $self = shift;
451     my $client = shift;
452     my $xml = OpenILS::Application::AppUtils->entityize(shift);
453
454     my $document = $parser->parse_string($xml);
455
456     my @mfr = $self->method_lookup("open-ils.ingest.flat_marc.biblio.xml")->run($document);
457     my @mXfe = $self->method_lookup("open-ils.ingest.extract.field_entry.all.xml")->run($document);
458     my ($fp) = $self->method_lookup("open-ils.ingest.fingerprint.xml")->run($xml);
459     my ($rd) = $self->method_lookup("open-ils.ingest.descriptor.xml")->run($xml);
460
461     return { full_rec => \@mfr, field_entries => \@mXfe, fingerprint => $fp, descriptor => $rd };
462 }
463 __PACKAGE__->register_method(  
464     api_name    => "open-ils.ingest.full.biblio.xml.readonly",
465     method        => "ro_biblio_ingest_single_xml",
466     api_level    => 1,
467     argc        => 1,
468 );                      
469
470 sub ro_biblio_ingest_single_record {
471     my $self = shift;
472     my $client = shift;
473     my $rec = shift;
474
475     OpenILS::Application::Ingest->post_init();
476     my $r = OpenSRF::AppSession
477             ->create('open-ils.cstore')
478             ->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rec )
479             ->gather(1);
480
481     return undef unless ($r and @$r);
482
483     my ($res) = $self->method_lookup("open-ils.ingest.full.biblio.xml.readonly")->run($r->marc);
484
485     $_->source($rec) for (@{$res->{field_entries}});
486     $_->record($rec) for (@{$res->{full_rec}});
487     $res->{descriptor}->record($rec);
488
489     return $res;
490 }
491 __PACKAGE__->register_method(  
492     api_name    => "open-ils.ingest.full.biblio.record.readonly",
493     method        => "ro_biblio_ingest_single_record",
494     api_level    => 1,
495     argc        => 1,
496 );                      
497
498 sub ro_biblio_ingest_stream_record {
499     my $self = shift;
500     my $client = shift;
501
502     OpenILS::Application::Ingest->post_init();
503
504     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
505
506     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
507     
508         my $rec = $resp->content;
509         last unless (defined $rec);
510
511         $log->debug("Running open-ils.ingest.full.biblio.record.readonly ...");
512         my ($res) = $self->method_lookup("open-ils.ingest.full.biblio.record.readonly")->run($rec);
513
514         $_->source($rec) for (@{$res->{field_entries}});
515         $_->record($rec) for (@{$res->{full_rec}});
516
517         $client->respond( $res );
518     }
519
520     return undef;
521 }
522 __PACKAGE__->register_method(  
523     api_name    => "open-ils.ingest.full.biblio.record_stream.readonly",
524     method        => "ro_biblio_ingest_stream_record",
525     api_level    => 1,
526     stream        => 1,
527 );                      
528
529 sub ro_biblio_ingest_stream_xml {
530     my $self = shift;
531     my $client = shift;
532
533     OpenILS::Application::Ingest->post_init();
534
535     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
536
537     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
538     
539         my $xml = $resp->content;
540         last unless (defined $xml);
541
542         $log->debug("Running open-ils.ingest.full.biblio.xml.readonly ...");
543         my ($res) = $self->method_lookup("open-ils.ingest.full.biblio.xml.readonly")->run($xml);
544
545         $client->respond( $res );
546     }
547
548     return undef;
549 }
550 __PACKAGE__->register_method(  
551     api_name    => "open-ils.ingest.full.biblio.xml_stream.readonly",
552     method        => "ro_biblio_ingest_stream_xml",
553     api_level    => 1,
554     stream        => 1,
555 );                      
556
557 sub rw_biblio_ingest_stream_import {
558     my $self = shift;
559     my $client = shift;
560
561     OpenILS::Application::Ingest->post_init();
562
563     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
564
565     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
566     
567         my $bib = $resp->content;
568         last unless (defined $bib);
569
570         $log->debug("Running open-ils.ingest.full.biblio.xml.readonly ...");
571         my ($res) = $self->method_lookup("open-ils.ingest.full.biblio.xml.readonly")->run($bib->marc);
572
573         $_->source($bib->id) for (@{$res->{field_entries}});
574         $_->record($bib->id) for (@{$res->{full_rec}});
575
576         $client->respond( $res );
577     }
578
579     return undef;
580 }
581 __PACKAGE__->register_method(  
582     api_name    => "open-ils.ingest.full.biblio.bib_stream.import",
583     method        => "rw_biblio_ingest_stream_import",
584     api_level    => 1,
585     stream        => 1,
586 );                      
587
588
589 # --------------------------------------------------------------------------------
590 # Authority ingest
591
592 package OpenILS::Application::Ingest::Authority;
593 use base qw/OpenILS::Application::Ingest/;
594 use Unicode::Normalize;
595
596 sub rw_authority_ingest_single_object {
597     my $self = shift;
598     my $client = shift;
599     my $auth = shift;
600
601     my ($blob) = $self->method_lookup("open-ils.ingest.full.authority.object.readonly")->run($auth);
602     return undef unless ($blob);
603
604     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
605
606     my $xact = $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
607     my $tmp;
608
609     # update full_rec stuff ...
610     $tmp = $cstore->request(
611         'open-ils.cstore.direct.authority.full_rec.id_list.atomic',
612         { record => $auth->id }
613     )->gather(1);
614
615     $cstore->request( 'open-ils.cstore.direct.authority.full_rec.delete' => $_ )->gather(1) for (@$tmp);
616     $cstore->request( 'open-ils.cstore.direct.authority.full_rec.create' => $_ )->gather(1) for (@{ $blob->{full_rec} });
617
618     # XXX when we start extracting authority descriptors and adding sources ...
619     #
620     # update rec_descriptor stuff ...
621     #$tmp = $cstore->request(
622     #    'open-ils.cstore.direct.authority.record_descriptor.id_list.atomic',
623     #    { record => $auth->id }
624     #)->gather(1);
625     #
626     #$cstore->request( 'open-ils.cstore.direct.authority.record_descriptor.delete' => $_ )->gather(1) for (@$tmp);
627     #$cstore->request( 'open-ils.cstore.direct.authority.record_descriptor.create' => $blob->{descriptor} )->gather(1);
628     #$cstore->request( 'open-ils.cstore.direct.authority.record_entry.update' => $auth )->gather(1);
629
630     $cstore->request( 'open-ils.cstore.transaction.commit' )->gather(1) || return undef;;
631     $cstore->disconnect;
632
633     return $auth->id;
634 }
635 __PACKAGE__->register_method(  
636     api_name    => "open-ils.ingest.full.authority.object",
637     method        => "rw_authority_ingest_single_object",
638     api_level    => 1,
639     argc        => 1,
640 );                      
641
642 sub rw_authority_ingest_single_record {
643     my $self = shift;
644     my $client = shift;
645     my $rec = shift;
646
647     OpenILS::Application::Ingest->post_init();
648     my $cstore = OpenSRF::AppSession->connect( 'open-ils.cstore' );
649     $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
650
651     my $r = $cstore->request( 'open-ils.cstore.direct.authority.record_entry.retrieve' => $rec )->gather(1);
652
653     $cstore->request('open-ils.cstore.transaction.rollback')->gather(1);
654     $cstore->disconnect;
655
656     return undef unless ($r and @$r);
657
658     return ($self->method_lookup("open-ils.ingest.full.authority.object")->run($r))[0];
659 }
660 __PACKAGE__->register_method(  
661     api_name    => "open-ils.ingest.full.authority.record",
662     method        => "rw_authority_ingest_single_record",
663     api_level    => 1,
664     argc        => 1,
665 );                      
666
667 sub ro_authority_ingest_single_object {
668     my $self = shift;
669     my $client = shift;
670     my $bib = shift;
671     my $xml = OpenILS::Application::AppUtils->entityize($bib->marc);
672
673     my $document = $parser->parse_string($xml);
674
675     my @mfr = $self->method_lookup("open-ils.ingest.flat_marc.authority.xml")->run($document);
676
677     $_->record($bib->id) for (@mfr);
678
679     return { full_rec => \@mfr };
680 }
681 __PACKAGE__->register_method(  
682     api_name    => "open-ils.ingest.full.authority.object.readonly",
683     method        => "ro_authority_ingest_single_object",
684     api_level    => 1,
685     argc        => 1,
686 );                      
687
688 sub ro_authority_ingest_single_xml {
689     my $self = shift;
690     my $client = shift;
691     my $xml = OpenILS::Application::AppUtils->entityize(shift);
692
693     my $document = $parser->parse_string($xml);
694
695     my @mfr = $self->method_lookup("open-ils.ingest.flat_marc.authority.xml")->run($document);
696
697     return { full_rec => \@mfr };
698 }
699 __PACKAGE__->register_method(  
700     api_name    => "open-ils.ingest.full.authority.xml.readonly",
701     method        => "ro_authority_ingest_single_xml",
702     api_level    => 1,
703     argc        => 1,
704 );                      
705
706 sub ro_authority_ingest_single_record {
707     my $self = shift;
708     my $client = shift;
709     my $rec = shift;
710
711     OpenILS::Application::Ingest->post_init();
712     my $r = OpenSRF::AppSession
713             ->create('open-ils.cstore')
714             ->request( 'open-ils.cstore.direct.authority.record_entry.retrieve' => $rec )
715             ->gather(1);
716
717     return undef unless ($r and @$r);
718
719     my ($res) = $self->method_lookup("open-ils.ingest.full.authority.xml.readonly")->run($r->marc);
720
721     $_->record($rec) for (@{$res->{full_rec}});
722     $res->{descriptor}->record($rec);
723
724     return $res;
725 }
726 __PACKAGE__->register_method(  
727     api_name    => "open-ils.ingest.full.authority.record.readonly",
728     method        => "ro_authority_ingest_single_record",
729     api_level    => 1,
730     argc        => 1,
731 );                      
732
733 sub ro_authority_ingest_stream_record {
734     my $self = shift;
735     my $client = shift;
736
737     OpenILS::Application::Ingest->post_init();
738
739     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
740
741     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
742     
743         my $rec = $resp->content;
744         last unless (defined $rec);
745
746         $log->debug("Running open-ils.ingest.full.authority.record.readonly ...");
747         my ($res) = $self->method_lookup("open-ils.ingest.full.authority.record.readonly")->run($rec);
748
749         $_->record($rec) for (@{$res->{full_rec}});
750
751         $client->respond( $res );
752     }
753
754     return undef;
755 }
756 __PACKAGE__->register_method(  
757     api_name    => "open-ils.ingest.full.authority.record_stream.readonly",
758     method        => "ro_authority_ingest_stream_record",
759     api_level    => 1,
760     stream        => 1,
761 );                      
762
763 sub ro_authority_ingest_stream_xml {
764     my $self = shift;
765     my $client = shift;
766
767     OpenILS::Application::Ingest->post_init();
768
769     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
770
771     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
772     
773         my $xml = $resp->content;
774         last unless (defined $xml);
775
776         $log->debug("Running open-ils.ingest.full.authority.xml.readonly ...");
777         my ($res) = $self->method_lookup("open-ils.ingest.full.authority.xml.readonly")->run($xml);
778
779         $client->respond( $res );
780     }
781
782     return undef;
783 }
784 __PACKAGE__->register_method(  
785     api_name    => "open-ils.ingest.full.authority.xml_stream.readonly",
786     method        => "ro_authority_ingest_stream_xml",
787     api_level    => 1,
788     stream        => 1,
789 );                      
790
791 sub rw_authority_ingest_stream_import {
792     my $self = shift;
793     my $client = shift;
794
795     OpenILS::Application::Ingest->post_init();
796
797     my $ses = OpenSRF::AppSession->create('open-ils.cstore');
798
799     while (my ($resp) = $client->recv( count => 1, timeout => 5 )) {
800     
801         my $bib = $resp->content;
802         last unless (defined $bib);
803
804         $log->debug("Running open-ils.ingest.full.authority.xml.readonly ...");
805         my ($res) = $self->method_lookup("open-ils.ingest.full.authority.xml.readonly")->run($bib->marc);
806
807         $_->record($bib->id) for (@{$res->{full_rec}});
808
809         $client->respond( $res );
810     }
811
812     return undef;
813 }
814 __PACKAGE__->register_method(  
815     api_name    => "open-ils.ingest.full.authority.bib_stream.import",
816     method        => "rw_authority_ingest_stream_import",
817     api_level    => 1,
818     stream        => 1,
819 );                      
820
821 # --------------------------------------------------------------------------------
822 # MARC index extraction
823
824 package OpenILS::Application::Ingest::XPATH;
825 use base qw/OpenILS::Application::Ingest/;
826 use Unicode::Normalize;
827
828 # give this an XML documentElement and an XPATH expression
829 sub xpath_to_string {
830     my $xml = shift;
831     my $xpath = shift;
832     my $ns_uri = shift;
833     my $ns_prefix = shift;
834     my $unique = shift;
835
836     $xml->setNamespace( $ns_uri, $ns_prefix, 1 ) if ($ns_uri && $ns_prefix);
837
838     my $string = "";
839
840     # grab the set of matching nodes
841     my @nodes = $xml->findnodes( $xpath );
842     for my $value (@nodes) {
843
844         # grab all children of the node
845         my @children = $value->childNodes();
846         for my $child (@children) {
847
848             # add the childs content to the growing buffer
849             my $content = quotemeta($child->textContent);
850             next if ($unique && $string =~ /$content/);  # uniquify the values
851             $string .= $child->textContent . " ";
852         }
853         if( ! @children ) {
854             $string .= $value->textContent . " ";
855         }
856     }
857
858     $string =~ s/(\w+)\/(\w+)/$1 $2/sgo;
859     # Split date ranges and ISSNs on the hyphen
860     $string =~ s/(\d{4})-(\d{3,4}x?)/ $1 $2 /goi;
861
862     return NFD($string);
863 }
864
865 sub class_index_string_xml {
866     my $self = shift;
867     my $client = shift;
868     my $xml = shift;
869     my @classes = @_;
870
871     OpenILS::Application::Ingest->post_init();
872     $xml = $parser->parse_string(OpenILS::Application::AppUtils->entityize($xml)) unless (ref $xml);
873
874     my %transform_cache;
875     
876     for my $class (@classes) {
877         my $class_constructor = "Fieldmapper::metabib::${class}_field_entry";
878         for my $type ( keys %{ $xpathset->{$class} } ) {
879
880             my $def = $xpathset->{$class}->{$type};
881             my $sf = $OpenILS::Application::Ingest::supported_formats{$def->{format}};
882
883             my $document = $xml;
884
885             if ($sf->{xslt}) {
886                 $document = $transform_cache{$def->{format}} || $sf->{xslt}->transform($xml);
887                 $transform_cache{$def->{format}} = $document;
888             }
889
890             my $value =  xpath_to_string(
891                     $document->documentElement    => $def->{xpath},
892                     $sf->{ns}            => $def->{format},
893                     1
894             );
895
896             next unless $value;
897
898             $value = NFD($value);
899             $value =~ s/\pM+//sgo;
900             $value =~ s/\pC+//sgo;
901             $value =~ s/\W+$//sgo;
902
903             $value =~ s/\b\.+\b//sgo;
904             $value = lc($value);
905
906             my $fm = $class_constructor->new;
907             $fm->value( $value );
908             $fm->field( $xpathset->{$class}->{$type}->{id} );
909             $client->respond($fm);
910         }
911     }
912     return undef;
913 }
914 __PACKAGE__->register_method(  
915     api_name    => "open-ils.ingest.field_entry.class.xml",
916     method        => "class_index_string_xml",
917     api_level    => 1,
918     argc        => 2,
919     stream        => 1,
920 );                      
921
922 sub class_index_string_record {
923     my $self = shift;
924     my $client = shift;
925     my $rec = shift;
926     my @classes = shift;
927
928     OpenILS::Application::Ingest->post_init();
929     my $r = OpenSRF::AppSession
930             ->create('open-ils.cstore')
931             ->request( 'open-ils.cstore.direct.authority.record_entry.retrieve' => $rec )
932             ->gather(1);
933
934     return undef unless ($r and @$r);
935
936     for my $fm ($self->method_lookup("open-ils.ingest.field_entry.class.xml")->run($r->marc, @classes)) {
937         $fm->source($rec);
938         $client->respond($fm);
939     }
940     return undef;
941 }
942 __PACKAGE__->register_method(  
943     api_name    => "open-ils.ingest.field_entry.class.record",
944     method        => "class_index_string_record",
945     api_level    => 1,
946     argc        => 2,
947     stream        => 1,
948 );                      
949
950 sub all_index_string_xml {
951     my $self = shift;
952     my $client = shift;
953     my $xml = shift;
954
955     for my $fm ($self->method_lookup("open-ils.ingest.field_entry.class.xml")->run($xml, keys(%$xpathset))) {
956         $client->respond($fm);
957     }
958     return undef;
959 }
960 __PACKAGE__->register_method(  
961     api_name    => "open-ils.ingest.extract.field_entry.all.xml",
962     method        => "all_index_string_xml",
963     api_level    => 1,
964     argc        => 1,
965     stream        => 1,
966 );                      
967
968 sub all_index_string_record {
969     my $self = shift;
970     my $client = shift;
971     my $rec = shift;
972
973     OpenILS::Application::Ingest->post_init();
974     my $r = OpenSRF::AppSession
975             ->create('open-ils.cstore')
976             ->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rec )
977             ->gather(1);
978
979     return undef unless ($r and @$r);
980
981     for my $fm ($self->method_lookup("open-ils.ingest.field_entry.class.xml")->run($r->marc, keys(%$xpathset))) {
982         $fm->source($rec);
983         $client->respond($fm);
984     }
985     return undef;
986 }
987 __PACKAGE__->register_method(  
988     api_name    => "open-ils.ingest.extract.field_entry.all.record",
989     method        => "all_index_string_record",
990     api_level    => 1,
991     argc        => 1,
992     stream        => 1,
993 );                      
994
995 # --------------------------------------------------------------------------------
996 # Flat MARC
997
998 package OpenILS::Application::Ingest::FlatMARC;
999 use base qw/OpenILS::Application::Ingest/;
1000 use Unicode::Normalize;
1001
1002
1003 sub _marcxml_to_full_rows {
1004
1005     my $marcxml = shift;
1006     my $xmltype = shift || 'metabib';
1007
1008     my $type = "Fieldmapper::${xmltype}::full_rec";
1009
1010     my @ns_list;
1011     
1012     my ($root) = $marcxml->findnodes('//*[local-name()="record"]');
1013
1014     for my $tagline ( @{$root->getChildrenByTagName("leader")} ) {
1015         next unless $tagline;
1016         _special_tag_to_full_rows($type, $tagline, \@ns_list, 'LDR');
1017     }
1018
1019     for my $tagline ( @{$root->getChildrenByTagName("controlfield")} ) {
1020         next unless $tagline;
1021         _special_tag_to_full_rows($type, $tagline, \@ns_list, $tagline->getAttribute( "tag" ));
1022     }
1023
1024     for my $tagline ( @{$root->getChildrenByTagName("datafield")} ) {
1025         next unless $tagline;
1026         _data_tag_to_full_rows($type, $tagline, \@ns_list, $tagline->getAttribute( "tag" ));
1027
1028         if ($xmltype eq 'metabib' and $tag eq '245') {
1029             _data_tag_to_full_rows($type, $tagline, \@ns_list, 'tnf');
1030         }
1031     }
1032
1033     $log->debug("Returning ".scalar(@ns_list)." Fieldmapper nodes from $xmltype xml");
1034     return @ns_list;
1035 }
1036
1037 =head2 _special_tag_to_full_rows
1038
1039 Converts a leader or control field to a set of normalized values
1040
1041 =cut
1042
1043 sub _special_tag_to_full_rows {
1044     my $type = shift;
1045     my $tagline = shift;
1046     my $ns_list = shift;
1047     my $tagname = shift;
1048
1049     my $ns = $type->new;
1050
1051     $ns->tag( $tagname );
1052     my $val = $tagline->textContent;
1053     $val = NFD($val);
1054     $val =~ s/\pM+//sgo;
1055     $val =~ s/\pC+//sgo;
1056     $val =~ s/\W+$//sgo;
1057     $ns->value( $val );
1058
1059     push @$ns_list, $ns;
1060 }
1061
1062 =head2 _data_tag_to_full_rows
1063
1064 Converts a data field to a set of normalized values
1065
1066 =cut
1067
1068 sub _data_tag_to_full_rows {
1069     my $type = shift;
1070     my $tagline = shift;
1071     my $ns_list = shift;
1072     my $tag = shift;
1073
1074     my $ind1 = $tagline->getAttribute( "ind1" );
1075     my $ind2 = $tagline->getAttribute( "ind2" );
1076
1077     for my $data ( @{$tagline->getChildrenByTagName('subfield')} ) {
1078         next unless $data;
1079
1080         my $ns = $type->new;
1081
1082         $ns->tag( $tag );
1083         $ns->ind1( $ind1 );
1084         $ns->ind2( $ind2 );
1085         $ns->subfield( $data->getAttribute( "code" ) );
1086         my $val = $data->textContent;
1087         $val = NFD($val);
1088         $val =~ s/\pM+//sgo;
1089         $val =~ s/\pC+//sgo;
1090         $val =~ s/\W+$//sgo;
1091         # Split date ranges and ISSNs on the hyphen
1092         $val =~ s/(\d{4})-(\d{3,4}x?)/ $1 $2 /goi;
1093         $val =~ s/(\w+)\/(\w+)/$1 $2/sgo;
1094         $ns->value( lc($val) );
1095
1096         push @$ns_list, $ns;
1097     }
1098 }
1099
1100 sub flat_marc_xml {
1101     my $self = shift;
1102     my $client = shift;
1103     my $xml = shift;
1104
1105     $log->debug("processing [$xml]");
1106
1107     $xml = $parser->parse_string(OpenILS::Application::AppUtils->entityize($xml)) unless (ref $xml);
1108
1109     my $type = 'metabib';
1110     $type = 'authority' if ($self->api_name =~ /authority/o);
1111
1112     OpenILS::Application::Ingest->post_init();
1113
1114     $client->respond($_) for (_marcxml_to_full_rows($xml, $type));
1115     return undef;
1116 }
1117 __PACKAGE__->register_method(  
1118     api_name    => "open-ils.ingest.flat_marc.authority.xml",
1119     method        => "flat_marc_xml",
1120     api_level    => 1,
1121     argc        => 1,
1122     stream        => 1,
1123 );                      
1124 __PACKAGE__->register_method(  
1125     api_name    => "open-ils.ingest.flat_marc.biblio.xml",
1126     method        => "flat_marc_xml",
1127     api_level    => 1,
1128     argc        => 1,
1129     stream        => 1,
1130 );                      
1131
1132 sub flat_marc_record {
1133     my $self = shift;
1134     my $client = shift;
1135     my $rec = shift;
1136
1137     my $type = 'biblio';
1138     $type = 'authority' if ($self->api_name =~ /authority/o);
1139
1140     OpenILS::Application::Ingest->post_init();
1141     my $r = OpenSRF::AppSession
1142             ->create('open-ils.cstore')
1143             ->request( "open-ils.cstore.direct.${type}.record_entry.retrieve" => $rec )
1144             ->gather(1);
1145
1146
1147     return undef unless ($r and $r->marc);
1148
1149     my @rows = $self->method_lookup("open-ils.ingest.flat_marc.$type.xml")->run($r->marc);
1150     for my $row (@rows) {
1151         $client->respond($row);
1152         $log->debug(OpenSRF::Utils::JSON->perl2JSON($row), DEBUG);
1153     }
1154     return undef;
1155 }
1156 __PACKAGE__->register_method(  
1157     api_name    => "open-ils.ingest.flat_marc.biblio.record_entry",
1158     method        => "flat_marc_record",
1159     api_level    => 1,
1160     argc        => 1,
1161     stream        => 1,
1162 );                      
1163 __PACKAGE__->register_method(  
1164     api_name    => "open-ils.ingest.flat_marc.authority.record_entry",
1165     method        => "flat_marc_record",
1166     api_level    => 1,
1167     argc        => 1,
1168     stream        => 1,
1169 );                      
1170
1171 # --------------------------------------------------------------------------------
1172 # URI extraction
1173
1174 package OpenILS::Application::Ingest::Biblio::URI;
1175 use base qw/OpenILS::Application::Ingest/;
1176 use Unicode::Normalize;
1177 use OpenSRF::EX qw/:try/;
1178
1179
1180 sub _extract_856_uris {
1181
1182     my $rec   = shift;
1183     my $max_cn = shift;
1184     my $max_uri = shift;
1185     my @objects;
1186     
1187     my $recid = $rec->id;
1188     my $marcxml = $rec->marc;
1189
1190     my $document = $parser->parse_string($marcxml);
1191     my @nodes = $document->findnodes('//*[local-name()="datafield" and @tag="856" and (@ind1="4" or @ind1="1") and (@ind2="0" or @ind2="1")]');
1192
1193     my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1194
1195     my %cn_cache;
1196
1197     for my $node (@nodes) {
1198         # first, is there a URI?
1199         my $href = $node->findvalue('*[local-name()="subfield" and @code="u"]/text()');
1200         next unless ($href);
1201
1202         # now, find the best possible label
1203         my $label = $node->findvalue('*[local-name()="subfield" and @code="y"]/text()');
1204         $label ||= $node->findvalue('*[local-name()="subfield" and @code="3"]/text()');
1205         $label ||= $href;
1206
1207         # look for use info
1208         my $use = $node->findvalue('*[local-name()="subfield" and @code="z"]/text()');
1209         $use ||= $node->findvalue('*[local-name()="subfield" and @code="2"]/text()');
1210         $use ||= $node->findvalue('*[local-name()="subfield" and @code="n"]/text()');
1211
1212         # moving on to the URI owner
1213         my $owner = $node->findvalue('*[local-name()="subfield" and @code="9"]/text()'); # Evergreen special sauce
1214         $owner ||= $node->findvalue('*[local-name()="subfield" and @code="w"]/text()');
1215         $owner ||= $node->findvalue('*[local-name()="subfield" and @code="n"]/text()');
1216
1217         $owner =~ s/^.*?\((\w+)\).*$/$1/o; # unwrap first paren-enclosed string and then ...
1218
1219         # no owner? skip it :(
1220         next unless ($owner);
1221
1222         my $org = $cstore
1223             ->request( 'open-ils.cstore.direct.actor.org_unit.search' => { shortname => $owner} )
1224             ->gather(1);
1225
1226         next unless ($org);
1227
1228         # now we can construct the uri object
1229         my $uri = $cstore
1230             ->request( 'open-ils.cstore.direct.asset.uri.search' => { label => $label, href => $href, use_restriction => $use, active => 't' } )
1231             ->gather(1);
1232
1233         if (!$uri) {
1234             $uri = Fieldmapper::asset::uri->new;
1235             $uri->isnew( 1 );
1236             $uri->id( $$max_uri++ );
1237             $uri->label($label);
1238             $uri->href($href);
1239             $uri->active('t');
1240             $uri->use_restriction($use);
1241         }
1242
1243         # see if we need to create a call number
1244         my $cn = $cn_cache{$org->id};
1245         $cn = $cn->clone if ($cn);
1246         $cn->clear_isnew if ($cn);
1247
1248         $cn ||= $cstore
1249             ->request( 'open-ils.cstore.direct.asset.call_number.search' => { owning_lib => $org->id, record => $recid, label => '##URI##' } )
1250             ->gather(1);
1251
1252         if (!$cn) {
1253             $cn = Fieldmapper::asset::call_number->new;
1254             $cn->isnew( 1 );
1255             $cn->deleted('f');
1256             $cn->id( $$max_cn++ );
1257             $cn->owning_lib( $org->id );
1258             $cn->record( $recid );
1259             $cn->create_date( 'now' );
1260             $cn->creator( $rec->creator );
1261             $cn->editor( $rec->editor );
1262             $cn->edit_date( 'now' );
1263             $cn->label( '##URI##' );
1264         }
1265
1266         $cn_cache{$org->id} = $cn;
1267
1268         push @objects, { uri => $uri, call_number => $cn };
1269     }
1270
1271     $log->debug("Returning ".scalar(@objects)." URI nodes for record $recid");
1272     $cstore->disconnect;
1273     return @objects;
1274 }
1275
1276 sub get_uris_record {
1277     my $self = shift;
1278     my $client = shift;
1279     my $rec = shift;
1280
1281     OpenILS::Application::Ingest->post_init();
1282     my $r = OpenSRF::AppSession
1283             ->create('open-ils.cstore')
1284             ->request( "open-ils.cstore.direct.biblio.record_entry.retrieve" => $rec )
1285             ->gather(1);
1286
1287     return undef unless ($r and $r->marc);
1288
1289     $client->respond($_) for (_extract_856_uris($r));
1290     return undef;
1291 }
1292 __PACKAGE__->register_method(  
1293     api_name    => "open-ils.ingest.856_uri.record",
1294     method        => "get_uris_record",
1295     api_level    => 1,
1296     argc        => 1,
1297     stream        => 1,
1298 );                      
1299
1300 sub get_uris_object {
1301     my $self = shift;
1302     my $client = shift;
1303     my $obj = shift;
1304     my $max_cn = shift;
1305     my $max_uri = shift;
1306
1307     return undef unless ($obj and $obj->marc);
1308
1309     $client->respond($_) for (_extract_856_uris($obj, \$max_cn, \$max_uri));
1310     return undef;
1311 }
1312 __PACKAGE__->register_method(  
1313     api_name    => "open-ils.ingest.856_uri.object",
1314     method        => "get_uris_object",
1315     api_level    => 1,
1316     argc        => 1,
1317     stream        => 1,
1318 );                      
1319
1320
1321 # --------------------------------------------------------------------------------
1322 # Fingerprinting
1323
1324 package OpenILS::Application::Ingest::Biblio::Fingerprint;
1325 use base qw/OpenILS::Application::Ingest/;
1326 use Unicode::Normalize;
1327 use OpenSRF::EX qw/:try/;
1328
1329 sub biblio_fingerprint_record {
1330     my $self = shift;
1331     my $client = shift;
1332     my $rec = shift;
1333
1334     OpenILS::Application::Ingest->post_init();
1335
1336     my $r = OpenSRF::AppSession
1337             ->create('open-ils.cstore')
1338             ->request( 'open-ils.cstore.direct.biblio.record_entry.retrieve' => $rec )
1339             ->gather(1);
1340
1341     return undef unless ($r and $r->marc);
1342
1343     my ($fp) = $self->method_lookup('open-ils.ingest.fingerprint.xml')->run($r->marc);
1344     $log->debug("Returning [$fp] as fingerprint for record $rec", INFO);
1345     $fp->{quality} = int($fp->{quality});
1346     return $fp;
1347 }
1348 __PACKAGE__->register_method(  
1349     api_name    => "open-ils.ingest.fingerprint.record",
1350     method        => "biblio_fingerprint_record",
1351     api_level    => 1,
1352     argc        => 1,
1353 );                      
1354
1355 our $fp_script;
1356 sub biblio_fingerprint {
1357     my $self = shift;
1358     my $client = shift;
1359     my $xml = OpenILS::Application::AppUtils->entityize(shift);
1360
1361     $log->internal("Got MARC [$xml]");
1362
1363     if(!$fp_script) {
1364         my @pfx = ( "apps", "open-ils.ingest","app_settings" );
1365         my $conf = OpenSRF::Utils::SettingsClient->new;
1366
1367         my $libs        = $conf->config_value(@pfx, 'script_path');
1368         my $script_file = $conf->config_value(@pfx, 'scripts', 'biblio_fingerprint');
1369         my $script_libs = (ref($libs)) ? $libs : [$libs];
1370
1371         $log->debug("Loading script $script_file for biblio fingerprinting...");
1372         
1373         $fp_script = new OpenILS::Utils::ScriptRunner
1374             ( file        => $script_file,
1375               paths        => $script_libs,
1376               reset_count    => 100 );
1377     }
1378
1379     $fp_script->insert('environment' => {marc => $xml} => 1);
1380
1381     my $res = $fp_script->run || ($log->error( "Fingerprint script died!  $@" ) && return undef);
1382     $log->debug("Script for biblio fingerprinting completed successfully...");
1383
1384     return $res;
1385 }
1386 __PACKAGE__->register_method(  
1387     api_name    => "open-ils.ingest.fingerprint.xml",
1388     method        => "biblio_fingerprint",
1389     api_level    => 1,
1390     argc        => 1,
1391 );                      
1392
1393 our $rd_script;
1394 sub biblio_descriptor {
1395     my $self = shift;
1396     my $client = shift;
1397     my $xml = OpenILS::Application::AppUtils->entityize(shift);
1398
1399     $log->internal("Got MARC [$xml]");
1400
1401     if(!$rd_script) {
1402         my @pfx = ( "apps", "open-ils.ingest","app_settings" );
1403         my $conf = OpenSRF::Utils::SettingsClient->new;
1404
1405         my $libs        = $conf->config_value(@pfx, 'script_path');
1406         my $script_file = $conf->config_value(@pfx, 'scripts', 'biblio_descriptor');
1407         my $script_libs = (ref($libs)) ? $libs : [$libs];
1408
1409         $log->debug("Loading script $script_file for biblio descriptor extraction...");
1410         
1411         $rd_script = new OpenILS::Utils::ScriptRunner
1412             ( file        => $script_file,
1413               paths        => $script_libs,
1414               reset_count    => 100 );
1415     }
1416
1417     $log->debug("Setting up environment for descriptor extraction script...");
1418     $rd_script->insert('environment.marc' => $xml => 1);
1419     $log->debug("Environment building complete...");
1420
1421     my $res = $rd_script->run || ($log->error( "Descriptor script died!  $@" ) && return undef);
1422     $log->debug("Script for biblio descriptor extraction completed successfully");
1423
1424     my $d1 = $res->date1;
1425     if ($d1 && $d1 ne '    ') {
1426         $d1 =~ tr/ux/00/;
1427         $res->date1( $d1 );
1428     }
1429
1430     my $d2 = $res->date2;
1431     if ($d2 && $d2 ne '    ') {
1432         $d2 =~ tr/ux/99/;
1433         $res->date2( $d2 );
1434     }
1435
1436     return $res;
1437 }
1438 __PACKAGE__->register_method(  
1439     api_name    => "open-ils.ingest.descriptor.xml",
1440     method        => "biblio_descriptor",
1441     api_level    => 1,
1442     argc        => 1,
1443 );                      
1444
1445
1446 1;
1447
1448 # vim:et:ts=4:sw=4: