blib/lib/EBook/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
« blib/lib/EBook/Tools/Mobipocket.pm ↑ Summary blib/lib/EBook/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.0");
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 2 ▶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 $self->{dsn} = $args{dsn} || 'dbi:SQLite:dbname=' . userconfigdir() . '/bisac.sqlite';
104  
105 $self->load_bisac();
106  
107 return $self;
108 }
109  
110  
111 =head1 ACCESSOR METHODS
112  
113 =head2 C<bisac($code)>
114  
115 Returns either the name matching a particular code (case-insensitive),
116 or the hash of all BISAC codes and references with the keys in
117 lower-case if no argument is provided.
118  
119 =cut
120  
121 sub bisac :method
122 {
123 my ($self,$code) = @_;
124 my $subname = ( caller(0) )[3];
125  
126 if ($code) {
127 return $self->{bisac_codes}->{$code};
128 }
129 return %{$self->{bisac_codes}};
130 }
131  
132  
133 =head2 C<find($regexp)>
134  
135 Returns a list of all BISAC values (names) where either the key or the
136 value for that entry matches a case-insensitive regular expression.
137 If no argument is specified, or it is just '.', then the entire list
138 is returned.
139  
140 =cut
141  
142 sub find :method
143 {
144 my ($self,$regexp) = @_;
145 my $subname = ( caller(0) )[3];
146  
147 my %seen;
148 my @keys;
149  
150 # Create a list of all unique keys and values (lowercased to be
151 # used again as keys)
152 foreach my $key (keys %{$self->{bisac_codes}}) {
153 $seen{$key} = 1;
154 }
155 foreach my $value (values %{$self->{bisac_codes}}) {
156 $seen{lc $value} = 1;
157 }
158  
159 if(not $regexp or $regexp eq '.') {
160 @keys = sort keys %seen;
161 }
162 else {
163 @keys = sort grep { /$regexp/i } keys %seen;
164 }
165  
166 return @{$self->{bisac_codes}}{@keys};
167 }
168  
169  
170 =head1 MODIFIER METHODS
171  
172 =head2 C<download_bisac()>
173  
174 Downloads the BISAC codes from the BISG website and converts them into
175 a hash. Codes and obsolete entries are lowercased and made the keys,
176 the values will be the official names they map to.
177  
178 =cut
179  
180 sub download_bisac :method
181 {
182 my $self = shift;
183 my $subname = ( caller(0) )[3];
184  
185 # LWP/Cookies variables
186 my $browser = LWP::UserAgent->new;
187 my $content;
188 my $content_type;
189 my $response;
190 my $url;
191  
192 # HTML parsing
193 my $dom = Mojo::DOM->new();
194 my @elements;
195 my $category;
196 my $key;
197 my $value;
198 my $bisac_headings_top_url =
199 $self->{baseurl} . '/complete-bisac-subject-headings-2013-edition';
200  
201 debug(2,"DEBUG[",$subname,"]");
202  
203  
204 $response = $browser->get($bisac_headings_top_url);
205 croak "Error loading ${bisac_headings_top_url}: ", $response->status_line()
206 unless $response->is_success();
207 $content_type = $response->content_type();
208 $content = $response->content();
209  
210 $dom->parse($content);
211  
212 foreach my $link ($dom->find('a[href*="bisac-subject-headings-list-"]')->each) {
213 my $href = $link->attr('href');
214 my $url = $self->{baseurl} . $href;
215 $response = $browser->get($url);
216 croak "Error loading ${url}: ", $response->status_line()
217 unless $response->is_success();
218 $content_type = $response->content_type();
219 $content = $response->content();
220  
221 $dom->parse($content);
222  
223 $category = uc $dom->at('h3')->text;
224 say "parsing ${category}...";
225  
226 foreach my $tr ($dom->find('tr')->each) {
227 my $td = $tr->children('td');
228 if ($td->[1] and $td->[1] =~ /\w/) {
229 $key = $td->[0]->all_text;
230 if ($key =~ /\w/) {
231 $value = $td->[1]->all_text;
232 }
233 else {
234 # The first column is empty, but the second column
235 # is not. This indicates a non-code reference
236 # entry.
237 #
238 # If the second column does not contain ' see ',
239 # then we don't know how to parse the reference,
240 # and we skip. If it contains ' see ' and ' or '
241 # then the reference is ambiguous and we also
242 # skip.
243 #
244 # If it contains 'headings under' then the result
245 # is ambiguous and we must skip.
246 #
247 # Otherwise the portion before ' see ' becomes the
248 # key and the portion afterwards becomes the
249 # value.
250  
251 if ($td->[1]->all_text =~
252 /^ # Start of string
253 (?! .* headings \s under) # Not matching look-ahead 'headings under'
254 (.*?) \s see \s # Match all characters up to ' see '
255 ( (?:(?! \s or \s ) # Complex match not matching ' or '
256 .)*) # ... but matching anything else
257 /x) {
258  
259 $key = $1;
260 $value = $2;
261  
262 # The value won't have the category prefix if
263 # it's in the current category, so we need to
264 # check and prepend if necessary.
265 if ($value !~ /^[A-Z]{3}/x) {
266 $value = $category . ' / ' . $value;
267 }
268 }
269 else {
270 $key = '';
271 $value = '';
272 }
273 }
274 # Remove trailing parentheticals and asterisks
275 $value =~ s/(.*?) \(.*\)/$1/;
276 $value =~ s/(.*?) \*/$1/;
277  
278 if($key and $value) {
279 $key = lc $key;
280 $self->{bisac_codes}->{$key} = $value;
281  
282 # Also put in a self-mapping of the lowercased
283 # value to itself if one does not already exist.
284 if (! $self->{bisac_codes}->{lc $value}) {
285 $self->{bisac_codes}->{lc $value} = $value;
286 }
287 }
288 }
289 else {
290 # There is one row with a single <td> element at the
291 # very end. We ignore this.
292 }
293 }
294 }
295 return;
296 }
297  
298  
299 =head2 C<load_bisac()>
300  
301 Load the BISAC codes from the specified database into the hash. This
302 is called automatically by new().
303  
304 If the load fails, nothing will happen (silently!), so the only way to
305 tell is to check to see if you have a populated hash afterwards.
306  
307 =cut
308  
309 sub load_bisac :method
310 {
311 my $self = shift;
312 my $subname = ( caller(0) )[3];
313  
314 my $dsn = $self->{dsn};
315 my $sql;
316  
317 my $dbh = DBI->connect(
318 $self->{dsn},$self->{dbuser},$self->{dbpass}, {
319 AutoCommit => 0,
320 PrintError => 0,
321 RaiseError => 0,
322 sqlite_see_if_its_a_number => 1,
323 });
324 return unless $dbh;
325  
326 my $sth;
327 my $row;
328  
329 $sth = $dbh->prepare('SELECT code,name FROM bisac_codes');
330 if (! $sth) {
331 # Table doesn't exist
332 $dbh->disconnect;
333 return;
334 }
335 $sth->execute() or croak ("Failed to load BISAC codes from database");
336 while($row = $sth->fetchrow_arrayref) {
337 $self->{bisac_codes}->{$row->[0]} = $row->[1];
338 }
339  
340 $dbh->disconnect();
341  
342 return;
343 }
344  
345  
346 =head2 C<save_bisac()>
347  
348 Save the BISAC codes in the hash to the database. This will destroy
349 any existing table named bisac_codes.
350  
351 Croaks on failure.
352  
353 =cut
354  
355 sub save_bisac :method
356 {
357 my $self = shift;
358 my $subname = ( caller(0) )[3];
359  
360 my $dbh = DBI->connect(
361 $self->{dsn},$self->{dbuser},$self->{dbpass}, {
362 AutoCommit => 0,
363 PrintError => 0,
364 RaiseError => 1,
365 sqlite_see_if_its_a_number => 1,
366 })
367 or croak("Failed to connect to $self->{dsn}");
368  
369 my $sth;
370 my $sql;
371 my @fields;
372 my $fieldlist;
373 my $placeholders;
374  
375 # Ensure the bisac_codes table exists as a blank slate.
376 $dbh->{RaiseError} = 0;
377 $sth = $dbh->prepare('SELECT * FROM bisac_codes WHERE 0 = 1');
378 $dbh->{RaiseError} = 1;
379 if ($sth) {
380 $dbh->do('DROP TABLE bisac_codes');
381 }
382  
383 $sql = '
384 CREATE TABLE bisac_codes (
385 code text PRIMARY KEY,
386 name text,
387 comment text
388 );';
389 $sth = $dbh->do($sql)
390 or croak ("Failed to create bisac_codes table!");
391 $dbh->commit();
392  
393 @fields = ('code','name');
394 $fieldlist = join (', ',@fields);
395 $placeholders = join (', ', map {'?'} @fields);
396 $sth = $dbh->prepare("INSERT INTO bisac_codes (${fieldlist}) VALUES (${placeholders})");
397 foreach my $key (keys %{$self->{bisac_codes}}) {
398 $sth->execute($key,$self->{bisac_codes}->{$key});
399 }
400 $dbh->commit;
401 $dbh->disconnect;
402  
403 return;
404 }
405  
406 1;
407 __END__
« blib/lib/EBook/Tools/Mobipocket.pm ↑ Summary blib/lib/EBook/Tools/MSReader.pm »