Aozora2Epub
view release on metacpan or search on metacpan
lib/Aozora2Epub.pm view on Meta::CPAN
package Aozora2Epub;
use utf8;
use strict;
use warnings;
use Aozora2Epub::Gensym;
use Aozora2Epub::CachedGet qw/http_get/;
use Aozora2Epub::Epub;
use Aozora2Epub::XHTML;
use Path::Tiny;
use URI;
use HTML::Escape qw/escape_html/;
use base qw(Class::Accessor);
__PACKAGE__->mk_accessors(qw/files title author epub bib_info notation_notes/);
our $VERSION = '0.05';
our $AOZORA_GAIJI_URL = 'https://www.aozora.gr.jp/gaiji/';
our $AOZORA_CARDS_URL = 'https://www.aozora.gr.jp/cards';
sub _base_url {
my $base = shift;
$base =~ s{[^/]+\.html$}{}s;
return $base;
}
sub _get_file {
my $url_or_path = "" . shift; # force to string.
if ($url_or_path =~ m{^https?://}) {
return http_get($url_or_path);
}
if ($url_or_path =~ m{\.html$}) {
return path($url_or_path)->slurp_utf8;
}
return path($url_or_path)->slurp_raw;
}
sub _get_content {
my $xhtml = shift;
if ($xhtml =~ m{/card\d+\.html$}) { # 峿¸ã«ã¼ã
unless ($xhtml =~ m{^https?://}) { # $xhtml shuld be \d+/card\d+.html
$xhtml = "$AOZORA_CARDS_URL/$xhtml";
}
my $text = _get_file($xhtml);
my $tree = Aozora2Epub::XHTML::Tree->new($text);
my $xhtml_url;
$tree->process('//a[text()="ãã¾ããXHTMLçã§èªã"]' => sub {
$xhtml_url = shift->attr('href');
});
my $xhtml_uri = URI->new($xhtml_url)->abs(URI->new($xhtml));
return _get_content($xhtml_uri->as_string);
}
if ($xhtml =~ m{/files/\d+_\d+\.html$}) { # XHTML
unless ($xhtml =~ m{^https?://}) { # $xhtml shuld be \d+/files/xxx_xxx.html
$xhtml = "$AOZORA_CARDS_URL/$xhtml";
}
my $text = _get_file($xhtml);
return ($text, _base_url($xhtml));
}
# XHTML string
return (qq{<div class="main_text">$xhtml</div>}, undef);
}
sub new {
my ($class, $content, %options) = @_;
my $self = bless {
files => [],
epub => Aozora2Epub::Epub->new,
title => undef,
author => undef,
bib_info => '',
notation_notes => '',
}, $class;
$self->append($content, %options, title=>'') if $content;
return $self;
}
sub _cat_url {
my ($base, $path) = @_;
unless ($base =~ m{^https?://}) {
return path($base, $path);
}
return URI->new($path)->abs(URI->new($base));
}
sub _build_elemlist_from_xhtml {
my $xhtml = shift;
my $tr = Aozora2Epub::XHTML->new_from_string(qq{<div class="main_text">$xhtml</div>});;
return @{$tr->contents};
}
sub append {
my ($self, $xhtml_like, %options) = @_;
( run in 1.657 second using v1.01-cache-2.11-cpan-600a1bdf6e4 )