blib/lib/Genealogy/ChroniclingAmerica.pm

filter: Statementstmt 76.7% 162 / 211 Branchbran 48.9% 46 / 94 Conditioncond 39.6% 21 / 53 MC/DCmcdc 6.4% 2 / 31 Subroutinesub 100% 16 / 16 Podpod 100% 2 / 2 totaltotal 61.1% 249 / 407 CC 73 SCAR 39.3
CC
73
Cov
64%
new
90.1
_get_items
58.1
get_next_entry
29.7
CRAP 50.7
↑ Summary
1 package Genealogy::ChroniclingAmerica;
2  
3 # OLD API
4 # https://chroniclingamerica.loc.gov/search/pages/results/?date1=1912&state=Indiana&format=json&andtext=ralph%3Dbixler
5  
6 # TODO: NEW API
7 # https://libraryofcongress.github.io/data-exploration/loc.gov%20JSON%20API/Chronicling_America/README.html
8 # https://libraryofcongress.github.io/data-exploration/loc.gov%20JSON%20API/Chronicling_America/ChronAm-download_results.html
9 # https://www.loc.gov/collections/chronicling-america/?dl=page&end_date=1912-12-31&ops=PHRASE&qs=ralph+bixler&searchType=advanced&start_date=1912-01-01&fo=json
10  
11 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 3 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 3 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 3 ▶use Return::Set 0.02;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 3 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 =head1 NAME
26  
27 Genealogy::ChroniclingAmerica - Find URLs for a given person on the Library of Congress Newspaper Records
28  
29 =head1 VERSION
30  
31 Version 0.08
32  
33 =cut
34  
35 3 our $VERSION = '0.08';
36  
37 =head1 SYNOPSIS
38  
39 use HTTP::Cache::Transparent; # be nice
40 use Genealogy::ChroniclingAmerica;
41  
42 HTTP::Cache::Transparent::init({
43 BasePath => '/tmp/cache'
44 });
45 my $loc = Genealogy::ChroniclingAmerica->new({
46 firstname => 'John',
47 lastname => 'Smith',
48 state => 'Indiana',
49 date_of_death => 1862
50 });
51  
52 while(my $url = $loc->get_next_entry()) {
53 print "$url\n";
54 }
55  
56 =head1 DESCRIPTION
57  
58 The B<Genealogy::ChroniclingAmerica> module allows users to search for historical newspaper records from the B<Chronicling America> archive,
59 maintained by the Library of Congress.
60 By providing a person's first name,
61 last name,
62 and state,
63 the module constructs and executes search queries,
64 retrieving URLs to relevant newspaper pages in JSON format.
65 It supports additional filters like date of birth and date of death,
66 enforces B<rate-limiting> to comply with API request limits,
67 local caching,
68 and includes robust error handling and validation.
69 Ideal for genealogy research,
70 this module streamlines access to historical newspaper archives with an easy-to-use interface.
71  
72 =over 4
73  
74 =item * Rate-Limiting
75  
76 A minimum interval between successive API calls can be enforced to ensure that the API is not overwhelmed and to comply with any request throttling requirements.
77  
78 Rate-limiting is implemented using L<Time::HiRes>.
79 A minimum interval between API
80 calls can be specified via the C<min_interval> parameter in the constructor.
81 Before making an API call,
82 the module checks how much time has elapsed since the
83 last request and,
84 if necessary,
85 sleeps for the remaining time.
86  
87 =back
88  
89 =head1 SUBROUTINES/METHODS
90  
91 =head2 new
92  
93 Creates a Genealogy::ChroniclingAmerica object.
94  
95 It takes three mandatory arguments:
96  
97 =over 4
98  
99 =item * C<firstname>
100  
101 =item * C<lastname>
102  
103 =item * C<state> - Must be the full name,
104 not an abbreviation.
105  
106 =back
107  
108 Accepts the following optional arguments:
109  
110 =over 4
111  
112 =item * C<cache>
113  
114 A caching object.
115 If not provided,
116 an in-memory cache is created with a default expiration of one hour.
117  
118 =item * C<middlename>
119  
120 =item * C<date_of_birth>
121  
122 =item * C<date_of_death>
123  
124 =item * C<host> - The domain of the site to search, the default is C<www.loc.gov>.
125  
126 =item * C<ua> - An object that understands get and env_proxy messages,
127 such as L<LWP::UserAgent::Throttled>.
128  
129 =item * C<min_interval> - Amount to rate limit.
130 Defaults to 4 seconds,
131 inline with L<https://libraryofcongress.github.io/data-exploration/loc.gov%20JSON%20API/Chronicling_America/README.html#rate-limits>
132  
133 =back
134  
135 If a search finds nothing it is repeated once,
136 since the Library of Congress sometimes answers an identical search inconsistently.
137  
138 =head3 API SPECIFICATION
139  
140 =head4 INPUT
141  
142 {
143 firstname => { type => 'string', min => 1, matches => qr/\D/ },
144 lastname => { type => 'string', min => 1, matches => qr/\D/ },
145 state => { type => 'string', min => 3, matches => qr/^\D+$/ }, # Full name, not an abbreviation
146 middlename => { type => 'string', optional => 1 },
147 date_of_birth => { type => 'integer', optional => 1 }, # A year
148 date_of_death => { type => 'integer', optional => 1 }, # A year
149 host => { type => 'string', optional => 1 },
150 ua => { type => 'object', can => 'get', optional => 1 },
151 cache => { type => 'object', can => ['get', 'set'], optional => 1 },
152 min_interval => { type => 'number', optional => 1 },
153 }
154  
155 The constructor croaks if a mandatory argument is missing or invalid.
156  
157 =head4 OUTPUT
158  
159 A blessed C<Genealogy::ChroniclingAmerica> object.
160 Called on an existing object it returns a clone with the new arguments.
161  
162 =cut
163  
164 4 ▶sub new {
Subroutine new: called CC=29 SCAR=45.0
Pod documented
165 4 my $class = shift;
166  
167 4 ▶ return unless(defined($class));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 0 4 4
168  
169 # Handle hash or hashref arguments
170 4 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition50%1/2
Params::Get::get_params(undef, \@_) || {}
l!l
40
MC/DC0%0/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table50%1/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
171  
172 4 ▶ if(Scalar::Util::blessed($class)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($class)) 0 4 4
173 # If $class is an object, clone it with new arguments
174 0 return bless { %{$class}, %{$params} }, ref($class);
175 }
176  
177 4 ▶ unless($params->{'firstname'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"firstname"}) 0 4 4
178 0 Carp::croak('Firstname is not optional');
179 }
180  
181 # Fail when the input is just a set of numbers
182 4 ▶ if($params->{'firstname'} !~ /\D/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"firstname"} =~ /\D/) 0 4 4
183 0 Carp::croak('Usage: ', __PACKAGE__, ": invalid input to new(), $params->{firstname}");
184 0 return;
185 }
186  
187 4 ▶ unless(defined($params->{'lastname'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $params->{"lastname"}) 0 4 4
188 0 Carp::croak('Lastname is not optional');
189 0 return;
190 }
191  
192 # Fail when the input is just a set of numbers
193 4 ▶ if($params->{'lastname'} !~ /\D/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"lastname"} =~ /\D/) 0 4 4
194 0 Carp::croak('Usage: ', __PACKAGE__, ": invalid input to new(), $params->{lastname}");
195 0 return;
196 }
197  
198 4 ▶ unless($params->{'state'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"state"}) 0 4 4
199 0 Carp::croak('State is not optional');
200 0 return;
201 }
202  
203 4 ▶ if(length($params->{'state'}) == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $params->{"state"} == 2) 0 4 4
204 0 Carp::croak('State needs to be the full name');
205 0 return;
206 }
207  
208 # Fail when the input contains a number
209 4 ▶ if($params->{'state'} =~ /\d/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"state"} =~ /\d/) 0 4 4
210 0 Carp::croak('Usage: ', __PACKAGE__, ": invalid input to new(), $params->{state}");
211 0 return;
212 }
213  
214 4 $params = Object::Configure::configure($class, $params);
215  
216 4 my $ua = $params->{'ua'};
217 4 ▶ if(!defined($ua)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ua) 0 4 4
218 0 my $ssl_opts;
219 0 ▶ if(-r '/etc/ssl/certs/ca-certificates.crt') { # Linux
Branch: 2 branches
BranchTrueFalseTotal
if (-r '/etc/ssl/certs/ca-certificates.crt') { } 0 0 0
elsif (-r '/opt/homebrew/etc/ca-certificates/cert.pem') { } 0 0 0
220 0 $ssl_opts = {
221 'SSL_ca_file' => '/etc/ssl/certs/ca-certificates.crt',
222 verify_hostname => 1
223 }
224 } elsif(-r '/opt/homebrew/etc/ca-certificates/cert.pem') { # MacOS
225 0 $ssl_opts = {
226 'SSL_ca_file' => '/opt/homebrew/etc/ca-certificates/cert.pem',
227 verify_hostname => 1
228 }
229 } else {
230 0 $ssl_opts = { verify_hostname => 0 };
231 }
232 0 $ua = LWP::UserAgent->new(
233 ssl_opts => $ssl_opts,
234 agent => __PACKAGE__ . "/$VERSION"
235 );
236 0 $ua->env_proxy(1);
237 }
238  
239 # Set up caching (default to an in-memory cache if none provided)
240 4 ▶ my $cache = $params->{cache} || CHI->new(
Condition33%1/3
$params->{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
l!l&&r!l&&!r
400
MC/DC0%0/2
$params->{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
$params->{'cache'} 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
Truth table33%1/3
A || B
A= $params->{'cache'}B= 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
ABresult
1X1
011
000
241 driver => 'Memory',
242 global => 1,
243 expires_in => '1 hour',
244 );
245  
246 # Set up rate-limiting: minimum interval between requests (in seconds)
247 # From https://libraryofcongress.github.io/data-exploration/loc.gov%20JSON%20API/Chronicling_America/README.html#rate-limits
248 # Burst Limit: 20 requests per 1 minute, Block for 5 minutes
249 4 ▶ my $min_interval = $params->{min_interval} || 4; # default: four second delay
Condition50%1/2
$params->{'min_interval'} || 4
l!l
40
MC/DC0%0/1
$params->{'min_interval'} || 4
$params->{'min_interval'}
Truth table50%1/2
A
A= $params->{'min_interval'}
Aresult
11
00
250  
251 my $rc = {
252 4 ▶ %{$params},
Condition50%1/2
$params->{'host'} || 'www.loc.gov'
l!l
04
MC/DC0%0/1
$params->{'host'} || 'www.loc.gov'
$params->{'host'}
Truth table50%1/2
A
A= $params->{'host'}
Aresult
11
00
253 min_interval => $min_interval,
254 ua => $ua,
255 4 host => $params->{'host'} || 'www.loc.gov',
256 path => 'collections/chronicling-america',
257 cache => $cache,
258 };
259  
260 4 my %query_parameters = ( 'fo' => 'json', 'location_state' => ucfirst(lc($params->{'state'})), 'ops' => 'PHRASE', 'searchType' => 'advanced' );
261 4 ▶ if($query_parameters{'location_state'} eq 'District of columbia') {
Branch: 1 branch
BranchTrueFalseTotal
if ($query_parameters{"location_state"} eq "District of columbia") 0 4 4
262 0 $query_parameters{'location_state'} = 'District of Columbia';
263 }
264 4 my $name = $params->{'firstname'};
265 4 ▶ if($params->{'middlename'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'middlename'}) { } 0 4 4
266 0 $rc->{'name'} = "$name $params->{middlename} $params->{lastname}";
267 0 $name .= '+' . $params->{middlename};
268 } else {
269 4 $rc->{'name'} = "$name $params->{lastname}";
270 }
271 4 $name .= "+$params->{lastname}";
272  
273 4 $name =~ s/\s/+/g;
274  
275 4 $query_parameters{'qs'} = $name;
276 4 ▶ if($params->{'date_of_birth'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"date_of_birth"}) 0 4 4
277 0 $query_parameters{'start_date'} = $params->{'date_of_birth'};
278 }
279 4 ▶ if($params->{'date_of_death'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"date_of_death"}) 0 4 4
280 0 $query_parameters{'end_date'} = $params->{'date_of_death'};
281 }
282  
283 # Just scanning for one year
284 4 ▶ $query_parameters{'start_date'} ||= $params->{'date_of_death'};
Condition33%1/3
$query_parameters{"start_date"} ||= $params->{"date_of_death"}
l!l&&r!l&&!r
004
MC/DC0%0/2
$query_parameters{"start_date"} ||= $params->{"date_of_death"}
$query_parameters{"start_date"} $params->{"date_of_death"}
Truth table33%1/3
A ||= B
A= $query_parameters{"start_date"}B= $params->{"date_of_death"}
ABresult
1X1
011
000
285 4 ▶ $query_parameters{'end_date'} ||= $params->{'date_of_birth'};
Condition33%1/3
$query_parameters{"end_date"} ||= $params->{"date_of_birth"}
l!l&&r!l&&!r
004
MC/DC0%0/2
$query_parameters{"end_date"} ||= $params->{"date_of_birth"}
$query_parameters{"end_date"} $params->{"date_of_birth"}
Truth table33%1/3
A ||= B
A= $query_parameters{"end_date"}B= $params->{"date_of_birth"}
ABresult
1X1
011
000
286  
287 4 ▶ $query_parameters{'start_date'} .= '-01-01' if($query_parameters{'start_date'});
Branch: 1 branch
BranchTrueFalseTotal
if $query_parameters{"start_date"} 0 4 4
288 4 ▶ $query_parameters{'end_date'} .= '-12-31' if($query_parameters{'end_date'});
Branch: 1 branch
BranchTrueFalseTotal
if $query_parameters{"end_date"} 0 4 4
289  
290 4 my $uri = URI->new("https://$rc->{host}/$rc->{path}");
291 4 $uri->query_form(%query_parameters);
292 4 my $url = $uri->as_string();
293 # ::diag(">>>>$url = ", $rc->{'name'});
294 # print ">>>>$url = ", $rc->{'name'}, "\n";
295  
296 4 my $items = _get_items($ua, $url);
297  
298 # loc.gov sometimes answers an identical search with no results, so try once more
299 4 ▶ unless(scalar(@{$items})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @{$items;}) 2 2 4
300 2 Time::HiRes::sleep($min_interval);
301 2 $items = _get_items($ua, $url);
302 }
303  
304 # Update last_request timestamp
305 4 $rc->{'last_request'} = time();
306  
307 4 ▶ if(scalar(@{$items})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$items;}) { } 3 1 4
308 # Add 'fo=json' to the end of each row
309 3 my @rc;
310 3 for my $item (@{$items}) {
311 3 ▶ unless($item->{'id'} =~ /&fo=json$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($item->{"id"} =~ /&fo=json$/) 3 0 3
312 3 $item->{'id'} .= '&fo=json';
313 }
314 3 push @rc, $item;
315 }
316 3 $rc->{'items'} = \@rc;
317 3 $rc->{'index'} = 0;
318 3 $rc->{'matches'} = scalar(@rc);
319 } else {
320 1 $rc->{'matches'} = 0;
321 }
322  
323 4 return bless $rc, $class;
324 }
325  
326 =head2 get_next_entry
327  
328 Returns the next match as a URL of a PDF of the newspaper page,
329 or undef when there are no more matches.
330  
331 Each call may make up to two requests of the Library of Congress:
332 one for the item and one for the OCR text of its page.
333 Items whose text doesn't contain the person's name are skipped.
334 Both requests honour C<min_interval>.
335  
336 The URL is not checked,
337 the Library of Congress may refuse (HTTP 403) requests for the PDF from some automated clients.
338  
339 =head3 API SPECIFICATION
340  
341 =head4 INPUT
342  
343 None, other than the object.
344  
345 =head4 OUTPUT
346  
347 {
348 type => 'string',
349 min => 5,
350 matches => qr/\.pdf$/, # A URL
351 optional => 1, # undef when no more matches
352 }
353  
354 =cut
355  
356 sub get_next_entry
357 5 ▶{
Subroutine get_next_entry: called CC=16 SCAR=33.9
Pod documented
358 5 my $self = shift;
359  
360 # Exit if no matches or index out of bounds
361 5 ▶ return if($self->{'matches'} == 0) || ($self->{'index'} >= $self->{'matches'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"matches"} == 0 or $self->{"index"} >= $self->{"matches"} 3 2 5
Condition100%3/3
$self->{"matches"} == 0 or $self->{"index"} >= $self->{"matches"}
l!l&&r!l&&!r
122
MC/DC100%2/2
$self->{"matches"} == 0 or $self->{"index"} >= $self->{"matches"}
$self->{"matches"} == 0 $self->{"index"} >= $self->{"matches"}
Truth table100%3/3
A or B
A= $self->{"matches"} == 0B= $self->{"index"} >= $self->{"matches"}
ABresult
1X1
011
000
362  
363 # Retrieve the next entry and increment index
364 2 my $entry = $self->{'items'}->[$self->{'index'}++];
365  
366 # Create a cache key based on the location, date and time zone (might want to use a stronger hash function if needed)
367 2 my $cache_key = "loc:$entry->{id}";
368 2 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 0 2 2
369 0 return $cached;
370 }
371  
372 # Enforce rate-limiting: ensure at least min_interval seconds between requests.
373 2 my $now = time();
374 2 my $elapsed = $now - $self->{last_request};
375 2 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 2 0 2
376 2 Time::HiRes::sleep($self->{min_interval} - $elapsed);
377 }
378  
379 # Make the API request
380 2 my $resp = $self->{'ua'}->get($entry->{'id'});
381  
382 # Update last_request timestamp
383 2 $self->{last_request} = time();
384  
385 # Handle error responses
386 2 ▶ if($resp->is_error()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_error) 0 2 2
387 0 ▶ Carp::carp("get_next_entry: API returned error on $entry->{id}: ", $resp->status_line()) unless($resp->code() == 404);
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->code == 404 0 0 0
388 0 return;
389 }
390  
391 2 ▶ unless($resp->is_success()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($resp->is_success) 0 2 2
392 0 Carp::croak($resp->status_line());
393 }
394  
395 2 my $data;
396 2 eval {
397 2 $data = decode_json($resp->decoded_content())
398 };
399 2 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
400 0 Carp::carp("$@: ", $resp->decoded_content());
401 0 return;
402 }
403  
404 2 my $full_text = $data->{'full_text'};
405 2 ▶ if(!defined($full_text)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $full_text) 2 0 2
406 # loc.gov now serves the text from a separate service
407 2 $full_text = $self->_fetch_full_text($data);
408 }
409 2 ▶ if(!defined($full_text)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $full_text) 0 2 2
410 0 return $self->get_next_entry();
411 }
412  
413 2 $full_text =~ s/[\r\n]/ /g;
414 2 ▶ if($full_text !~ /\Q$self->{'name'}\E/ims) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($full_text =~ /\Q$self->{"name"}\E/ism) 1 1 2
415 1 return $self->get_next_entry();
416 }
417  
418 # The PDF is now given in the 'resource' section
419 1 ▶ if(ref($data->{'resource'}) eq 'HASH' && (my $pdf = $data->{'resource'}->{'pdf'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->{"resource"} eq "HASH" and my $pdf = $data->{"resource"}{"pdf"}) 1 0 1
Condition33%1/3
ref $data->{"resource"} eq "HASH" and my $pdf = $data->{"resource"}{"pdf"}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $data->{"resource"} eq "HASH" and my $pdf = $data->{"resource"}{"pdf"}
ref $data->{"resource"} eq "HASH" my $pdf = $data->{"resource"}{"pdf"}
Truth table33%1/3
A and B
A= ref $data->{"resource"} eq "HASH"B= my $pdf = $data->{"resource"}{"pdf"}
ABresult
0X0
100
111
420 1 $self->{'cache'}->set($cache_key, $pdf);
421 1 return Return::Set::set_return($pdf, { type => 'string', 'min' => 5, matches => qr/\.pdf$/ });
422 }
423  
424 0 foreach my $page(@{$data->{'page'}}) {
425 0 ▶ if($page->{'mimetype'} eq 'application/pdf') {
Branch: 1 branch
BranchTrueFalseTotal
if ($page->{"mimetype"} eq "application/pdf") 0 0 0
426 # Cache the result before returning it
427 0 $self->{'cache'}->set($cache_key, $page->{'url'});
428 0 return Return::Set::set_return($page->{'url'}, { type => 'string', 'min' => 5, matches => qr/\.pdf$/ });
429 }
430 }
431 }
432  
433 # Fetch the OCR text of a page from the 'fulltext_file' service, returns undef on any failure
434 sub _fetch_full_text
435 2 ▶{
Subroutine _fetch_full_text: called CC=10 SCAR=26.2
436 2 my ($self, $data) = @_;
437  
438 2 ▶ my $url = (ref($data->{'resource'}) eq 'HASH' && $data->{'resource'}->{'fulltext_file'}) || $data->{'fulltext_service'};
Condition33%2/6
ref $data->{'resource'} eq 'HASH' && $data->{'resource'}{'fulltext_file'} || $data->{'fulltext_service'}
l!l&&r!l&&!r
200
ref $data->{"resource"} eq "HASH" and $data->{"resource"}{"fulltext_file"}
!ll&&!rl&&r
002
MC/DC0%0/3
ref $data->{'resource'} eq 'HASH' && $data->{'resource'}{'fulltext_file'} || $data->{'fulltext_service'}
ref $data->{"resource"} eq "HASH" $data->{"resource"}{"fulltext_file"} $data->{'fulltext_service'}
Truth table20%1/5
A and B || C
A= ref $data->{"resource"} eq "HASH"B= $data->{"resource"}{"fulltext_file"}C= $data->{'fulltext_service'}
ABCresult
11X1
0X11
1011
0X00
1000
439 2 ▶ return unless($url);
Branch: 1 branch
BranchTrueFalseTotal
unless $url 0 2 2
440  
441 2 my $now = time();
442 2 my $elapsed = $now - $self->{'last_request'};
443 2 ▶ if($elapsed < $self->{'min_interval'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 2 0 2
444 2 Time::HiRes::sleep($self->{'min_interval'} - $elapsed);
445 }
446 2 my $resp = $self->{'ua'}->get($url);
447 2 $self->{'last_request'} = time();
448  
449 2 ▶ return unless($resp->is_success());
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->is_success 0 2 2
450  
451 2 my $json;
452 2 eval { $json = decode_json($resp->decoded_content()) };
453 2 ▶ return if($@ || ref($json) ne 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
if $@ or ref $json ne "HASH" 0 2 2
Condition33%1/3
$@ or ref $json ne "HASH"
l!l&&r!l&&!r
002
MC/DC0%0/2
$@ or ref $json ne "HASH"
$@ ref $json ne "HASH"
Truth table33%1/3
A or B
A= $@B= ref $json ne "HASH"
ABresult
1X1
011
000
454  
455 # Keyed by segment name
456 2 ▶ return join(' ', map { ref($_) eq 'HASH' ? ($_->{'full_text'} // ()) : () } values %{$json});
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 2 0 2
Condition33%1/3
$_->{"full_text"} // ()
l!l&&r!l&&!r
200
MC/DC0%0/2
$_->{"full_text"} // ()
$_->{"full_text"} ()
Truth table33%1/3
A // B
A= $_->{"full_text"}B= ()
ABresult
1X1
011
000
457 }
458  
459 # This is the sample code at https://libraryofcongress.github.io/data-exploration/loc.gov%20JSON%20API/Chronicling_America/ChronAm-download_results.html
460 # translated into Perl
461  
462 # Run P1 search and get a list of results
463  
464 sub _get_items
465 6 ▶{
Subroutine _get_items: called CC=21 SCAR=40.6
466 6 my ($ua, $url, $items_ref, $conditional, $depth) = @_;
467  
468 6 ▶ $items_ref ||= [];
Condition50%1/2
$items_ref ||= []
l!l
06
MC/DC0%0/1
$items_ref ||= []
$items_ref
Truth table50%1/2
A
A= $items_ref
Aresult
11
00
469 6 ▶ $conditional ||= 'True';
Condition50%1/2
$conditional ||= "True"
l!l
06
MC/DC0%0/1
$conditional ||= "True"
$conditional
Truth table50%1/2
A
A= $conditional
Aresult
11
00
470 6 ▶ $depth ||= 0;
Condition50%1/2
$depth ||= 0
l!l
06
MC/DC0%0/1
$depth ||= 0
$depth
Truth table50%1/2
A
A= $depth
Aresult
11
00
471  
472 # Check that the query URL is not an item or resource link
473 6 my @exclude = ('loc.gov/item', 'loc.gov/resource');
474 6 for my $string (@exclude) {
475 12 ▶ if (index($url, $string) != -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($url, $string) != -1) 0 12 12
476 0 Carp::croak('Your URL points directly to an item or ',
477 'resource page (you can tell because "item" ',
478 'or "resource" is in the URL). Please use ',
479 'a search URL instead. For example, instead ',
480 'of "https://www.loc.gov/item/2009581123/", ',
481 'try "https://www.loc.gov/maps/?q=2009581123".');
482 }
483 }
484  
485 # Create URI object and add parameters
486 6 my $uri = URI->new($url);
487 6 $uri->query_form(
488 $uri->query_form(),
489 fo => 'json',
490 c => 100,
491 at => 'results,pagination'
492 );
493  
494 # Make HTTP request
495 # ::diag(__LINE__);
496 # ::diag($uri);
497 6 my $response = $ua->get($uri);
498  
499 # Check that the API request was successful
500 6 ▶ if($response->is_success() && $response->header('Content-Type') && ($response->header('Content-Type') =~ /json/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_success and $response->header("Content-Type") and $response->header("Content-Type") =~ /json/) 6 0 6
Condition33%2/6
$response->is_success and $response->header("Content-Type") and $response->header("Content-Type") =~ /json/
!ll&&!rl&&r
006
$response->is_success and $response->header("Content-Type")
!ll&&!rl&&r
006
MC/DC0%0/3
$response->is_success and $response->header("Content-Type") and $response->header("Content-Type") =~ /json/
$response->is_success $response->header("Content-Type") $response->header("Content-Type") =~ /json/
Truth table25%1/4
A and B and C
A= $response->is_successB= $response->header("Content-Type")C= $response->header("Content-Type") =~ /json/
ABCresult
0XX0
10X0
1100
1111
501 6 my $data = decode_json($response->decoded_content());
502 6 my $results = $data->{results};
503  
504 6 for my $result(@{$results}) {
505 # Filter out anything that's a collection or web page
506 3 ▶ my $original_format = $result->{original_format} || [];
Condition50%1/2
$result->{'original_format'} || []
l!l
03
MC/DC0%0/1
$result->{'original_format'} || []
$result->{'original_format'}
Truth table50%1/2
A
A= $result->{'original_format'}
Aresult
11
00
507 3 my $filter_out = 0;
508  
509 # Check if original_format contains "collection" or "web page"
510 3 for my $format (@$original_format) {
511 0 ▶ if ($format =~ /collection/i || $format =~ /web page/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format =~ /collection/i or $format =~ /web page/i) 0 0 0
Condition0%0/3
$format =~ /collection/i or $format =~ /web page/i
l!l&&r!l&&!r
000
MC/DC0%0/2
$format =~ /collection/i or $format =~ /web page/i
$format =~ /collection/i $format =~ /web page/i
Truth table0%0/3
A or B
A= $format =~ /collection/iB= $format =~ /web page/i
ABresult
1X1
011
000
512 0 $filter_out = 1;
513 0 last;
514 }
515 }
516  
517 # Evaluate conditional (simplified - assumes 'True' means true)
518 3 ▶ if ($conditional ne 'True') {
Branch: 1 branch
BranchTrueFalseTotal
if ($conditional ne "True") 0 3 3
519 0 $filter_out = 1;
520 }
521  
522 3 ▶ unless ($filter_out) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($filter_out) 3 0 3
523 # Get the link to the item record
524 3 ▶ if (my $item = $result->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = $result->{"id"}) 3 0 3
525 # Filter out links to Catalog or other platforms
526 3 ▶ if ($item =~ /^http:\/\/www\.loc\.gov\/resource/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item =~ m[^http://www\.loc\.gov/resource]) 3 0 3
527 # my $resource = $item; # Assign item to resource
528 # push @$items_ref, $resource;
529 3 push @$items_ref, $result;
530 }
531 3 ▶ if ($item =~ /^http:\/\/www\.loc\.gov\/item/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item =~ m[^http://www\.loc\.gov/item]) 0 3 3
532 0 push @$items_ref, $result;
533 }
534 }
535 }
536 }
537  
538 # Repeat the loop on the next page, unless we're on the last page
539 # Put the $depth in case the end of list code doesn't work
540 6 ▶ if(($depth <= 10) && defined(my $next_url = $data->{pagination}->{next})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth <= 10 and defined(my $next_url = $data->{"pagination"}{"next"})) 0 6 6
Condition33%1/3
$depth <= 10 and defined(my $next_url = $data->{"pagination"}{"next"})
!ll&&!rl&&r
060
MC/DC0%0/2
$depth <= 10 and defined(my $next_url = $data->{"pagination"}{"next"})
$depth <= 10 defined(my $next_url = $data->{"pagination"}{"next"})
Truth table33%1/3
A and B
A= $depth <= 10B= defined(my $next_url = $data->{"pagination"}{"next"})
ABresult
0X0
100
111
541 0 _get_items($ua, $next_url, $items_ref, $conditional, $depth + 1);
542 }
543  
544 6 return $items_ref;
545 }
546 0 Carp::carp($url, ': ', $response->status_line());
547 0 return $items_ref;
548 }
549  
550 =head1 AUTHOR
551  
552 Nigel Horne, C<< <njh at nigelhorne.com> >>
553  
554 =head1 BUGS
555  
556 If a middle name is given and no match is found,
557 it should search again without the middle name.
558  
559 =head1 SEE ALSO
560  
561 =over 4
562  
563 =item * L<https://github.com/nigelhorne/gedcom>
564  
565 =item * L<https://chroniclingamerica.loc.gov>
566  
567 =item * L<https://github.com/LibraryOfCongress/data-exploration>
568  
569 =back
570  
571 =head1 SUPPORT
572  
573 This module is provided as-is without any warranty.
574  
575 Please report any bugs or feature requests to C<bug-genealogy-chroniclingamerica at rt.cpan.org>,
576 or through the web interface at
577 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Genealogy-ChroniclingAmerica>.
578 I will be notified, and then you'll
579 automatically be notified of progress on your bug as I make changes.
580  
581 You can find documentation for this module with the perldoc command.
582  
583 perldoc Genealogy::ChroniclingAmerica
584  
585 You can also look for information at:
586  
587 =over 4
588  
589 =item * RT: CPAN's request tracker
590  
591 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Genealogy-ChroniclingAmerica>
592  
593 =item * Search CPAN
594  
595 L<https://metacpan.org/release/Genealogy-ChroniclingAmerica>
596  
597 =back
598  
599 =head1 LICENSE AND COPYRIGHT
600  
601 Copyright 2018-2026 Nigel Horne.
602  
603 This program is released under the following licence: GPL2
604  
605 =cut
606  
607 3 1; # End of Genealogy::ChroniclingAmerica
↑ Summary