Gutenberg.pm

filter: Statementstmt 93.1% 27 / 29 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 94.8% 37 / 39 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Gutenberg/Catalog.pm ↑ Summary
1 package EBook::Gutenberg;
2 2 ▶use 5.016;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 our $VERSION = '1.00';
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use Getopt::Long;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use File::Temp qw(tempfile);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use JSON::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use List::Util qw(all first max);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 0 ▶use EBook::Gutenberg::Catalog;
Subroutine BEGIN: called CC=1 SCAR=2.6
15 use EBook::Gutenberg::Dialog qw(:codes);
16 use EBook::Gutenberg::Get;
17 use EBook::Gutenberg::Home;
18  
19 my $PRGNAM = 'gutenberg';
20 my $PRGVER = $VERSION;
21  
22 my $HELP = <<"HERE";
23 $PRGNAM - $PRGVER
24  
25 Usage: $0 [options] command [command options] [args]
26  
27 Commands:
28 update Update local Project Gutenberg catalog
29 get <target> Download ebook matching target
30 search <target> Search for ebooks matching target
31 meta <id> Dump ebook metadata
32 menu Launch gutenberg ncurses interface
33  
34 Options:
35 -d|--data=<dir> gutenberg data directory
36 -y|--no-prompt Disable prompts for user input
37 -q|--quiet Disable informative output
38 -h|--help Print this help message
39 -v|--version Print gutenberg version
40  
41 Consult the gutenberg(1) manual for documentation on command-specific options.
42 HERE
43  
44 my $VER_MSG = <<"HERE";
45 $PRGNAM - $PRGVER
46  
47 Copyright (C) 2025 Samuel Young
48  
49 This program is free software: you can redistribute it and/or modify
50 it under the terms of the GNU General Public License as published by
51 the Free Software Foundation, either version 3 of the License, or
52 (at your option) any later version.
53 HERE
54  
55 my %COMMANDS = (
56 'update' => \&update,
57 'search' => \&search,
58 'get' => \&get,
59 'meta' => \&meta,
60 'menu' => \&menu,
61 );
62  
63 my $OLD_DEFAULT_DATA = File::Spec->catfile(home, '.gutenberg');
64 my $DOT_LOCAL = File::Spec->catfile(home, '.local/share');
65  
66 my $ARG_MAX = 4096;
67  
68 sub _default_data {
69  
70 # The default prior to 0.03
71 if (-d $OLD_DEFAULT_DATA) {
72 return $OLD_DEFAULT_DATA;
73 }
74  
75 if (exists $ENV{ XDG_DATA_HOME } and -d $ENV{ XDG_DATA_HOME }) {
76 return File::Spec->catfile($ENV{ XDG_DATA_HOME }, 'gutenberg');
77 }
78  
79 if (-d $DOT_LOCAL) {
80 return File::Spec->catfile($DOT_LOCAL, 'gutenberg');
81 }
82  
83 return $OLD_DEFAULT_DATA;
84  
85 }
86  
87 sub _prompt {
88  
89 my $prompt = shift;
90  
91 while (1) {
92 print "$prompt [y/N] ";
93 my $in = readline STDIN;
94 chomp $in;
95 if (fc $in eq fc 'y') {
96 return 1;
97 } elsif ($in eq '' or fc $in eq fc 'n') {
98 return 0;
99 } else {
100 warn "'$in' is an invalid reponse\n";
101 }
102 }
103  
104 }
105  
106 # Ask user to select a number out of a given list valid numbers
107 sub _nprompt {
108  
109 my $prompt = shift;
110 my %n = map { $_ => 1 } @_;
111  
112 while (1) {
113 print "$prompt ";
114 my $in = readline STDIN;
115 chomp $in;
116 if ($in eq '' or fc $in eq fc 'n') {
117 return undef;
118 } elsif ($in =~ /^\d+$/ and exists $n{ $in }) {
119 return $in;
120 } else {
121 warn "'$in' is an invalid reponse\n";
122 }
123 }
124  
125 }
126  
127 sub _title2rx {
128  
129 my $title = shift;
130  
131 my $rx;
132  
133 if ($title =~ /^\/(.*)\/$/) {
134 $rx = qr/$1/i;
135 # treat as literal string
136 } else {
137 $rx = qr/\Q$title\E/i;
138 }
139  
140 return $rx;
141  
142 }
143  
144 sub _target2param {
145  
146 my $targ = shift;
147  
148 if ($targ =~ /^\d+$/) {
149 return id => $targ;
150 } else {
151 return title => _title2rx($targ);
152 }
153  
154 }
155  
156 sub _book_meta_str {
157  
158 my $book = shift;
159  
160 return <<"HERE";
161 ID: $book->{ 'Text#' }
162 Title: $book->{ Title }
163 Type: $book->{ Type }
164 Issued: $book->{ Issued }
165 Authors: $book->{ Authors }
166 Language: $book->{ Language }
167 Subjects: $book->{ Subjects }
168 Shelves: $book->{ Bookshelves }
169 LoCC: $book->{ LoCC }
170 HERE
171  
172 }
173  
174 sub _book_meta_json {
175  
176 my $book = shift;
177  
178 my %copy = %$book;;
179  
180 for my $k (qw(Authors Subjects Bookshelves LoCC)) {
181 $copy{ $k } = [ split /\s*;\s*/, $copy{ $k } ];
182 }
183  
184 my $json = JSON::PP->new->pretty(1)->canonical(1);
185  
186 return $json->encode(\%copy);
187  
188 }
189  
190 sub _touch_get {
191  
192 my $self = shift;
193  
194 # touch file
195 if (-f $self->{ GetFile }) {
196 utime undef, undef, $self->{ GetFile };
197 # create file if it doesn't exist
198 } else {
199 my $fh;
200 open $fh, '>', $self->{ GetFile } and close $fh
201 or die "Failed to open $self->{ GetFile } for writing: $!\n";
202 }
203  
204 return 1;
205  
206 }
207  
208 # Wait at least 5 seconds between multiple Project Gutenberg network
209 # operations (update, get)
210 sub _get_ok {
211  
212 my $self = shift;
213  
214 return time - ((stat($self->{ GetFile }))[9] // 0) > 5;
215  
216 }
217  
218 sub _gen_search_params {
219  
220 my $self = shift;
221  
222 my %search;
223  
224 if (@{ $self->{ Args } }) {
225 my ($k, $v) = _target2param($self->{ Args }->[0]);
226 $search{ $k } = $v;
227 }
228  
229 if (@{ $self->{ Authors } }) {
230 $search{ authors } = $self->{ Authors };
231 }
232  
233 if (@{ $self->{ Subjects } }) {
234 $search{ subjects } = $self->{ Subjects };
235 }
236  
237 if (defined $self->{ Language }) {
238 $search{ language } = $self->{ Language };
239 }
240  
241 if (@{ $self->{ Shelves } }) {
242 $search{ shelves } = $self->{ Shelves };
243 }
244  
245 return %search;
246  
247 }
248  
249 sub _search {
250  
251 my $self = shift;
252 my %params = @_;
253  
254 my $catalog = EBook::Gutenberg::Catalog->new($self->{ Catalog });
255  
256 my $filter = {
257 Type => sub { $_ eq 'Text' },
258 };
259  
260 if (defined $params{ title }) {
261 $filter->{ Title } = sub { m/$params{ title }/i };
262 }
263  
264 if (defined $params{ id }) {
265 $filter->{ 'Text#' } = sub { $_ == $params{ id } };
266 }
267  
268 # Get a list words from each supplied author parameter, with non-word
269 # characters stripped out. Then filter out books that do not contain every
270 # word from that list in their author entries. This seems to be the simplest
271 # and DWIMest way of going about this that I could find.
272 if (defined $params{ authors } and @{ $params{ authors } }) {
273 my @words =
274 map { split /\s+/ }
275 map { s/\W+/ /gr }
276 @{ $params{ authors } };
277 $filter->{ Authors } = sub {
278 my $a = $_;
279 all { $a =~ m/(^|\W)\Q$_\E(\W|$)/i } @words;
280 };
281 }
282  
283 # Same as authors
284 if (defined $params{ subjects } and @{ $params{ subjects } }) {
285 my @words =
286 map { split /\s+/ }
287 map { s/\W+/ /gr }
288 @{ $params{ subjects } };
289 $filter->{ Subjects } = sub {
290 my $a = $_;
291 all { $a =~ m/(^|\W)\Q$_\E(\W|$)/i } @words;
292 };
293 }
294  
295 # Same as authors
296 if (defined $params{ shelves } and @{ $params{ shelves } }) {
297 my @words =
298 map { split /\s+/ }
299 map { s/\W+/ /gr }
300 @{ $params{ shelves } };
301 $filter->{ Bookshelves } = sub {
302 my $a = $_;
303 all { $a =~ m/(^|\W)\Q$_\E(\W|$)/i } @words;
304 };
305 }
306  
307 if (defined $params{ language }) {
308 $filter->{ Language } = sub { $_ eq $params{ language } };
309 }
310  
311 my @books = @{ $catalog->books($filter) };
312  
313 return @books;
314  
315 }
316  
317 sub _print_list {
318  
319 my @books = @_;
320  
321 # ugly :-(
322 my $idlen = max (length('ID'), map { length $_->{ 'Text#' } } @books);
323 printf "%-*s %s\n", $idlen, 'ID', 'Title';
324 printf "%s\n", '-' x 25;
325 for my $b (@books) {
326 printf "%-*s %s\n", $idlen, $b->{ 'Text#' }, $b->{ Title };
327 }
328  
329 }
330  
331 sub _dialog_search {
332  
333 my $self = shift;
334  
335 state $ltitl = '';
336 state $lauth = '';
337 state $lsubj = '';
338 state $llang = '';
339 state $lshlf = '';
340 state $lebid = '';
341  
342 while (1) {
343  
344 my ($rv, $form) = $self->{ Dialog }->form(
345 <<'HERE',
346 Search for an ebook using the parameter fields below. Fields left blank will be
347 ignored. The "Title" field can be given a Perl regex if the input starts and
348 ends with a slash (/) character.
349 HERE
350 17, 45, 6,
351 'Title', 1, 0, $ltitl, 1, 10, 36, 255,
352 'Author', 2, 0, $lauth, 2, 10, 36, 255,
353 'Subject', 3, 0, $lsubj, 3, 10, 36, 255,
354 'Language', 4, 0, $llang, 4, 10, 36, 255,
355 'Shelf', 5, 0, $lshlf, 5, 10, 36, 255,
356 'ID', 6, 0, $lebid, 6, 10, 36, 255,
357 {
358 title => 'Search',
359 ok_label => 'Search',
360 extra_button => 1,
361 extra_label => 'Update',
362 erase_on_exit => 1,
363 },
364 );
365  
366 last if $rv == DIALOG_CANCEL or $rv == DIALOG_ESC;
367  
368 $self->{ Dialog }->infobox('Searching...', 0, 0);
369  
370 ($ltitl, $lauth, $lsubj, $llang, $lshlf, $lebid) = @$form;
371  
372 if ($rv == DIALOG_EXTRA) {
373 $rv = $self->{ Dialog }->yesno(
374 'Would you like to update your local gutenberg catalog?', 0, 0
375 );
376 next if $rv != DIALOG_OK;
377 $self->{ Dialog }->infobox('Updating gutenberg catalog...', 0, 0);
378 my $catalog = EBook::Gutenberg::Catalog->new($self->{ Catalog });
379 sleep 5 unless $self->_get_ok;
380 $self->_touch_get;
381 eval { $catalog->fetch };
382 if ($@ ne '') {
383 $self->{ Dialog }->msgbox("Failed to fetch catalog: $@", 0, 0);
384 next;
385 }
386 $self->{ Dialog }->msgbox(
387 "Successfully updated gutenberg catalog", 0, 0
388 );
389 } elsif ($rv == DIALOG_OK) {
390  
391 unless (-s $self->{ Catalog }) {
392 $self->{ Dialog }->msgbox(
393 <<'HERE', 0, 0
394 No existing Project Gutenberg catalog found. Please run a catalog update before
395 searching.
396 HERE
397 );
398 next;
399 }
400  
401 my %param;
402  
403 if ($ltitl ne '') {
404 $param{ title } = _title2rx($ltitl);
405 }
406  
407 if ($lauth ne '') {
408 $param{ authors } = [ $lauth ];
409 }
410  
411 if ($lsubj ne '') {
412 $param{ subjects } = [ $lsubj ];
413 }
414  
415 if ($llang ne '') {
416 $param{ language } = $llang;
417 }
418  
419 if ($lshlf ne '') {
420 $param{ shelves } = [ $lshlf ];
421 }
422  
423 if ($lebid ne '') {
424 unless ($lebid =~ /^\d+$/) {
425 $self->{ Dialog }->msgbox(
426 "'ID' must be an integar", 0, 0
427 );
428 next;
429 }
430 $param{ id } = $lebid;
431 }
432  
433 unless (%param) {
434 $self->{ Dialog }->msgbox(
435 'No search parameters provided.', 0, 0
436 );
437 next;
438 }
439  
440 my @books = $self->_search(%param);
441  
442 if (@books > $ARG_MAX) {
443 $self->{ Dialog }->msgbox(
444 'Too many search results. Please narrow your search parameters.',
445 0, 0
446 );
447 next;
448 } elsif (@books == 0) {
449 $self->{ Dialog }->msgbox(
450 'Found no ebooks matching the given search parameters.', 0, 0
451 );
452 } else {
453 $self->_dialog_download_select(\@books);
454 }
455 }
456 }
457  
458 return 1;
459  
460 }
461  
462 sub _dialog_download_select {
463  
464 my $self = shift;
465 my $books = shift;
466  
467 my @iter = map { $_->{ 'Text#' } => $_->{ Title } } @$books;
468  
469 while (1) {
470  
471 my ($rv, $sel) = $self->{ Dialog }->menu(
472 '', 0, 0, 0,
473 @iter,
474 {
475 title => 'Search Results',
476 ok_label => 'View',
477 },
478 );
479  
480 last if $rv == DIALOG_CANCEL or $rv == DIALOG_ESC;
481  
482 my $book = first { $_->{ 'Text#' } == $sel } @$books;
483  
484 $self->_dialog_ebook($book);
485  
486 }
487  
488 return 1;
489  
490 }
491  
492 sub _dialog_ebook {
493  
494 my $self = shift;
495 my $book = shift;
496  
497 while (1) {
498  
499 my $rv = $self->{ Dialog }->yesno(
500 _book_meta_str($book), 0, 0,
501 {
502 title => $book->{ Title },
503 yes_label => 'Download',
504 extra_button => 1,
505 extra_label => 'Read',
506 no_label => 'Cancel',
507 },
508 );
509  
510 if ($rv == DIALOG_OK) {
511 $self->_dialog_download_format($book);
512 } elsif ($rv == DIALOG_EXTRA) {
513 $self->_dialog_read($book);
514 } elsif ($rv == DIALOG_CANCEL or $rv == DIALOG_ESC) {
515 last;
516 }
517  
518 }
519  
520 return 1;
521  
522 }
523  
524 sub _dialog_download_format {
525  
526 my $self = shift;
527 my $book = shift;
528  
529 while (1) {
530  
531 my ($rv, $sel) = $self->{ Dialog }->menu(
532 '', 0, 0, 0,
533 'epub3', 'Newer style EPUB. May not be compatible with older e-readers.',
534 'epub', 'Older style EPUB. Better compatibility with older e-readers.',
535 'epub-noimages', 'Same as "epub" but with no images.',
536 'kindle', 'KF8 ebook, an Amazon-proprietary format used by newer Kindle devices.',
537 'mobi', 'Ebook format commonly used by older Kindle devices.',
538 'text', 'Plain text file.',
539 'zip', 'Zip archive of HTML and images.',
540 'html', 'Single HTML page.',
541 {
542 title => 'Format Selection',
543 },
544 );
545  
546 last if $rv == DIALOG_CANCEL or $rv == DIALOG_ESC;
547  
548 $self->_dialog_download($book, $sel);
549  
550 }
551  
552 }
553  
554 sub _dialog_download {
555  
556 my $self = shift;
557 my $book = shift;
558 my $fmt = shift;
559  
560 my $default = sprintf "%s.%s",
561 $book->{ Title },
562 $EBook::Gutenberg::Get::FORMATS{ $fmt }->{ suffix };
563  
564  
565 my ($rv, $path) = $self->{ Dialog }->inputbox(
566 'Please input the path to write the downloaded ebook to.', 0, 0,
567 $default,
568 );
569  
570 return 1 if $rv == DIALOG_CANCEL or $rv == DIALOG_ESC;
571  
572 $self->{ Dialog }->infobox('Fetching ebook...', 0, 0);
573  
574 my $p = eval {
575 sleep 5 unless $self->_get_ok;
576 $self->_touch_get;
577 gutenberg_get(
578 $book->{ 'Text#' },
579 { fmt => $fmt, to => $path }
580 );
581 };
582  
583 if ($@ ne '') {
584 $self->{ Dialog }->msgbox(
585 "Failed to fetch ebook: $@", 0, 0
586 );
587 return 1;
588 }
589  
590 $self->{ Dialog }->msgbox(
591 "Successfully fetched $p", 0, 0
592 );
593  
594 return 1;
595  
596 }
597  
598 sub _dialog_read {
599  
600 my $self = shift;
601 my $book = shift;
602  
603 $self->{ Dialog }->infobox(
604 'Fetching text...', 0, 0
605 );
606  
607 my $file = $self->{ TxtCache }{ $book->{ 'Text#' } } // do {
608  
609 my $p = eval {
610 my $tmp = do {
611 my ($fh, $fn) = tempfile;
612 close $fh;
613 $fn;
614 };
615 # TODO: Sleep less?
616 sleep 5 unless $self->_get_ok;
617 $self->_touch_get;
618 gutenberg_get(
619 $book->{ 'Text#' },
620 { fmt => 'text', to => $tmp },
621 );
622 };
623  
624 if ($@ ne '') {
625 $self->{ Dialog }->msgbox(
626 "Failed to fetch ebook: $@", 0, 0
627 );
628 return 1;
629 }
630  
631 $self->{ TxtCache }{ $book->{ 'Text#' } } = $p;
632  
633 };
634  
635 # dialog does have a textbox widget, but it doesn't display large text files
636 # like Gutenberg's text ebooks correctly, so we'll just use a pager instead.
637 $self->{ Dialog }->pager($file);
638  
639 return 1;
640  
641 }
642  
643 sub help {
644  
645 my $self = shift;
646 my $exit = shift;
647  
648 print $HELP;
649  
650 exit $exit if defined $exit;
651  
652 return 1;
653  
654 }
655  
656 sub update {
657  
658 my $self = shift;
659  
660 my $catalog = EBook::Gutenberg::Catalog->new($self->{ Catalog });
661  
662 unless ($self->_get_ok) {
663 die "Please wait at least 5 seconds before performing another " .
664 "network operation with Project Gutenberg\n";
665 }
666  
667 unless ($self->{ Quiet }) {
668 say "Fetching Project Gutenberg catalog, please be patient";
669 }
670  
671 $catalog->fetch;
672  
673 $self->_touch_get;
674  
675 unless ($self->{ Quiet }) {
676 say "Updated $self->{ Catalog }";
677 }
678  
679 return 1;
680  
681 }
682  
683 sub search {
684  
685 my $self = shift;
686  
687 unless (-f $self->{ Catalog }) {
688 die "Could not find an existing Project Gutenberg catalog, please " .
689 "run 'update' to fetch a catalog before running 'search'\n";
690 }
691  
692 my %search = $self->_gen_search_params;
693  
694 unless (%search) {
695 $self->help(1);
696 }
697  
698 my @books = $self->_search(%search);
699  
700 if (@books == 0) {
701 die "Could not find any ebooks matching the given parameters\n";
702 } else {
703 _print_list(@books);
704 }
705  
706 return 1;
707  
708 }
709  
710 sub get {
711  
712 my $self = shift;
713  
714 unless (-f $self->{ Catalog }) {
715 die "Could not find an existing Project Gutenberg catalog, please " .
716 "run 'update' to fetch a catalog before running 'get'\n";
717 }
718  
719 unless ($self->_get_ok) {
720 die "Please wait at least 5 seconds before performing another " .
721 "network operation with Project Gutenberg\n";
722 }
723  
724 my %search = $self->_gen_search_params;
725  
726 unless (%search) {
727 $self->help(1);
728 }
729  
730 my @books = $self->_search(%search);
731  
732 my $sel;
733  
734 if (@books == 0) {
735 die "Could not find any ebooks matching the given parameters\n";
736 } elsif (@books == 1 or $self->{ NoPrompt }) {
737 $sel = $books[0];
738 } else {
739  
740 my %nmap = map { $books[$_]->{ 'Text#' } => $_ } 0 .. $#books;
741  
742 _print_list(@books);
743  
744 if (@books >= 100 and !$self->{ Quiet }) {
745 say "You might consider narrowing your search parameters";
746 }
747  
748 my $n = _nprompt("Please select an ebook ID:", keys %nmap);
749  
750 unless (defined $n) {
751 say "Doing nothing" unless $self->{ Quiet };
752 return 1;
753 }
754  
755 $sel = $books[$nmap{ $n }];
756  
757 }
758  
759 unless ($sel->{ Type } eq 'Text') {
760 die "gutenberg does not currently support fetching non-text ebooks\n";
761 }
762  
763 my $ok = $self->{ NoPrompt } ? 1 : do {
764 print _book_meta_str($sel);
765 _prompt("Would you like to download this ebook?");
766 };
767  
768 unless ($ok) {
769 say "Doing nothing" unless $self->{ Quiet };
770 return 1;
771 }
772  
773 my $link = gutenberg_link($sel->{ 'Text#' }, $self->{ Format });
774  
775 unless ($self->{ Quiet }) {
776 say "Fetching $link, please be patient.";
777 }
778  
779 my $fetch = gutenberg_get(
780 $sel->{ 'Text#' },
781 {
782 fmt => $self->{ Format },
783 to => $self->{ To } // "$sel->{ Title }.*",
784 }
785 );
786  
787 $self->_touch_get;
788  
789 unless ($self->{ Quiet }) {
790 say "Downloaded ebook to $fetch";
791 }
792  
793 return 1;
794  
795 }
796  
797 sub meta {
798  
799 my $self = shift;
800  
801 unless (-f $self->{ Catalog }) {
802 die "Could not find an existing Project Gutenberg catalog, please " .
803 "run 'update' to fetch a catalog before running 'meta'\n";
804 }
805  
806 my $id = shift @{ $self->{ Args } }
807 or $self->help(1);
808  
809 unless ($id =~ /^\d+$/) {
810 die "'meta' must be given an ebook ID as argument\n";
811 }
812  
813 my $catalog = EBook::Gutenberg::Catalog->new($self->{ Catalog });
814  
815 my $book = $catalog->book($id);
816  
817 unless (defined $book) {
818 die "Could not find an ebook with an ID of $id\n";
819 }
820  
821 if ($self->{ MetaJSON }) {
822 print _book_meta_json($book);
823 } else {
824 print _book_meta_str($book);
825 }
826  
827 return 1;
828  
829 }
830  
831 sub menu {
832  
833 my $self = shift;
834  
835 my $dialog;
836 my ($rv, $sel);
837  
838 $self->{ Dialog } = EBook::Gutenberg::Dialog->new(
839 backtitle => "$PRGNAM $PRGVER"
840 );
841  
842 $self->_dialog_search;
843  
844 return 1;
845  
846 }
847  
848 sub init {
849  
850 my $class = shift;
851  
852 my $self = {
853 Command => undef,
854 Data => undef,
855 To => undef,
856 Format => undef,
857 Authors => [],
858 Subjects => [],
859 Language => undef,
860 Shelves => [],
861 NoPrompt => 0,
862 Quiet => 0,
863 MetaJSON => 0,
864 Args => [],
865 # Not set by any option
866 Catalog => undef,
867 GetFile => undef,
868 Dialog => undef,
869 TxtCache => {},
870 };
871  
872 bless $self, $class;
873  
874 Getopt::Long::config('bundling');
875 GetOptions(
876 'data|d=s' => \$self->{ Data },
877 'to|t=s' => \$self->{ To },
878 'format|f=s' => \$self->{ Format },
879 'author|a=s' => $self->{ Authors },
880 'subject|s=s' => $self->{ Subjects },
881 'language|l=s' => \$self->{ Language },
882 'shelf|H=s' => $self->{ Shelves },
883 'no-prompt|y' => \$self->{ NoPrompt },
884 'quiet|q' => \$self->{ Quiet },
885 'json|j' => \$self->{ MetaJSON },
886 'help|h' => sub { $self->help(0); },
887 'version|v' => sub { print $VER_MSG; exit 0; },
888 ) or die "Invalid command line arguments\n";
889  
890 $self->{ Command } = shift @ARGV or $self->help(1);
891 $self->{ Args } = [ @ARGV ];
892  
893 unless (exists $COMMANDS{ $self->{ Command } }) {
894 die "'$self->{ Command }' is not a valid command\n";
895 }
896  
897 $self->{ Data } //= $ENV{ GUTENBERG_DATA };
898 $self->{ Data } //= _default_data;
899 unless (-d $self->{ Data }) {
900 make_path($self->{ Data });
901 }
902 $self->{ Catalog } = File::Spec->catfile(
903 $self->{ Data },
904 'pg_catalog.csv'
905 );
906 # GetFile is used to keep track of the last time we fetched something from
907 # Project Gutenberg. gutenberg tries to wait at least 5 seconds between
908 # Project Gutenberg network operations.
909 $self->{ GetFile } = File::Spec->catfile(
910 $self->{ Data },
911 'get'
912 );
913  
914 $self->{ Format } //= 'epub3';
915 $self->{ Format } = lc $self->{ Format };
916 unless (exists $EBook::Gutenberg::Get::FORMATS{ $self->{ Format } }) {
917 die "'$self->{ Format }' is not a valid ebook format\n";
918 }
919  
920 if (defined $self->{ Language }) {
921 unless (length $self->{ Language } == 2) {
922 die "-l|--language takes a two-character language code as argument\n";
923 }
924 $self->{ Language } = lc $self->{ Language };
925 }
926  
927 binmode *STDOUT, ':utf8';
928  
929 return $self;
930  
931 }
932  
933 sub run {
934  
935 my $self = shift;
936  
937 $COMMANDS{ $self->{ Command } }($self);
938  
939 return 1;
940  
941 }
942  
943 DESTROY {
944  
945 my $self = shift;
946  
947 for my $f (keys %{ $self->{ TxtCache } }) {
948 unlink $f if -e $f;
949 }
950  
951 }
952  
953 1;
954  
955 =head1 NAME
956  
957 EBook::Gutenberg - Fetch ebooks from Project Gutenberg
958  
959 =head1 SYNOPSIS
960  
961 use EBook::Gutenberg;
962  
963 my $gutenberg = EBook::Gutenberg->init;
964 $gutenberg->run;
965  
966 =head1 DESCRIPTION
967  
968 B<EBook::Gutenberg> is a module that provides the core functionality for the
969 L<gutenberg> utility. This is developer documentation, for L<gutenberg> user
970 documentation you should consult its manual.
971  
972 =head1 METHODS
973  
974 =over 4
975  
976 =item $gut = EBook::Gutenberg->init()
977  
978 Reads C<@ARGV> and returns a blessed C<EBook::Gutenberg> object.
979  
980 =item $gut->run()
981  
982 Runs L<gutenberg> based on the parameters processed in C<init()>.
983  
984 =item $gut->update
985  
986 Update local Project Gutenberg catalog; the C<update> command.
987  
988 =item $gut->search
989  
990 Search for ebooks; the C<search> command.
991  
992 =item $gut->get
993  
994 Download an ebook; the C<get> command.
995  
996 =item $gut->meta
997  
998 Print ebook metadata; the C<meta> command.
999  
1000 =item $gut->menu
1001  
1002 Launch the L<dialog(1)>-based menu interface.
1003  
1004 =item $gut->help([$exit])
1005  
1006 Print L<gutenberg> manual. Exit with code C<$exit> if provided.
1007  
1008 =back
1009  
1010 =head1 AUTHOR
1011  
1012 Written by Samuel Young, E<lt>samyoung12788@gmail.comE<gt>.
1013  
1014 This project's source can be found on its
1015 L<Codeberg page|https://codeberg.org/1-1sam/gutenberg>. Comments and pull
1016 requests are welcome!
1017  
1018 =head1 COPYRIGHT
1019  
1020 Copyright (C) 2025 Samuel Young
1021  
1022 This program is free software: you can redistribute it and/or modify
1023 it under the terms of the GNU General Public License as published by
1024 the Free Software Foundation, either version 3 of the License, or
1025 (at your option) any later version.
1026  
1027 =head1 SEE ALSO
1028  
1029 L<gutenberg>
1030  
1031 =cut
1032  
1033 # vim: expandtab shiftwidth=4
« Gutenberg/Catalog.pm ↑ Summary