Tools/BISG.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Tools/Mobipocket.pm ↑ Summary Tools/MSReader.pm »
1 package EBook::Tools::BISG;
2 2 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use version 0.74; our $VERSION = qv("0.5.4");
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 =head1 NAME
7  
8 EBook::Tools::BISG - Class for downloading information from the Book Industry Study Group webpages
9  
10 =head1 SYNOPSIS
11  
12 use EBook::Tools::BISG;
13 my $bisg = EBook::Tools::BISG->new();
14 $bisg->download_bisac;
15 $bisg->save_bisac;
16 say $bisg->bisac('fic000000');
17 %bisac_codes = $bisg->bisac();
18  
19 =head1 DEPENDENCIES
20  
21 =over
22  
23 =item * C<DBI>
24  
25 This will also require a DBD of your choice. The default is to use a
26 local SQLite store.
27  
28 =item * C<LWP>
29  
30 =item * C<Mojo::DOM>
31  
32 =back
33  
34 =cut
35  
36 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 2 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 0 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
39 use LWP;
40 use Mojo::DOM;
41  
42  
43 #################################
44 ########## CONSTRUCTOR ##########
45 #################################
46  
47 =head1 CONSTRUCTOR
48  
49 =head2 C<new(%args)>
50  
51 Instantiates a new Ebook::Tools::BISG object.
52  
53 =head3 Arguments
54  
55 =over
56  
57 =item * C<baseurl>
58  
59 The base url of the bisg.org website or mirror to use.
60  
61 =item * C<dsn>
62  
63 The Perl::DBI Data Source Name. Defaults to a sqlite store named
64 bisac.sqlite in the user config directory.
65  
66 =back
67  
68 =cut
69  
70 my @fields = (
71 'baseurl',
72 'bisac_codes',
73 'dbuser',
74 'dbpass',
75 'dsn',
76 );
77  
78 require fields;
79 fields->import(@fields);
80  
81 sub new {
82 my ($self,%args) = @_;
83 my $class = ref($self) || $self;
84 my $subname = (caller(0))[3];
85 debug(2,"DEBUG[",$subname,"]");
86  
87 my %valid_args = (
88 'baseurl' => 1,
89 'dbuser' => 1,
90 'dbpass' => 1,
91 'dsn' => 1,
92 );
93 foreach my $arg (keys %args) {
94 croak($subname,"(): invalid argument '",$arg,"'")
95 if(!$valid_args{$arg});
96 }
97  
98 $self = fields::new($class);
99 $self->{baseurl} = $args{file} || 'http://www.bisg.org';
100 $self->{bisac_codes} = {};
101 $self->{dbuser} = $args{dbuser} || '';
102 $self->{dbpass} = $args{dbpass} || '';
103  
104 if($args{dsn}) {
105 $self->{dsn} = $args{dsn};
106 $self->load_bisac();
107 }
108 else {
109 my $configdir = userconfigdir();
110 if($configdir) {
111 $self->{dsn} = 'dbi:SQLite:dbname=' . $configdir . '/bisac.sqlite';
112 $self->load_bisac();
113 }
114 }
115  
116 return $self;
117 }
118  
119  
120 =head1 ACCESSOR METHODS
121  
122 =head2 C<bisac($code)>
123  
124 Returns either the name matching a particular code (case-insensitive),
125 or the hash of all BISAC codes and references with the keys in
126 lower-case if no argument is provided.
127  
128 =cut
129  
130 sub bisac :method
131 {
132 my ($self,$code) = @_;
133 my $subname = ( caller(0) )[3];
134  
135 if ($code) {
136 return $self->{bisac_codes}->{$code};
137 }
138 return %{$self->{bisac_codes}};
139 }
140  
141  
142 =head2 C<find($regexp)>
143  
144 Returns a list of all BISAC values (names) where either the key or the
145 value for that entry matches a case-insensitive regular expression.
146 If no argument is specified, or it is just '.', then the entire list
147 is returned.
148  
149 =cut
150  
151 sub find :method
152 {
153 my ($self,$regexp) = @_;
154 my $subname = ( caller(0) )[3];
155  
156 my %seen;
157 my @keys;
158  
159 # Create a list of all unique keys and values (lowercased to be
160 # used again as keys)
161 foreach my $key (keys %{$self->{bisac_codes}}) {
162 $seen{$key} = 1;
163 }
164 foreach my $value (values %{$self->{bisac_codes}}) {
165 $seen{lc $value} = 1;
166 }
167  
168 if(not $regexp or $regexp eq '.') {
169 @keys = sort keys %seen;
170 }
171 else {
172 @keys = sort grep { /$regexp/i } keys %seen;
173 }
174  
175 return @{$self->{bisac_codes}}{@keys};
176 }
177  
178  
179 =head1 MODIFIER METHODS
180  
181 =head2 C<download_bisac()>
182  
183 Downloads the BISAC codes from the BISG website and converts them into
184 a hash. Codes and obsolete entries are lowercased and made the keys,
185 the values will be the official names they map to.
186  
187 =cut
188  
189 sub download_bisac :method
190 {
191 my $self = shift;
192 my $subname = ( caller(0) )[3];
193  
194 # LWP/Cookies variables
195 my $browser = LWP::UserAgent->new;
196 my $content;
197 my $content_type;
198 my $response;
199 my $url;
200  
201 # HTML parsing
202 my $dom = Mojo::DOM->new();
203 my @elements;
204 my $category;
205 my $key;
206 my $value;
207 my $bisac_headings_top_url =
208 $self->{baseurl} . '/complete-bisac-subject-headings-2013-edition';
209  
210 debug(2,"DEBUG[",$subname,"]");
211  
212  
213 $response = $browser->get($bisac_headings_top_url);
214 croak "Error loading ${bisac_headings_top_url}: ", $response->status_line()
215 unless $response->is_success();
216 $content_type = $response->content_type();
217 $content = $response->content();
218  
219 $dom->parse($content);
220  
221 foreach my $link ($dom->find('a[href*="bisac-subject-headings-list-"]')->each) {
222 my $href = $link->attr('href');
223 my $url = $self->{baseurl} . $href;
224 $response = $browser->get($url);
225 croak "Error loading ${url}: ", $response->status_line()
226 unless $response->is_success();
227 $content_type = $response->content_type();
228 $content = $response->content();
229  
230 $dom->parse($content);
231  
232 $category = uc $dom->at('h3')->text;
233 say "parsing ${category}...";
234  
235 foreach my $tr ($dom->find('tr')->each) {
236 my $td = $tr->children('td');
237 if ($td->[1] and $td->[1] =~ /\w/) {
238 $key = $td->[0]->all_text;
239 if ($key =~ /\w/) {
240 $value = $td->[1]->all_text;
241 }
242 else {
243 # The first column is empty, but the second column
244 # is not. This indicates a non-code reference
245 # entry.
246 #
247 # If the second column does not contain ' see ',
248 # then we don't know how to parse the reference,
249 # and we skip. If it contains ' see ' and ' or '
250 # then the reference is ambiguous and we also
251 # skip.
252 #
253 # If it contains 'headings under' then the result
254 # is ambiguous and we must skip.
255 #
256 # Otherwise the portion before ' see ' becomes the
257 # key and the portion afterwards becomes the
258 # value.
259  
260 if ($td->[1]->all_text =~
261 /^ # Start of string
262 (?! .* headings \s under) # Not matching look-ahead 'headings under'
263 (.*?) \s see \s # Match all characters up to ' see '
264 ( (?:(?! \s or \s ) # Complex match not matching ' or '
265 .)*) # ... but matching anything else
266 /x) {
267  
268 $key = $1;
269 $value = $2;
270  
271 # The value won't have the category prefix if
272 # it's in the current category, so we need to
273 # check and prepend if necessary.
274 if ($value !~ /^[A-Z]{3}/x) {
275 $value = $category . ' / ' . $value;
276 }
277 }
278 else {
279 $key = '';
280 $value = '';
281 }
282 }
283 # Remove trailing parentheticals and asterisks
284 $value =~ s/(.*?) \(.*\)/$1/;
285 $value =~ s/(.*?) \*/$1/;
286  
287 if($key and $value) {
288 $key = lc $key;
289 $self->{bisac_codes}->{$key} = $value;
290  
291 # Also put in a self-mapping of the lowercased
292 # value to itself if one does not already exist.
293 if (! $self->{bisac_codes}->{lc $value}) {
294 $self->{bisac_codes}->{lc $value} = $value;
295 }
296 }
297 }
298 else {
299 # There is one row with a single <td> element at the
300 # very end. We ignore this.
301 }
302 }
303 }
304 return;
305 }
306  
307  
308 =head2 C<load_bisac()>
309  
310 Load the BISAC codes from the specified database into the hash. This
311 is called automatically by new().
312  
313 If the load fails, nothing will happen (silently!), so the only way to
314 tell is to check to see if you have a populated hash afterwards.
315  
316 =cut
317  
318 sub load_bisac :method
319 {
320 my $self = shift;
321 my $subname = ( caller(0) )[3];
322  
323 my $dsn = $self->{dsn};
324 my $sql;
325  
326 my $dbh = DBI->connect(
327 $self->{dsn},$self->{dbuser},$self->{dbpass}, {
328 AutoCommit => 0,
329 PrintError => 0,
330 RaiseError => 0,
331 sqlite_see_if_its_a_number => 1,
332 });
333 return unless $dbh;
334  
335 my $sth;
336 my $row;
337  
338 $sth = $dbh->prepare('SELECT code,name FROM bisac_codes');
339 if (! $sth) {
340 # Table doesn't exist
341 $dbh->disconnect;
342 return;
343 }
344 $sth->execute() or croak ("Failed to load BISAC codes from database");
345 while($row = $sth->fetchrow_arrayref) {
346 $self->{bisac_codes}->{$row->[0]} = $row->[1];
347 }
348  
349 $dbh->disconnect();
350  
351 return;
352 }
353  
354  
355 =head2 C<save_bisac()>
356  
357 Save the BISAC codes in the hash to the database. This will destroy
358 any existing table named bisac_codes.
359  
360 Croaks on failure.
361  
362 =cut
363  
364 sub save_bisac :method
365 {
366 my $self = shift;
367 my $subname = ( caller(0) )[3];
368  
369 my $dbh = DBI->connect(
370 $self->{dsn},$self->{dbuser},$self->{dbpass}, {
371 AutoCommit => 0,
372 PrintError => 0,
373 RaiseError => 1,
374 sqlite_see_if_its_a_number => 1,
375 })
376 or croak("Failed to connect to $self->{dsn}");
377  
378 my $sth;
379 my $sql;
380 my @fields;
381 my $fieldlist;
382 my $placeholders;
383  
384 # Ensure the bisac_codes table exists as a blank slate.
385 $dbh->{RaiseError} = 0;
386 $sth = $dbh->prepare('SELECT * FROM bisac_codes WHERE 0 = 1');
387 $dbh->{RaiseError} = 1;
388 if ($sth) {
389 $dbh->do('DROP TABLE bisac_codes');
390 }
391  
392 $sql = '
393 CREATE TABLE bisac_codes (
394 code text PRIMARY KEY,
395 name text,
396 comment text
397 );';
398 $sth = $dbh->do($sql)
399 or croak ("Failed to create bisac_codes table!");
400 $dbh->commit();
401  
402 @fields = ('code','name');
403 $fieldlist = join (', ',@fields);
404 $placeholders = join (', ', map {'?'} @fields);
405 $sth = $dbh->prepare("INSERT INTO bisac_codes (${fieldlist}) VALUES (${placeholders})");
406 foreach my $key (keys %{$self->{bisac_codes}}) {
407 $sth->execute($key,$self->{bisac_codes}->{$key});
408 }
409 $dbh->commit;
410 $dbh->disconnect;
411  
412 return;
413 }
414  
415 1;
416 __END__
« Tools/Mobipocket.pm ↑ Summary Tools/MSReader.pm »