update epub internal

This commit is contained in:
Celogeek 2024-01-05 17:55:32 +01:00
parent 4a12fe5715
commit 5c1728dff8
Signed by: celogeek
SSH Key Fingerprint: SHA256:DEDfxIK2nUWXbslbRkww3zsauDjhWHlTXar+ak4lDJ4

View File

@ -15,34 +15,35 @@ import (
"text/template" "text/template"
"time" "time"
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image" "github.com/celogeek/go-comic-converter/v2/internal/epubimage"
epubimageprocessor "github.com/celogeek/go-comic-converter/v2/internal/epub/imageprocessor" "github.com/celogeek/go-comic-converter/v2/internal/epubimageprocessor"
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options" "github.com/celogeek/go-comic-converter/v2/internal/epubprogress"
epubprogress "github.com/celogeek/go-comic-converter/v2/internal/epub/progress" "github.com/celogeek/go-comic-converter/v2/internal/epubtemplates"
epubtemplates "github.com/celogeek/go-comic-converter/v2/internal/epub/templates" "github.com/celogeek/go-comic-converter/v2/internal/epubtree"
epubtree "github.com/celogeek/go-comic-converter/v2/internal/epub/tree" "github.com/celogeek/go-comic-converter/v2/internal/epubzip"
epubzip "github.com/celogeek/go-comic-converter/v2/internal/epub/zip" "github.com/celogeek/go-comic-converter/v2/pkg/epuboptions"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
) )
type ePub struct { type ePub struct {
*epuboptions.Options options *epuboptions.EPUBOptions
UID string
Publisher string uid string
UpdatedAt string publisher string
updatedAt string
templateProcessor *template.Template templateProcessor *template.Template
imageProcessor *epubimageprocessor.EPUBImageProcessor imageProcessor *epubimageprocessor.EPUBImageProcessor
} }
type epubPart struct { type epubPart struct {
Cover *epubimage.Image Cover *epubimage.EPUBImage
Images []*epubimage.Image Images []*epubimage.EPUBImage
Reader *zip.ReadCloser Reader *zip.ReadCloser
} }
// initialize EPUB // initialize EPUB
func New(options *epuboptions.Options) *ePub { func New(options *epuboptions.EPUBOptions) *ePub {
uid := uuid.Must(uuid.NewV4()) uid := uuid.Must(uuid.NewV4())
tmpl := template.New("parser") tmpl := template.New("parser")
tmpl.Funcs(template.FuncMap{ tmpl.Funcs(template.FuncMap{
@ -51,10 +52,10 @@ func New(options *epuboptions.Options) *ePub {
}) })
return &ePub{ return &ePub{
Options: options, options: options,
UID: uid.String(), uid: uid.String(),
Publisher: "GO Comic Converter", publisher: "GO Comic Converter",
UpdatedAt: time.Now().UTC().Format("2006-01-02T15:04:05Z"), updatedAt: time.Now().UTC().Format("2006-01-02T15:04:05Z"),
templateProcessor: tmpl, templateProcessor: tmpl,
imageProcessor: epubimageprocessor.New(options), imageProcessor: epubimageprocessor.New(options),
} }
@ -71,14 +72,14 @@ func (e *ePub) render(templateString string, data map[string]any) string {
} }
// write image to the zip // write image to the zip
func (e *ePub) writeImage(wz *epubzip.EPUBZip, img *epubimage.Image, zipImg *zip.File) error { func (e *ePub) writeImage(wz *epubzip.EPUBZip, img *epubimage.EPUBImage, zipImg *zip.File) error {
err := wz.WriteContent( err := wz.WriteContent(
img.EPUBPagePath(), img.EPUBPagePath(),
[]byte(e.render(epubtemplates.Text, map[string]any{ []byte(e.render(epubtemplates.Text, map[string]any{
"Title": fmt.Sprintf("Image %d Part %d", img.Id, img.Part), "Title": fmt.Sprintf("Image %d Part %d", img.Id, img.Part),
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height), "ViewPort": fmt.Sprintf("width=%d,height=%d", e.options.Image.View.Width, e.options.Image.View.Height),
"ImagePath": img.ImgPath(), "ImagePath": img.ImgPath(),
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""), "ImageStyle": img.ImgStyle(e.options.Image.View.Width, e.options.Image.View.Height, ""),
})), })),
) )
if err == nil { if err == nil {
@ -89,18 +90,18 @@ func (e *ePub) writeImage(wz *epubzip.EPUBZip, img *epubimage.Image, zipImg *zip
} }
// write blank page // write blank page
func (e *ePub) writeBlank(wz *epubzip.EPUBZip, img *epubimage.Image) error { func (e *ePub) writeBlank(wz *epubzip.EPUBZip, img *epubimage.EPUBImage) error {
return wz.WriteContent( return wz.WriteContent(
img.EPUBSpacePath(), img.EPUBSpacePath(),
[]byte(e.render(epubtemplates.Blank, map[string]any{ []byte(e.render(epubtemplates.Blank, map[string]any{
"Title": fmt.Sprintf("Blank Page %d", img.Id), "Title": fmt.Sprintf("Blank Page %d", img.Id),
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height), "ViewPort": fmt.Sprintf("width=%d,height=%d", e.options.Image.View.Width, e.options.Image.View.Height),
})), })),
) )
} }
// write title image // write title image
func (e *ePub) writeCoverImage(wz *epubzip.EPUBZip, img *epubimage.Image, part, totalParts int) error { func (e *ePub) writeCoverImage(wz *epubzip.EPUBZip, img *epubimage.EPUBImage, part, totalParts int) error {
title := "Cover" title := "Cover"
text := "" text := ""
if totalParts > 1 { if totalParts > 1 {
@ -112,9 +113,9 @@ func (e *ePub) writeCoverImage(wz *epubzip.EPUBZip, img *epubimage.Image, part,
"OEBPS/Text/cover.xhtml", "OEBPS/Text/cover.xhtml",
[]byte(e.render(epubtemplates.Text, map[string]any{ []byte(e.render(epubtemplates.Text, map[string]any{
"Title": title, "Title": title,
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height), "ViewPort": fmt.Sprintf("width=%d,height=%d", e.options.Image.View.Width, e.options.Image.View.Height),
"ImagePath": fmt.Sprintf("Images/cover.%s", e.Image.Format), "ImagePath": fmt.Sprintf("Images/cover.%s", e.options.Image.Format),
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""), "ImageStyle": img.ImgStyle(e.options.Image.View.Width, e.options.Image.View.Height, ""),
})), })),
); err != nil { ); err != nil {
return err return err
@ -143,22 +144,22 @@ func (e *ePub) writeCoverImage(wz *epubzip.EPUBZip, img *epubimage.Image, part,
} }
// write title image // write title image
func (e *ePub) writeTitleImage(wz *epubzip.EPUBZip, img *epubimage.Image, title string) error { func (e *ePub) writeTitleImage(wz *epubzip.EPUBZip, img *epubimage.EPUBImage, title string) error {
titleAlign := "" titleAlign := ""
if !e.Image.View.PortraitOnly { if !e.options.Image.View.PortraitOnly {
if e.Image.Manga { if e.options.Image.Manga {
titleAlign = "right:0" titleAlign = "right:0"
} else { } else {
titleAlign = "left:0" titleAlign = "left:0"
} }
} }
if !e.Image.View.PortraitOnly { if !e.options.Image.View.PortraitOnly {
if err := wz.WriteContent( if err := wz.WriteContent(
"OEBPS/Text/space_title.xhtml", "OEBPS/Text/space_title.xhtml",
[]byte(e.render(epubtemplates.Blank, map[string]any{ []byte(e.render(epubtemplates.Blank, map[string]any{
"Title": "Blank Page Title", "Title": "Blank Page Title",
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height), "ViewPort": fmt.Sprintf("width=%d,height=%d", e.options.Image.View.Width, e.options.Image.View.Height),
})), })),
); err != nil { ); err != nil {
return err return err
@ -169,9 +170,9 @@ func (e *ePub) writeTitleImage(wz *epubzip.EPUBZip, img *epubimage.Image, title
"OEBPS/Text/title.xhtml", "OEBPS/Text/title.xhtml",
[]byte(e.render(epubtemplates.Text, map[string]any{ []byte(e.render(epubtemplates.Text, map[string]any{
"Title": title, "Title": title,
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height), "ViewPort": fmt.Sprintf("width=%d,height=%d", e.options.Image.View.Width, e.options.Image.View.Height),
"ImagePath": fmt.Sprintf("Images/title.%s", e.Image.Format), "ImagePath": fmt.Sprintf("Images/title.%s", e.options.Image.Format),
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, titleAlign), "ImageStyle": img.ImgStyle(e.options.Image.View.Width, e.options.Image.View.Height, titleAlign),
})), })),
); err != nil { ); err != nil {
return err return err
@ -199,7 +200,7 @@ func (e *ePub) writeTitleImage(wz *epubzip.EPUBZip, img *epubimage.Image, title
} }
// extract image and split it into part // extract image and split it into part
func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipStorageImageReader, err error) { func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipImageReader, err error) {
images, err := e.imageProcessor.Load() images, err := e.imageProcessor.Load()
if err != nil { if err != nil {
@ -216,11 +217,11 @@ func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipStorage
parts = make([]*epubPart, 0) parts = make([]*epubPart, 0)
cover := images[0] cover := images[0]
if e.Image.HasCover { if e.options.Image.HasCover {
images = images[1:] images = images[1:]
} }
if e.Dry { if e.options.Dry {
parts = append(parts, &epubPart{ parts = append(parts, &epubPart{
Cover: cover, Cover: cover,
Images: images, Images: images,
@ -228,19 +229,19 @@ func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipStorage
return parts, nil, nil return parts, nil, nil
} }
imgStorage, err = epubzip.NewEPUBZipStorageImageReader(e.ImgStorage()) imgStorage, err = epubzip.NewImageReader(e.options.Temp())
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
// compute size of the EPUB part and try to be as close as possible of the target // compute size of the EPUB part and try to be as close as possible of the target
maxSize := uint64(e.LimitMb * 1024 * 1024) maxSize := uint64(e.options.LimitMb * 1024 * 1024)
xhtmlSize := uint64(1024) xhtmlSize := uint64(1024)
// descriptor files + title + cover // descriptor files + title + cover
baseSize := uint64(128*1024) + imgStorage.Size(cover.EPUBImgPath())*2 baseSize := uint64(128*1024) + imgStorage.Size(cover.EPUBImgPath())*2
currentSize := baseSize currentSize := baseSize
currentImages := make([]*epubimage.Image, 0) currentImages := make([]*epubimage.EPUBImage, 0)
part := 1 part := 1
for _, img := range images { for _, img := range images {
@ -252,7 +253,7 @@ func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipStorage
}) })
part += 1 part += 1
currentSize = baseSize currentSize = baseSize
currentImages = make([]*epubimage.Image, 0) currentImages = make([]*epubimage.EPUBImage, 0)
} }
currentSize += imgSize currentSize += imgSize
currentImages = append(currentImages, img) currentImages = append(currentImages, img)
@ -270,7 +271,7 @@ func (e *ePub) getParts() (parts []*epubPart, imgStorage *epubzip.EPUBZipStorage
// create a tree from the directories. // create a tree from the directories.
// //
// this is used to simulate the toc. // this is used to simulate the toc.
func (e *ePub) getTree(images []*epubimage.Image, skip_files bool) string { func (e *ePub) getTree(images []*epubimage.EPUBImage, skip_files bool) string {
t := epubtree.New() t := epubtree.New()
for _, img := range images { for _, img := range images {
if skip_files { if skip_files {
@ -280,7 +281,7 @@ func (e *ePub) getTree(images []*epubimage.Image, skip_files bool) string {
} }
} }
c := t.Root() c := t.Root()
if skip_files && e.StripFirstDirectoryFromToc && len(c.Children) == 1 { if skip_files && e.options.StripFirstDirectoryFromToc && len(c.Children) == 1 {
c = c.Children[0] c = c.Children[0]
} }
@ -315,21 +316,21 @@ func (e *ePub) computeAspectRatio(epubParts []*epubPart) float64 {
} }
func (e *ePub) computeViewPort(epubParts []*epubPart) { func (e *ePub) computeViewPort(epubParts []*epubPart) {
if e.Image.View.AspectRatio == -1 { if e.options.Image.View.AspectRatio == -1 {
return //keep device size return //keep device size
} }
// readjusting view port // readjusting view port
bestAspectRatio := e.Image.View.AspectRatio bestAspectRatio := e.options.Image.View.AspectRatio
if bestAspectRatio == 0 { if bestAspectRatio == 0 {
bestAspectRatio = e.computeAspectRatio(epubParts) bestAspectRatio = e.computeAspectRatio(epubParts)
} }
viewWidth, viewHeight := int(float64(e.Image.View.Height)/bestAspectRatio), int(float64(e.Image.View.Width)*bestAspectRatio) viewWidth, viewHeight := int(float64(e.options.Image.View.Height)/bestAspectRatio), int(float64(e.options.Image.View.Width)*bestAspectRatio)
if viewWidth > e.Image.View.Width { if viewWidth > e.options.Image.View.Width {
e.Image.View.Height = viewHeight e.options.Image.View.Height = viewHeight
} else { } else {
e.Image.View.Width = viewWidth e.options.Image.View.Width = viewWidth
} }
} }
@ -345,12 +346,12 @@ func (e *ePub) Write() error {
return err return err
} }
if e.Dry { if e.options.Dry {
p := epubParts[0] p := epubParts[0]
fmt.Fprintf(os.Stderr, "TOC:\n - %s\n%s\n", e.Title, e.getTree(p.Images, true)) fmt.Fprintf(os.Stderr, "TOC:\n - %s\n%s\n", e.options.Title, e.getTree(p.Images, true))
if e.DryVerbose { if e.options.DryVerbose {
if e.Image.HasCover { if e.options.Image.HasCover {
fmt.Fprintf(os.Stderr, "Cover:\n%s\n", e.getTree([]*epubimage.Image{p.Cover}, false)) fmt.Fprintf(os.Stderr, "Cover:\n%s\n", e.getTree([]*epubimage.EPUBImage{p.Cover}, false))
} }
fmt.Fprintf(os.Stderr, "Files:\n%s\n", e.getTree(p.Images, false)) fmt.Fprintf(os.Stderr, "Files:\n%s\n", e.getTree(p.Images, false))
} }
@ -368,14 +369,14 @@ func (e *ePub) Write() error {
Description: "Writing Part", Description: "Writing Part",
CurrentJob: 2, CurrentJob: 2,
TotalJob: 2, TotalJob: 2,
Quiet: e.Quiet, Quiet: e.options.Quiet,
Json: e.Json, Json: e.options.Json,
}) })
e.computeViewPort(epubParts) e.computeViewPort(epubParts)
hasTitlePage := e.TitlePage == 1 || (e.TitlePage == 2 && totalParts > 1) hasTitlePage := e.options.TitlePage == 1 || (e.options.TitlePage == 2 && totalParts > 1)
for i, part := range epubParts { for i, part := range epubParts {
ext := filepath.Ext(e.Output) ext := filepath.Ext(e.options.Output)
suffix := "" suffix := ""
if totalParts > 1 { if totalParts > 1 {
fmtLen := len(fmt.Sprint(totalParts)) fmtLen := len(fmt.Sprint(totalParts))
@ -383,14 +384,14 @@ func (e *ePub) Write() error {
suffix = fmt.Sprintf(fmtPart, i+1, totalParts) suffix = fmt.Sprintf(fmtPart, i+1, totalParts)
} }
path := fmt.Sprintf("%s%s%s", e.Output[0:len(e.Output)-len(ext)], suffix, ext) path := fmt.Sprintf("%s%s%s", e.options.Output[0:len(e.options.Output)-len(ext)], suffix, ext)
wz, err := epubzip.New(path) wz, err := epubzip.New(path)
if err != nil { if err != nil {
return err return err
} }
defer wz.Close() defer wz.Close()
title := e.Title title := e.options.Title
if totalParts > 1 { if totalParts > 1 {
title = fmt.Sprintf("%s [%d/%d]", title, i+1, totalParts) title = fmt.Sprintf("%s [%d/%d]", title, i+1, totalParts)
} }
@ -401,19 +402,19 @@ func (e *ePub) Write() error {
{"OEBPS/content.opf", epubtemplates.Content(&epubtemplates.ContentOptions{ {"OEBPS/content.opf", epubtemplates.Content(&epubtemplates.ContentOptions{
Title: title, Title: title,
HasTitlePage: hasTitlePage, HasTitlePage: hasTitlePage,
UID: e.UID, UID: e.uid,
Author: e.Author, Author: e.options.Author,
Publisher: e.Publisher, Publisher: e.publisher,
UpdatedAt: e.UpdatedAt, UpdatedAt: e.updatedAt,
ImageOptions: e.Image, ImageOptions: e.options.Image,
Cover: part.Cover, Cover: part.Cover,
Images: part.Images, Images: part.Images,
Current: i + 1, Current: i + 1,
Total: totalParts, Total: totalParts,
})}, })},
{"OEBPS/toc.xhtml", epubtemplates.Toc(title, hasTitlePage, e.StripFirstDirectoryFromToc, part.Images)}, {"OEBPS/toc.xhtml", epubtemplates.Toc(title, hasTitlePage, e.options.StripFirstDirectoryFromToc, part.Images)},
{"OEBPS/Text/style.css", e.render(epubtemplates.Style, map[string]any{ {"OEBPS/Text/style.css", e.render(epubtemplates.Style, map[string]any{
"View": e.Image.View, "View": e.options.Image.View,
})}, })},
} }
@ -443,9 +444,9 @@ func (e *ePub) Write() error {
} }
// Double Page or Last Image that is not a double page // Double Page or Last Image that is not a double page
if !e.Image.View.PortraitOnly && if !e.options.Image.View.PortraitOnly &&
(img.DoublePage || (img.DoublePage ||
(!e.Image.KeepDoublePageIfSplitted && img.Part == 1) || (!e.options.Image.KeepDoublePageIfSplitted && img.Part == 1) ||
(img.Part == 0 && img == lastImage)) { (img.Part == 0 && img == lastImage)) {
if err := e.writeBlank(wz, img); err != nil { if err := e.writeBlank(wz, img); err != nil {
return err return err
@ -455,14 +456,14 @@ func (e *ePub) Write() error {
bar.Add(1) bar.Add(1)
} }
bar.Close() bar.Close()
if !e.Json { if !e.options.Json {
fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr)
} }
// display corrupted images // display corrupted images
hasError := false hasError := false
for pId, part := range epubParts { for pId, part := range epubParts {
if pId == 0 && e.Image.HasCover && part.Cover.Error != nil { if pId == 0 && e.options.Image.HasCover && part.Cover.Error != nil {
hasError = true hasError = true
fmt.Fprintf(os.Stderr, "Error on image %s: %v\n", filepath.Join(part.Cover.Path, part.Cover.Name), part.Cover.Error) fmt.Fprintf(os.Stderr, "Error on image %s: %v\n", filepath.Join(part.Cover.Path, part.Cover.Name), part.Cover.Error)
} }