Compare commits

...

12 Commits

Author SHA1 Message Date
f445a26993
update main script 2024-01-05 17:55:51 +01:00
0946696a8f
make public version for epub 2024-01-05 17:55:43 +01:00
5c1728dff8
update epub internal 2024-01-05 17:55:32 +01:00
4a12fe5715
make public epuboptions 2024-01-05 17:55:14 +01:00
f34ba5a37c
move epubzip 2024-01-05 17:54:41 +01:00
18a31c43f7
move epubtemplate 2024-01-05 17:54:25 +01:00
3a0f37d5f4
move epubtree 2024-01-05 17:54:15 +01:00
66b66a6b76
move epubprogress 2024-01-05 17:54:02 +01:00
9601e0a9b4
move epubimageprocessor 2024-01-05 17:53:45 +01:00
475af92ce1
move epubimagefilters 2024-01-05 17:53:18 +01:00
80427dca67
move epubimage 2024-01-05 17:53:04 +01:00
1250deb53f
simplify converter struct 2024-01-05 17:52:45 +01:00
34 changed files with 596 additions and 556 deletions

View File

@ -14,17 +14,14 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"regexp" "regexp"
"runtime" "runtime"
"strings" "strings"
"time" "time"
"github.com/celogeek/go-comic-converter/v2/internal/converter/options"
) )
type Converter struct { type converter struct {
Options *options.Options Options *converterOptions
Cmd *flag.FlagSet Cmd *flag.FlagSet
order []converterOrder order []converterOrder
@ -33,10 +30,10 @@ type Converter struct {
} }
// Create a new parser // Create a new parser
func New() *Converter { func New() *converter {
options := options.New() options := newOptions()
cmd := flag.NewFlagSet("go-comic-converter", flag.ExitOnError) cmd := flag.NewFlagSet("go-comic-converter", flag.ExitOnError)
conv := &Converter{ conv := &converter{
Options: options, Options: options,
Cmd: cmd, Cmd: cmd,
order: make([]converterOrder, 0), order: make([]converterOrder, 0),
@ -64,169 +61,76 @@ func New() *Converter {
} }
// Load default options (config + default) // Load default options (config + default)
func (c *Converter) LoadConfig() error { func (c *converter) LoadConfig() error {
return c.Options.LoadConfig() return c.Options.LoadConfig()
} }
// Create a new section of config
func (c *Converter) AddSection(section string) {
c.order = append(c.order, converterOrderSection{value: section})
}
// Add a string parameter
func (c *Converter) AddStringParam(p *string, name string, value string, usage string) {
c.Cmd.StringVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name, isString: true})
}
// Add an integer parameter
func (c *Converter) AddIntParam(p *int, name string, value int, usage string) {
c.Cmd.IntVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Add an float parameter
func (c *Converter) AddFloatParam(p *float64, name string, value float64, usage string) {
c.Cmd.Float64Var(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Add a boolean parameter
func (c *Converter) AddBoolParam(p *bool, name string, value bool, usage string) {
c.Cmd.BoolVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Initialize the parser with all section and parameter. // Initialize the parser with all section and parameter.
func (c *Converter) InitParse() { func (c *converter) InitParse() {
c.AddSection("Output") c.addSection("Output")
c.AddStringParam(&c.Options.Input, "input", "", "Source of comic to convert: directory, cbz, zip, cbr, rar, pdf") c.addStringParam(&c.Options.Input, "input", "", "Source of comic to convert: directory, cbz, zip, cbr, rar, pdf")
c.AddStringParam(&c.Options.Output, "output", "", "Output of the EPUB (directory or EPUB): (default [INPUT].epub)") c.addStringParam(&c.Options.Output, "output", "", "Output of the EPUB (directory or EPUB): (default [INPUT].epub)")
c.AddStringParam(&c.Options.Author, "author", "GO Comic Converter", "Author of the EPUB") c.addStringParam(&c.Options.Author, "author", "GO Comic Converter", "Author of the EPUB")
c.AddStringParam(&c.Options.Title, "title", "", "Title of the EPUB") c.addStringParam(&c.Options.Title, "title", "", "Title of the EPUB")
c.AddSection("Config") c.addSection("Config")
c.AddStringParam(&c.Options.Profile, "profile", c.Options.Profile, fmt.Sprintf("Profile to use: \n%s", c.Options.AvailableProfiles())) c.addStringParam(&c.Options.Profile, "profile", c.Options.Profile, fmt.Sprintf("Profile to use: \n%s", c.Options.AvailableProfiles()))
c.AddIntParam(&c.Options.Quality, "quality", c.Options.Quality, "Quality of the image") c.addIntParam(&c.Options.Quality, "quality", c.Options.Quality, "Quality of the image")
c.AddBoolParam(&c.Options.Grayscale, "grayscale", c.Options.Grayscale, "Grayscale image. Ideal for eInk devices.") c.addBoolParam(&c.Options.Grayscale, "grayscale", c.Options.Grayscale, "Grayscale image. Ideal for eInk devices.")
c.AddIntParam(&c.Options.GrayscaleMode, "grayscale-mode", c.Options.GrayscaleMode, "Grayscale Mode\n0 = normal\n1 = average\n2 = luminance") c.addIntParam(&c.Options.GrayscaleMode, "grayscale-mode", c.Options.GrayscaleMode, "Grayscale Mode\n0 = normal\n1 = average\n2 = luminance")
c.AddBoolParam(&c.Options.Crop, "crop", c.Options.Crop, "Crop images") c.addBoolParam(&c.Options.Crop, "crop", c.Options.Crop, "Crop images")
c.AddIntParam(&c.Options.CropRatioLeft, "crop-ratio-left", c.Options.CropRatioLeft, "Crop ratio left: ratio of pixels allow to be non blank while cutting on the left.") c.addIntParam(&c.Options.CropRatioLeft, "crop-ratio-left", c.Options.CropRatioLeft, "Crop ratio left: ratio of pixels allow to be non blank while cutting on the left.")
c.AddIntParam(&c.Options.CropRatioUp, "crop-ratio-up", c.Options.CropRatioUp, "Crop ratio up: ratio of pixels allow to be non blank while cutting on the top.") c.addIntParam(&c.Options.CropRatioUp, "crop-ratio-up", c.Options.CropRatioUp, "Crop ratio up: ratio of pixels allow to be non blank while cutting on the top.")
c.AddIntParam(&c.Options.CropRatioRight, "crop-ratio-right", c.Options.CropRatioRight, "Crop ratio right: ratio of pixels allow to be non blank while cutting on the right.") c.addIntParam(&c.Options.CropRatioRight, "crop-ratio-right", c.Options.CropRatioRight, "Crop ratio right: ratio of pixels allow to be non blank while cutting on the right.")
c.AddIntParam(&c.Options.CropRatioBottom, "crop-ratio-bottom", c.Options.CropRatioBottom, "Crop ratio bottom: ratio of pixels allow to be non blank while cutting on the bottom.") c.addIntParam(&c.Options.CropRatioBottom, "crop-ratio-bottom", c.Options.CropRatioBottom, "Crop ratio bottom: ratio of pixels allow to be non blank while cutting on the bottom.")
c.AddIntParam(&c.Options.Brightness, "brightness", c.Options.Brightness, "Brightness readjustement: between -100 and 100, > 0 lighter, < 0 darker") c.addIntParam(&c.Options.Brightness, "brightness", c.Options.Brightness, "Brightness readjustement: between -100 and 100, > 0 lighter, < 0 darker")
c.AddIntParam(&c.Options.Contrast, "contrast", c.Options.Contrast, "Contrast readjustement: between -100 and 100, > 0 more contrast, < 0 less contrast") c.addIntParam(&c.Options.Contrast, "contrast", c.Options.Contrast, "Contrast readjustement: between -100 and 100, > 0 more contrast, < 0 less contrast")
c.AddBoolParam(&c.Options.AutoContrast, "autocontrast", c.Options.AutoContrast, "Improve contrast automatically") c.addBoolParam(&c.Options.AutoContrast, "autocontrast", c.Options.AutoContrast, "Improve contrast automatically")
c.AddBoolParam(&c.Options.AutoRotate, "autorotate", c.Options.AutoRotate, "Auto Rotate page when width > height") c.addBoolParam(&c.Options.AutoRotate, "autorotate", c.Options.AutoRotate, "Auto Rotate page when width > height")
c.AddBoolParam(&c.Options.AutoSplitDoublePage, "autosplitdoublepage", c.Options.AutoSplitDoublePage, "Auto Split double page when width > height") c.addBoolParam(&c.Options.AutoSplitDoublePage, "autosplitdoublepage", c.Options.AutoSplitDoublePage, "Auto Split double page when width > height")
c.AddBoolParam(&c.Options.KeepDoublePageIfSplitted, "keepdoublepageifsplitted", c.Options.KeepDoublePageIfSplitted, "Keep the double page if splitted") c.addBoolParam(&c.Options.KeepDoublePageIfSplitted, "keepdoublepageifsplitted", c.Options.KeepDoublePageIfSplitted, "Keep the double page if splitted")
c.AddBoolParam(&c.Options.NoBlankImage, "noblankimage", c.Options.NoBlankImage, "Remove blank image") c.addBoolParam(&c.Options.NoBlankImage, "noblankimage", c.Options.NoBlankImage, "Remove blank image")
c.AddBoolParam(&c.Options.Manga, "manga", c.Options.Manga, "Manga mode (right to left)") c.addBoolParam(&c.Options.Manga, "manga", c.Options.Manga, "Manga mode (right to left)")
c.AddBoolParam(&c.Options.HasCover, "hascover", c.Options.HasCover, "Has cover. Indicate if your comic have a cover. The first page will be used as a cover and include after the title.") c.addBoolParam(&c.Options.HasCover, "hascover", c.Options.HasCover, "Has cover. Indicate if your comic have a cover. The first page will be used as a cover and include after the title.")
c.AddIntParam(&c.Options.LimitMb, "limitmb", c.Options.LimitMb, "Limit size of the EPUB: Default nolimit (0), Minimum 20") c.addIntParam(&c.Options.LimitMb, "limitmb", c.Options.LimitMb, "Limit size of the EPUB: Default nolimit (0), Minimum 20")
c.AddBoolParam(&c.Options.StripFirstDirectoryFromToc, "strip", c.Options.StripFirstDirectoryFromToc, "Strip first directory from the TOC if only 1") c.addBoolParam(&c.Options.StripFirstDirectoryFromToc, "strip", c.Options.StripFirstDirectoryFromToc, "Strip first directory from the TOC if only 1")
c.AddIntParam(&c.Options.SortPathMode, "sort", c.Options.SortPathMode, "Sort path mode\n0 = alpha for path and file\n1 = alphanum for path and alpha for file\n2 = alphanum for path and file") c.addIntParam(&c.Options.SortPathMode, "sort", c.Options.SortPathMode, "Sort path mode\n0 = alpha for path and file\n1 = alphanum for path and alpha for file\n2 = alphanum for path and file")
c.AddStringParam(&c.Options.ForegroundColor, "foreground-color", c.Options.ForegroundColor, "Foreground color in hexa format RGB. Black=000, White=FFF") c.addStringParam(&c.Options.ForegroundColor, "foreground-color", c.Options.ForegroundColor, "Foreground color in hexa format RGB. Black=000, White=FFF")
c.AddStringParam(&c.Options.BackgroundColor, "background-color", c.Options.BackgroundColor, "Background color in hexa format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777") c.addStringParam(&c.Options.BackgroundColor, "background-color", c.Options.BackgroundColor, "Background color in hexa format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777")
c.AddBoolParam(&c.Options.NoResize, "noresize", c.Options.NoResize, "Do not reduce image size if exceed device size") c.addBoolParam(&c.Options.NoResize, "noresize", c.Options.NoResize, "Do not reduce image size if exceed device size")
c.AddStringParam(&c.Options.Format, "format", c.Options.Format, "Format of output images: jpeg (lossy), png (lossless)") c.addStringParam(&c.Options.Format, "format", c.Options.Format, "Format of output images: jpeg (lossy), png (lossless)")
c.AddFloatParam(&c.Options.AspectRatio, "aspect-ratio", c.Options.AspectRatio, "Aspect ratio (height/width) of the output\n -1 = same as device\n 0 = same as source\n1.6 = amazon advice for kindle") c.addFloatParam(&c.Options.AspectRatio, "aspect-ratio", c.Options.AspectRatio, "Aspect ratio (height/width) of the output\n -1 = same as device\n 0 = same as source\n1.6 = amazon advice for kindle")
c.AddBoolParam(&c.Options.PortraitOnly, "portrait-only", c.Options.PortraitOnly, "Portrait only: force orientation to portrait only.") c.addBoolParam(&c.Options.PortraitOnly, "portrait-only", c.Options.PortraitOnly, "Portrait only: force orientation to portrait only.")
c.AddIntParam(&c.Options.TitlePage, "titlepage", c.Options.TitlePage, "Title page\n0 = never\n1 = always\n2 = only if epub is splitted") c.addIntParam(&c.Options.TitlePage, "titlepage", c.Options.TitlePage, "Title page\n0 = never\n1 = always\n2 = only if epub is splitted")
c.AddSection("Default config") c.addSection("Default config")
c.AddBoolParam(&c.Options.Show, "show", false, "Show your default parameters") c.addBoolParam(&c.Options.Show, "show", false, "Show your default parameters")
c.AddBoolParam(&c.Options.Save, "save", false, "Save your parameters as default") c.addBoolParam(&c.Options.Save, "save", false, "Save your parameters as default")
c.AddBoolParam(&c.Options.Reset, "reset", false, "Reset your parameters to default") c.addBoolParam(&c.Options.Reset, "reset", false, "Reset your parameters to default")
c.AddSection("Shortcut") c.addSection("Shortcut")
c.AddBoolParam(&c.Options.Auto, "auto", false, "Activate all automatic options") c.addBoolParam(&c.Options.Auto, "auto", false, "Activate all automatic options")
c.AddBoolParam(&c.Options.NoFilter, "nofilter", false, "Deactivate all filters") c.addBoolParam(&c.Options.NoFilter, "nofilter", false, "Deactivate all filters")
c.AddBoolParam(&c.Options.MaxQuality, "maxquality", false, "Max quality: color png + noresize") c.addBoolParam(&c.Options.MaxQuality, "maxquality", false, "Max quality: color png + noresize")
c.AddBoolParam(&c.Options.BestQuality, "bestquality", false, "Max quality: color jpg q100 + noresize") c.addBoolParam(&c.Options.BestQuality, "bestquality", false, "Max quality: color jpg q100 + noresize")
c.AddBoolParam(&c.Options.GreatQuality, "greatquality", false, "Max quality: grayscale jpg q90 + noresize") c.addBoolParam(&c.Options.GreatQuality, "greatquality", false, "Max quality: grayscale jpg q90 + noresize")
c.AddBoolParam(&c.Options.GoodQuality, "goodquality", false, "Max quality: grayscale jpg q90") c.addBoolParam(&c.Options.GoodQuality, "goodquality", false, "Max quality: grayscale jpg q90")
c.AddSection("Compatibility") c.addSection("Compatibility")
c.AddBoolParam(&c.Options.AppleBookCompatibility, "applebookcompatibility", c.Options.AppleBookCompatibility, "Apple book compatibility") c.addBoolParam(&c.Options.AppleBookCompatibility, "applebookcompatibility", c.Options.AppleBookCompatibility, "Apple book compatibility")
c.AddSection("Other") c.addSection("Other")
c.AddIntParam(&c.Options.Workers, "workers", runtime.NumCPU(), "Number of workers") c.addIntParam(&c.Options.Workers, "workers", runtime.NumCPU(), "Number of workers")
c.AddBoolParam(&c.Options.Dry, "dry", false, "Dry run to show all options") c.addBoolParam(&c.Options.Dry, "dry", false, "Dry run to show all options")
c.AddBoolParam(&c.Options.DryVerbose, "dry-verbose", false, "Display also sorted files after the TOC") c.addBoolParam(&c.Options.DryVerbose, "dry-verbose", false, "Display also sorted files after the TOC")
c.AddBoolParam(&c.Options.Quiet, "quiet", false, "Disable progress bar") c.addBoolParam(&c.Options.Quiet, "quiet", false, "Disable progress bar")
c.AddBoolParam(&c.Options.Json, "json", false, "Output progression and information in Json format") c.addBoolParam(&c.Options.Json, "json", false, "Output progression and information in Json format")
c.AddBoolParam(&c.Options.Version, "version", false, "Show current and available version") c.addBoolParam(&c.Options.Version, "version", false, "Show current and available version")
c.AddBoolParam(&c.Options.Help, "help", false, "Show this help message") c.addBoolParam(&c.Options.Help, "help", false, "Show this help message")
}
// Customize version of FlagSet.PrintDefaults
func (c *Converter) Usage(isString bool, f *flag.Flag) string {
var b strings.Builder
fmt.Fprintf(&b, " -%s", f.Name) // Two spaces before -; see next two comments.
name, usage := flag.UnquoteUsage(f)
if len(name) > 0 {
b.WriteString(" ")
b.WriteString(name)
}
// Print the default value only if it differs to the zero value
// for this flag type.
if isZero, err := c.isZeroValue(f, f.DefValue); err != nil {
c.isZeroValueErrs = append(c.isZeroValueErrs, err)
} else if !isZero {
if isString {
fmt.Fprintf(&b, " (default %q)", f.DefValue)
} else {
fmt.Fprintf(&b, " (default %v)", f.DefValue)
}
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if b.Len() <= 4 { // space, space, '-', 'x'.
b.WriteString("\t")
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
b.WriteString("\n \t")
}
b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
return b.String()
}
// Taken from flag package as it is private and needed for usage.
//
// isZeroValue determines whether the string represents the zero
// value for a flag.
func (c *Converter) isZeroValue(f *flag.Flag, value string) (ok bool, err error) {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(f.Value)
var z reflect.Value
if typ.Kind() == reflect.Pointer {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
// Catch panics calling the String method, which shouldn't prevent the
// usage message from being printed, but that we should report to the
// user so that they know to fix their code.
defer func() {
if e := recover(); e != nil {
if typ.Kind() == reflect.Pointer {
typ = typ.Elem()
}
err = fmt.Errorf("panic calling String method on zero %v for flag %s: %v", typ, f.Name, e)
}
}()
return value == z.Interface().(flag.Value).String(), nil
} }
// Parse all parameters // Parse all parameters
func (c *Converter) Parse() { func (c *converter) Parse() {
c.Cmd.Parse(os.Args[1:]) c.Cmd.Parse(os.Args[1:])
if c.Options.Help { if c.Options.Help {
c.Cmd.Usage() c.Cmd.Usage()
@ -277,7 +181,7 @@ func (c *Converter) Parse() {
} }
// Check parameters // Check parameters
func (c *Converter) Validate() error { func (c *converter) Validate() error {
// Check input // Check input
if c.Options.Input == "" { if c.Options.Input == "" {
return errors.New("missing input") return errors.New("missing input")
@ -393,14 +297,49 @@ func (c *Converter) Validate() error {
return nil return nil
} }
// Customize version of FlagSet.PrintDefaults
func (c *converter) Usage(isString bool, f *flag.Flag) string {
var b strings.Builder
fmt.Fprintf(&b, " -%s", f.Name) // Two spaces before -; see next two comments.
name, usage := flag.UnquoteUsage(f)
if len(name) > 0 {
b.WriteString(" ")
b.WriteString(name)
}
// Print the default value only if it differs to the zero value
// for this flag type.
if isZero, err := c.isZeroValue(f, f.DefValue); err != nil {
c.isZeroValueErrs = append(c.isZeroValueErrs, err)
} else if !isZero {
if isString {
fmt.Fprintf(&b, " (default %q)", f.DefValue)
} else {
fmt.Fprintf(&b, " (default %v)", f.DefValue)
}
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if b.Len() <= 4 { // space, space, '-', 'x'.
b.WriteString("\t")
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
b.WriteString("\n \t")
}
b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
return b.String()
}
// Helper to show usage, err and exit 1 // Helper to show usage, err and exit 1
func (c *Converter) Fatal(err error) { func (c *converter) Fatal(err error) {
c.Cmd.Usage() c.Cmd.Usage()
fmt.Fprintf(os.Stderr, "\nError: %s\n", err) fmt.Fprintf(os.Stderr, "\nError: %s\n", err)
os.Exit(1) os.Exit(1)
} }
func (c *Converter) Stats() { func (c *converter) Stats() {
// Display elapse time and memory usage // Display elapse time and memory usage
elapse := time.Since(c.startAt).Round(time.Millisecond) elapse := time.Since(c.startAt).Round(time.Millisecond)
var mem runtime.MemStats var mem runtime.MemStats

View File

@ -0,0 +1,65 @@
package converter
import (
"flag"
"fmt"
"reflect"
)
// Create a new section of config
func (c *converter) addSection(section string) {
c.order = append(c.order, converterOrderSection{value: section})
}
// Add a string parameter
func (c *converter) addStringParam(p *string, name string, value string, usage string) {
c.Cmd.StringVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name, isString: true})
}
// Add an integer parameter
func (c *converter) addIntParam(p *int, name string, value int, usage string) {
c.Cmd.IntVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Add an float parameter
func (c *converter) addFloatParam(p *float64, name string, value float64, usage string) {
c.Cmd.Float64Var(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Add a boolean parameter
func (c *converter) addBoolParam(p *bool, name string, value bool, usage string) {
c.Cmd.BoolVar(p, name, value, usage)
c.order = append(c.order, converterOrderName{value: name})
}
// Taken from flag package as it is private and needed for usage.
//
// isZeroValue determines whether the string represents the zero
// value for a flag.
func (c *converter) isZeroValue(f *flag.Flag, value string) (ok bool, err error) {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(f.Value)
var z reflect.Value
if typ.Kind() == reflect.Pointer {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
// Catch panics calling the String method, which shouldn't prevent the
// usage message from being printed, but that we should report to the
// user so that they know to fix their code.
defer func() {
if e := recover(); e != nil {
if typ.Kind() == reflect.Pointer {
typ = typ.Elem()
}
err = fmt.Errorf("panic calling String method on zero %v for flag %s: %v", typ, f.Name, e)
}
}()
return value == z.Interface().(flag.Value).String(), nil
}

View File

@ -1,7 +1,7 @@
/* /*
Manage options with default value from config. Manage options with default value from config.
*/ */
package options package converter
import ( import (
"encoding/json" "encoding/json"
@ -10,11 +10,10 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/celogeek/go-comic-converter/v2/internal/converter/profiles"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
type Options struct { type converterOptions struct {
// Output // Output
Input string `yaml:"-"` Input string `yaml:"-"`
Output string `yaml:"-"` Output string `yaml:"-"`
@ -75,12 +74,12 @@ type Options struct {
Help bool `yaml:"-"` Help bool `yaml:"-"`
// Internal // Internal
profiles profiles.Profiles profiles converterProfiles
} }
// Initialize default options. // Initialize default options.
func New() *Options { func newOptions() *converterOptions {
return &Options{ return &converterOptions{
Profile: "SR", Profile: "SR",
Quality: 85, Quality: 85,
Grayscale: true, Grayscale: true,
@ -97,15 +96,15 @@ func New() *Options {
BackgroundColor: "FFF", BackgroundColor: "FFF",
Format: "jpeg", Format: "jpeg",
TitlePage: 1, TitlePage: 1,
profiles: profiles.New(), profiles: newProfiles(),
} }
} }
func (o *Options) Header() string { func (o *converterOptions) Header() string {
return "Go Comic Converter\n\nOptions:" return "Go Comic Converter\n\nOptions:"
} }
func (o *Options) String() string { func (o *converterOptions) String() string {
var b strings.Builder var b strings.Builder
b.WriteString(o.Header()) b.WriteString(o.Header())
for _, v := range []struct { for _, v := range []struct {
@ -125,7 +124,7 @@ func (o *Options) String() string {
return b.String() return b.String()
} }
func (o *Options) MarshalJSON() ([]byte, error) { func (o *converterOptions) MarshalJSON() ([]byte, error) {
out := map[string]any{ out := map[string]any{
"input": o.Input, "input": o.Input,
"output": o.Output, "output": o.Output,
@ -186,13 +185,13 @@ func (o *Options) MarshalJSON() ([]byte, error) {
} }
// Config file: ~/.go-comic-converter.yaml // Config file: ~/.go-comic-converter.yaml
func (o *Options) FileName() string { func (o *converterOptions) FileName() string {
home, _ := os.UserHomeDir() home, _ := os.UserHomeDir()
return filepath.Join(home, ".go-comic-converter.yaml") return filepath.Join(home, ".go-comic-converter.yaml")
} }
// Load config files // Load config files
func (o *Options) LoadConfig() error { func (o *converterOptions) LoadConfig() error {
f, err := os.Open(o.FileName()) f, err := os.Open(o.FileName())
if err != nil { if err != nil {
return nil return nil
@ -207,7 +206,7 @@ func (o *Options) LoadConfig() error {
} }
// Get current settings for fields that can be saved // Get current settings for fields that can be saved
func (o *Options) ShowConfig() string { func (o *converterOptions) ShowConfig() string {
var profileDesc string var profileDesc string
profile := o.GetProfile() profile := o.GetProfile()
if profile != nil { if profile != nil {
@ -296,13 +295,13 @@ func (o *Options) ShowConfig() string {
} }
// reset all settings to default value // reset all settings to default value
func (o *Options) ResetConfig() error { func (o *converterOptions) ResetConfig() error {
New().SaveConfig() newOptions().SaveConfig()
return o.LoadConfig() return o.LoadConfig()
} }
// save all current settings as futur default value // save all current settings as futur default value
func (o *Options) SaveConfig() error { func (o *converterOptions) SaveConfig() error {
f, err := os.Create(o.FileName()) f, err := os.Create(o.FileName())
if err != nil { if err != nil {
return err return err
@ -312,11 +311,11 @@ func (o *Options) SaveConfig() error {
} }
// shortcut to get current profile // shortcut to get current profile
func (o *Options) GetProfile() *profiles.Profile { func (o *converterOptions) GetProfile() *converterProfile {
return o.profiles.Get(o.Profile) return o.profiles.Get(o.Profile)
} }
// all available profiles // all available profiles
func (o *Options) AvailableProfiles() string { func (o *converterOptions) AvailableProfiles() string {
return o.profiles.String() return o.profiles.String()
} }

View File

@ -1,25 +1,25 @@
/* /*
Manage supported profiles for go-comic-converter. Manage supported profiles for go-comic-converter.
*/ */
package profiles package converter
import ( import (
"fmt" "fmt"
"strings" "strings"
) )
type Profile struct { type converterProfile struct {
Code string `json:"code"` Code string `json:"code"`
Description string `json:"description"` Description string `json:"description"`
Width int `json:"width"` Width int `json:"width"`
Height int `json:"height"` Height int `json:"height"`
} }
type Profiles []Profile type converterProfiles []*converterProfile
// Initialize list of all supported profiles. // Initialize list of all supported profiles.
func New() Profiles { func newProfiles() converterProfiles {
return []Profile{ return []*converterProfile{
// High Resolution for Tablette // High Resolution for Tablette
{"HR", "High Resolution", 2400, 3840}, {"HR", "High Resolution", 2400, 3840},
{"SR", "Standard Resolution", 1200, 1920}, {"SR", "Standard Resolution", 1200, 1920},
@ -55,7 +55,7 @@ func New() Profiles {
} }
} }
func (p Profiles) String() string { func (p converterProfiles) String() string {
s := make([]string, 0) s := make([]string, 0)
for _, v := range p { for _, v := range p {
s = append(s, fmt.Sprintf( s = append(s, fmt.Sprintf(
@ -69,10 +69,10 @@ func (p Profiles) String() string {
} }
// Lookup profile by code // Lookup profile by code
func (p Profiles) Get(name string) *Profile { func (p converterProfiles) Get(name string) *converterProfile {
for _, profile := range p { for _, profile := range p {
if profile.Code == name { if profile.Code == name {
return &profile return profile
} }
} }
return nil return nil

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)
} }

View File

@ -1,23 +0,0 @@
/*
Templates use to create xml files of the EPUB.
*/
package epubtemplates
import _ "embed"
var (
//go:embed "epub_templates_container.xml.tmpl"
Container string
//go:embed "epub_templates_applebooks.xml.tmpl"
AppleBooks string
//go:embed "epub_templates_style.css.tmpl"
Style string
//go:embed "epub_templates_text.xhtml.tmpl"
Text string
//go:embed "epub_templates_blank.xhtml.tmpl"
Blank string
)

View File

@ -1,100 +0,0 @@
package epubzip
import (
"archive/zip"
"image"
"os"
"sync"
)
type EPUBZipStorageImageWriter struct {
fh *os.File
fz *zip.Writer
format string
mut *sync.Mutex
}
func NewEPUBZipStorageImageWriter(filename string, format string) (*EPUBZipStorageImageWriter, error) {
fh, err := os.Create(filename)
if err != nil {
return nil, err
}
fz := zip.NewWriter(fh)
return &EPUBZipStorageImageWriter{fh, fz, format, &sync.Mutex{}}, nil
}
func (e *EPUBZipStorageImageWriter) Close() error {
if err := e.fz.Close(); err != nil {
e.fh.Close()
return err
}
return e.fh.Close()
}
func (e *EPUBZipStorageImageWriter) Add(filename string, img image.Image, quality int) error {
zipImage, err := CompressImage(filename, e.format, img, quality)
if err != nil {
return err
}
e.mut.Lock()
defer e.mut.Unlock()
fh, err := e.fz.CreateRaw(zipImage.Header)
if err != nil {
return err
}
_, err = fh.Write(zipImage.Data)
if err != nil {
return err
}
return nil
}
type EPUBZipStorageImageReader struct {
filename string
fh *os.File
fz *zip.Reader
files map[string]*zip.File
}
func NewEPUBZipStorageImageReader(filename string) (*EPUBZipStorageImageReader, error) {
fh, err := os.Open(filename)
if err != nil {
return nil, err
}
s, err := fh.Stat()
if err != nil {
return nil, err
}
fz, err := zip.NewReader(fh, s.Size())
if err != nil {
return nil, err
}
files := map[string]*zip.File{}
for _, z := range fz.File {
files[z.Name] = z
}
return &EPUBZipStorageImageReader{filename, fh, fz, files}, nil
}
func (e *EPUBZipStorageImageReader) Get(filename string) *zip.File {
return e.files[filename]
}
func (e *EPUBZipStorageImageReader) Size(filename string) uint64 {
img := e.Get(filename)
if img != nil {
return img.CompressedSize64 + 30 + uint64(len(img.Name))
}
return 0
}
func (e *EPUBZipStorageImageReader) Close() error {
return e.fh.Close()
}
func (e *EPUBZipStorageImageReader) Remove() error {
return os.Remove(e.filename)
}

View File

@ -9,7 +9,7 @@ import (
"strings" "strings"
) )
type Image struct { type EPUBImage struct {
Id int Id int
Part int Part int
Raw image.Image Raw image.Image
@ -27,47 +27,47 @@ type Image struct {
} }
// key name of the blank plage after the image // key name of the blank plage after the image
func (i *Image) SpaceKey() string { func (i *EPUBImage) SpaceKey() string {
return fmt.Sprintf("space_%d", i.Id) return fmt.Sprintf("space_%d", i.Id)
} }
// path of the blank page // path of the blank page
func (i *Image) SpacePath() string { func (i *EPUBImage) SpacePath() string {
return fmt.Sprintf("Text/%s.xhtml", i.SpaceKey()) return fmt.Sprintf("Text/%s.xhtml", i.SpaceKey())
} }
// path of the blank page into the EPUB // path of the blank page into the EPUB
func (i *Image) EPUBSpacePath() string { func (i *EPUBImage) EPUBSpacePath() string {
return fmt.Sprintf("OEBPS/%s", i.SpacePath()) return fmt.Sprintf("OEBPS/%s", i.SpacePath())
} }
// key for page // key for page
func (i *Image) PageKey() string { func (i *EPUBImage) PageKey() string {
return fmt.Sprintf("page_%d_p%d", i.Id, i.Part) return fmt.Sprintf("page_%d_p%d", i.Id, i.Part)
} }
// page path linked to the image // page path linked to the image
func (i *Image) PagePath() string { func (i *EPUBImage) PagePath() string {
return fmt.Sprintf("Text/%s.xhtml", i.PageKey()) return fmt.Sprintf("Text/%s.xhtml", i.PageKey())
} }
// page path into the EPUB // page path into the EPUB
func (i *Image) EPUBPagePath() string { func (i *EPUBImage) EPUBPagePath() string {
return fmt.Sprintf("OEBPS/%s", i.PagePath()) return fmt.Sprintf("OEBPS/%s", i.PagePath())
} }
// key for image // key for image
func (i *Image) ImgKey() string { func (i *EPUBImage) ImgKey() string {
return fmt.Sprintf("img_%d_p%d", i.Id, i.Part) return fmt.Sprintf("img_%d_p%d", i.Id, i.Part)
} }
// image path // image path
func (i *Image) ImgPath() string { func (i *EPUBImage) ImgPath() string {
return fmt.Sprintf("Images/%s.%s", i.ImgKey(), i.Format) return fmt.Sprintf("Images/%s.%s", i.ImgKey(), i.Format)
} }
// image path into the EPUB // image path into the EPUB
func (i *Image) EPUBImgPath() string { func (i *EPUBImage) EPUBImgPath() string {
return fmt.Sprintf("OEBPS/%s", i.ImgPath()) return fmt.Sprintf("OEBPS/%s", i.ImgPath())
} }
@ -75,7 +75,7 @@ func (i *Image) EPUBImgPath() string {
// //
// center by default. // center by default.
// align to left or right if it's part of the splitted double page. // align to left or right if it's part of the splitted double page.
func (i *Image) ImgStyle(viewWidth, viewHeight int, align string) string { func (i *EPUBImage) ImgStyle(viewWidth, viewHeight int, align string) string {
relWidth, relHeight := i.RelSize(viewWidth, viewHeight) relWidth, relHeight := i.RelSize(viewWidth, viewHeight)
marginW, marginH := float64(viewWidth-relWidth)/2, float64(viewHeight-relHeight)/2 marginW, marginH := float64(viewWidth-relWidth)/2, float64(viewHeight-relHeight)/2
@ -100,7 +100,7 @@ func (i *Image) ImgStyle(viewWidth, viewHeight int, align string) string {
return strings.Join(style, "; ") return strings.Join(style, "; ")
} }
func (i *Image) RelSize(viewWidth, viewHeight int) (relWidth, relHeight int) { func (i *EPUBImage) RelSize(viewWidth, viewHeight int) (relWidth, relHeight int) {
w, h := viewWidth, viewHeight w, h := viewWidth, viewHeight
srcw, srch := i.Width, i.Height srcw, srch := i.Width, i.Height

View File

@ -6,55 +6,54 @@ package epubimageprocessor
import ( import (
"fmt" "fmt"
"image" "image"
"image/color"
"image/draw" "image/draw"
"os" "os"
"sync" "sync"
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image" "github.com/celogeek/go-comic-converter/v2/internal/epubimage"
epubimagefilters "github.com/celogeek/go-comic-converter/v2/internal/epub/imagefilters" "github.com/celogeek/go-comic-converter/v2/internal/epubimagefilters"
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/epubzip"
epubzip "github.com/celogeek/go-comic-converter/v2/internal/epub/zip" "github.com/celogeek/go-comic-converter/v2/pkg/epuboptions"
"github.com/disintegration/gift" "github.com/disintegration/gift"
) )
type EPUBImageProcessor struct { type EPUBImageProcessor struct {
*epuboptions.Options options *epuboptions.EPUBOptions
} }
func New(o *epuboptions.Options) *EPUBImageProcessor { func New(o *epuboptions.EPUBOptions) *EPUBImageProcessor {
return &EPUBImageProcessor{o} return &EPUBImageProcessor{o}
} }
// extract and convert images // extract and convert images
func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) { func (e *EPUBImageProcessor) Load() (images []*epubimage.EPUBImage, err error) {
images = make([]*epubimage.Image, 0) images = make([]*epubimage.EPUBImage, 0)
imageCount, imageInput, err := e.load() imageCount, imageInput, err := e.load()
if err != nil { if err != nil {
return nil, err return nil, err
} }
// dry run, skip convertion // dry run, skip convertion
if e.Dry { if e.options.Dry {
for img := range imageInput { for img := range imageInput {
images = append(images, &epubimage.Image{ images = append(images, &epubimage.EPUBImage{
Id: img.Id, Id: img.Id,
Path: img.Path, Path: img.Path,
Name: img.Name, Name: img.Name,
Format: e.Image.Format, Format: e.options.Image.Format,
}) })
} }
return images, nil return images, nil
} }
imageOutput := make(chan *epubimage.Image) imageOutput := make(chan *epubimage.EPUBImage)
// processing // processing
bar := epubprogress.New(epubprogress.Options{ bar := epubprogress.New(epubprogress.Options{
Quiet: e.Quiet, Quiet: e.options.Quiet,
Json: e.Json, Json: e.options.Json,
Max: imageCount, Max: imageCount,
Description: "Processing", Description: "Processing",
CurrentJob: 1, CurrentJob: 1,
@ -62,17 +61,17 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
}) })
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
imgStorage, err := epubzip.NewEPUBZipStorageImageWriter(e.ImgStorage(), e.Image.Format) imgStorage, err := epubzip.NewImageWriter(e.options.Temp(), e.options.Image.Format)
if err != nil { if err != nil {
bar.Close() bar.Close()
return nil, err return nil, err
} }
wr := 50 wr := 50
if e.Image.Format == "png" { if e.options.Image.Format == "png" {
wr = 100 wr = 100
} }
for i := 0; i < e.WorkersRatio(wr); i++ { for i := 0; i < e.options.WorkersRatio(wr); i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
@ -86,7 +85,7 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
raw = dst raw = dst
} }
img := &epubimage.Image{ img := &epubimage.EPUBImage{
Id: input.Id, Id: input.Id,
Part: part, Part: part,
Raw: raw, Raw: raw,
@ -97,7 +96,7 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
DoublePage: part == 0 && src.Bounds().Dx() > src.Bounds().Dy(), DoublePage: part == 0 && src.Bounds().Dx() > src.Bounds().Dy(),
Path: input.Path, Path: input.Path,
Name: input.Name, Name: input.Name,
Format: e.Image.Format, Format: e.options.Image.Format,
OriginalAspectRatio: float64(src.Bounds().Dy()) / float64(src.Bounds().Dx()), OriginalAspectRatio: float64(src.Bounds().Dy()) / float64(src.Bounds().Dx()),
Error: input.Error, Error: input.Error,
} }
@ -105,12 +104,12 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
// do not keep double page if requested // do not keep double page if requested
if !img.IsCover && if !img.IsCover &&
img.DoublePage && img.DoublePage &&
e.Options.Image.AutoSplitDoublePage && e.options.Image.AutoSplitDoublePage &&
!e.Options.Image.KeepDoublePageIfSplitted { !e.options.Image.KeepDoublePageIfSplitted {
continue continue
} }
if err = imgStorage.Add(img.EPUBImgPath(), dst, e.Image.Quality); err != nil { if err = imgStorage.Add(img.EPUBImgPath(), dst, e.options.Image.Quality); err != nil {
bar.Close() bar.Close()
fmt.Fprintf(os.Stderr, "error with %s: %s", input.Name, err) fmt.Fprintf(os.Stderr, "error with %s: %s", input.Name, err)
os.Exit(1) os.Exit(1)
@ -131,7 +130,7 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
if img.Part == 0 { if img.Part == 0 {
bar.Add(1) bar.Add(1)
} }
if e.Image.NoBlankImage && img.IsBlank { if e.options.Image.NoBlankImage && img.IsBlank {
continue continue
} }
images = append(images, img) images = append(images, img)
@ -146,7 +145,7 @@ func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
} }
func (e *EPUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw.Image { func (e *EPUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw.Image {
if e.Options.Image.GrayScale { if e.options.Image.GrayScale {
return image.NewGray(r) return image.NewGray(r)
} }
@ -183,13 +182,13 @@ func (e *EPUBImageProcessor) transformImage(src image.Image, srcId int) []image.
var images []image.Image var images []image.Image
// Lookup for margin if crop is enable or if we want to remove blank image // Lookup for margin if crop is enable or if we want to remove blank image
if e.Image.Crop.Enabled || e.Image.NoBlankImage { if e.options.Image.Crop.Enabled || e.options.Image.NoBlankImage {
f := epubimagefilters.AutoCrop( f := epubimagefilters.AutoCrop(
src, src,
e.Image.Crop.Left, e.options.Image.Crop.Left,
e.Image.Crop.Up, e.options.Image.Crop.Up,
e.Image.Crop.Right, e.options.Image.Crop.Right,
e.Image.Crop.Bottom, e.options.Image.Crop.Bottom,
) )
// detect if blank image // detect if blank image
@ -197,42 +196,42 @@ func (e *EPUBImageProcessor) transformImage(src image.Image, srcId int) []image.
isBlank := size.Dx() == 0 && size.Dy() == 0 isBlank := size.Dx() == 0 && size.Dy() == 0
// crop is enable or if blank image with noblankimage options // crop is enable or if blank image with noblankimage options
if e.Image.Crop.Enabled || (e.Image.NoBlankImage && isBlank) { if e.options.Image.Crop.Enabled || (e.options.Image.NoBlankImage && isBlank) {
filters = append(filters, f) filters = append(filters, f)
splitFilters = append(splitFilters, f) splitFilters = append(splitFilters, f)
} }
} }
if e.Image.AutoRotate && src.Bounds().Dx() > src.Bounds().Dy() { if e.options.Image.AutoRotate && src.Bounds().Dx() > src.Bounds().Dy() {
filters = append(filters, gift.Rotate90()) filters = append(filters, gift.Rotate90())
} }
if e.Image.AutoContrast { if e.options.Image.AutoContrast {
f := epubimagefilters.AutoContrast() f := epubimagefilters.AutoContrast()
filters = append(filters, f) filters = append(filters, f)
splitFilters = append(splitFilters, f) splitFilters = append(splitFilters, f)
} }
if e.Image.Contrast != 0 { if e.options.Image.Contrast != 0 {
f := gift.Contrast(float32(e.Image.Contrast)) f := gift.Contrast(float32(e.options.Image.Contrast))
filters = append(filters, f) filters = append(filters, f)
splitFilters = append(splitFilters, f) splitFilters = append(splitFilters, f)
} }
if e.Image.Brightness != 0 { if e.options.Image.Brightness != 0 {
f := gift.Brightness(float32(e.Image.Brightness)) f := gift.Brightness(float32(e.options.Image.Brightness))
filters = append(filters, f) filters = append(filters, f)
splitFilters = append(splitFilters, f) splitFilters = append(splitFilters, f)
} }
if e.Image.Resize { if e.options.Image.Resize {
f := gift.ResizeToFit(e.Image.View.Width, e.Image.View.Height, gift.LanczosResampling) f := gift.ResizeToFit(e.options.Image.View.Width, e.options.Image.View.Height, gift.LanczosResampling)
filters = append(filters, f) filters = append(filters, f)
} }
if e.Image.GrayScale { if e.options.Image.GrayScale {
var f gift.Filter var f gift.Filter
switch e.Image.GrayScaleMode { switch e.options.Image.GrayScaleMode {
case 1: // average case 1: // average
f = gift.ColorFunc(func(r0, g0, b0, a0 float32) (r float32, g float32, b float32, a float32) { f = gift.ColorFunc(func(r0, g0, b0, a0 float32) (r float32, g float32, b float32, a float32) {
y := (r0 + g0 + b0) / 3 y := (r0 + g0 + b0) / 3
@ -261,7 +260,7 @@ func (e *EPUBImageProcessor) transformImage(src image.Image, srcId int) []image.
} }
// auto split off // auto split off
if !e.Image.AutoSplitDoublePage { if !e.options.Image.AutoSplitDoublePage {
return images return images
} }
@ -271,16 +270,16 @@ func (e *EPUBImageProcessor) transformImage(src image.Image, srcId int) []image.
} }
// cover // cover
if e.Image.HasCover && srcId == 0 { if e.options.Image.HasCover && srcId == 0 {
return images return images
} }
// convert double page // convert double page
for _, b := range []bool{e.Image.Manga, !e.Image.Manga} { for _, b := range []bool{e.options.Image.Manga, !e.options.Image.Manga} {
g := gift.New(splitFilters...) g := gift.New(splitFilters...)
g.Add(epubimagefilters.CropSplitDoublePage(b)) g.Add(epubimagefilters.CropSplitDoublePage(b))
if e.Image.Resize { if e.options.Image.Resize {
g.Add(gift.ResizeToFit(e.Image.View.Width, e.Image.View.Height, gift.LanczosResampling)) g.Add(gift.ResizeToFit(e.options.Image.View.Width, e.options.Image.View.Height, gift.LanczosResampling))
} }
dst := e.createImage(src, g.Bounds(src.Bounds())) dst := e.createImage(src, g.Bounds(src.Bounds()))
g.Draw(dst, src) g.Draw(dst, src)
@ -289,55 +288,3 @@ func (e *EPUBImageProcessor) transformImage(src image.Image, srcId int) []image.
return images return images
} }
type CoverTitleDataOptions struct {
Src image.Image
Name string
Text string
Align string
PctWidth int
PctMargin int
MaxFontSize int
BorderSize int
}
func (e *EPUBImageProcessor) Cover16LevelOfGray(bounds image.Rectangle) draw.Image {
return image.NewPaletted(bounds, color.Palette{
color.Gray{0x00},
color.Gray{0x11},
color.Gray{0x22},
color.Gray{0x33},
color.Gray{0x44},
color.Gray{0x55},
color.Gray{0x66},
color.Gray{0x77},
color.Gray{0x88},
color.Gray{0x99},
color.Gray{0xAA},
color.Gray{0xBB},
color.Gray{0xCC},
color.Gray{0xDD},
color.Gray{0xEE},
color.Gray{0xFF},
})
}
// create a title page with the cover
func (e *EPUBImageProcessor) CoverTitleData(o *CoverTitleDataOptions) (*epubzip.ZipImage, error) {
// Create a blur version of the cover
g := gift.New(epubimagefilters.CoverTitle(o.Text, o.Align, o.PctWidth, o.PctMargin, o.MaxFontSize, o.BorderSize))
var dst draw.Image
if o.Name == "cover" && e.Image.GrayScale {
dst = e.Cover16LevelOfGray(o.Src.Bounds())
} else {
dst = e.createImage(o.Src, g.Bounds(o.Src.Bounds()))
}
g.Draw(dst, o.Src)
return epubzip.CompressImage(
fmt.Sprintf("OEBPS/Images/%s.%s", o.Name, e.Image.Format),
e.Image.Format,
dst,
e.Image.Quality,
)
}

View File

@ -0,0 +1,61 @@
package epubimageprocessor
import (
"fmt"
"image"
"image/color"
"image/draw"
"github.com/celogeek/go-comic-converter/v2/internal/epubimagefilters"
"github.com/celogeek/go-comic-converter/v2/internal/epubzip"
"github.com/disintegration/gift"
)
type CoverTitleDataOptions struct {
Src image.Image
Name string
Text string
Align string
PctWidth int
PctMargin int
MaxFontSize int
BorderSize int
}
// create a title page with the cover
func (e *EPUBImageProcessor) CoverTitleData(o *CoverTitleDataOptions) (*epubzip.EPUBZipImage, error) {
// Create a blur version of the cover
g := gift.New(epubimagefilters.CoverTitle(o.Text, o.Align, o.PctWidth, o.PctMargin, o.MaxFontSize, o.BorderSize))
var dst draw.Image
if o.Name == "cover" && e.options.Image.GrayScale {
// 16 shade of gray
dst = image.NewPaletted(o.Src.Bounds(), color.Palette{
color.Gray{0x00},
color.Gray{0x11},
color.Gray{0x22},
color.Gray{0x33},
color.Gray{0x44},
color.Gray{0x55},
color.Gray{0x66},
color.Gray{0x77},
color.Gray{0x88},
color.Gray{0x99},
color.Gray{0xAA},
color.Gray{0xBB},
color.Gray{0xCC},
color.Gray{0xDD},
color.Gray{0xEE},
color.Gray{0xFF},
})
} else {
dst = e.createImage(o.Src, g.Bounds(o.Src.Bounds()))
}
g.Draw(dst, o.Src)
return epubzip.CompressImage(
fmt.Sprintf("OEBPS/Images/%s.%s", o.Name, e.options.Image.Format),
e.options.Image.Format,
dst,
e.options.Image.Quality,
)
}

View File

@ -51,7 +51,7 @@ func (e *EPUBImageProcessor) isSupportedImage(path string) bool {
// Load images from input // Load images from input
func (e *EPUBImageProcessor) load() (totalImages int, output chan *tasks, err error) { func (e *EPUBImageProcessor) load() (totalImages int, output chan *tasks, err error) {
fi, err := os.Stat(e.Input) fi, err := os.Stat(e.options.Input)
if err != nil { if err != nil {
return return
} }
@ -60,7 +60,7 @@ func (e *EPUBImageProcessor) load() (totalImages int, output chan *tasks, err er
if fi.IsDir() { if fi.IsDir() {
return e.loadDir() return e.loadDir()
} else { } else {
switch ext := strings.ToLower(filepath.Ext(e.Input)); ext { switch ext := strings.ToLower(filepath.Ext(e.options.Input)); ext {
case ".cbz", ".zip": case ".cbz", ".zip":
return e.loadCbz() return e.loadCbz()
case ".cbr", ".rar": case ".cbr", ".rar":
@ -101,7 +101,7 @@ func (e *EPUBImageProcessor) corruptedImage(path, name string) image.Image {
func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *tasks, err error) { func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *tasks, err error) {
images := make([]string, 0) images := make([]string, 0)
input := filepath.Clean(e.Input) input := filepath.Clean(e.options.Input)
err = filepath.WalkDir(input, func(path string, d fs.DirEntry, err error) error { err = filepath.WalkDir(input, func(path string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
return err return err
@ -123,7 +123,7 @@ func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *tasks, err
return return
} }
sort.Sort(sortpath.By(images, e.SortPathMode)) sort.Sort(sortpath.By(images, e.options.SortPathMode))
// Queue all file with id // Queue all file with id
type job struct { type job struct {
@ -139,16 +139,16 @@ func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *tasks, err
}() }()
// read in parallel and get an image // read in parallel and get an image
output = make(chan *tasks, e.Workers) output = make(chan *tasks, e.options.Workers)
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for j := 0; j < e.WorkersRatio(50); j++ { for j := 0; j < e.options.WorkersRatio(50); j++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
for job := range jobs { for job := range jobs {
var img image.Image var img image.Image
var err error var err error
if !e.Dry { if !e.options.Dry {
var f *os.File var f *os.File
f, err = os.Open(job.Path) f, err = os.Open(job.Path)
if err == nil { if err == nil {
@ -188,7 +188,7 @@ func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *tasks, err
// load a zip file that include images // load a zip file that include images
func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *tasks, err error) { func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *tasks, err error) {
r, err := zip.OpenReader(e.Input) r, err := zip.OpenReader(e.options.Input)
if err != nil { if err != nil {
return return
} }
@ -212,7 +212,7 @@ func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *tasks, err
for _, img := range images { for _, img := range images {
names = append(names, img.Name) names = append(names, img.Name)
} }
sort.Sort(sortpath.By(names, e.SortPathMode)) sort.Sort(sortpath.By(names, e.options.SortPathMode))
indexedNames := make(map[string]int) indexedNames := make(map[string]int)
for i, name := range names { for i, name := range names {
@ -231,16 +231,16 @@ func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *tasks, err
} }
}() }()
output = make(chan *tasks, e.Workers) output = make(chan *tasks, e.options.Workers)
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for j := 0; j < e.WorkersRatio(50); j++ { for j := 0; j < e.options.WorkersRatio(50); j++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
for job := range jobs { for job := range jobs {
var img image.Image var img image.Image
var err error var err error
if !e.Dry { if !e.options.Dry {
var f io.ReadCloser var f io.ReadCloser
f, err = job.F.Open() f, err = job.F.Open()
if err == nil { if err == nil {
@ -275,7 +275,7 @@ func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *tasks, err
// load a rar file that include images // load a rar file that include images
func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err error) { func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err error) {
var isSolid bool var isSolid bool
files, err := rardecode.List(e.Input) files, err := rardecode.List(e.options.Input)
if err != nil { if err != nil {
return return
} }
@ -296,7 +296,7 @@ func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err
return return
} }
sort.Sort(sortpath.By(names, e.SortPathMode)) sort.Sort(sortpath.By(names, e.options.SortPathMode))
indexedNames := make(map[string]int) indexedNames := make(map[string]int)
for i, name := range names { for i, name := range names {
@ -312,10 +312,10 @@ func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err
jobs := make(chan *job) jobs := make(chan *job)
go func() { go func() {
defer close(jobs) defer close(jobs)
if isSolid && !e.Dry { if isSolid && !e.options.Dry {
r, rerr := rardecode.OpenReader(e.Input) r, rerr := rardecode.OpenReader(e.options.Input)
if rerr != nil { if rerr != nil {
fmt.Fprintf(os.Stderr, "\nerror processing image %s: %s\n", e.Input, rerr) fmt.Fprintf(os.Stderr, "\nerror processing image %s: %s\n", e.options.Input, rerr)
os.Exit(1) os.Exit(1)
} }
defer r.Close() defer r.Close()
@ -350,16 +350,16 @@ func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err
}() }()
// send file to the queue // send file to the queue
output = make(chan *tasks, e.Workers) output = make(chan *tasks, e.options.Workers)
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for j := 0; j < e.WorkersRatio(50); j++ { for j := 0; j < e.options.WorkersRatio(50); j++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
for job := range jobs { for job := range jobs {
var img image.Image var img image.Image
var err error var err error
if !e.Dry { if !e.options.Dry {
var f io.ReadCloser var f io.ReadCloser
f, err = job.Open() f, err = job.Open()
if err == nil { if err == nil {
@ -391,7 +391,7 @@ func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *tasks, err
// extract image from a pdf // extract image from a pdf
func (e *EPUBImageProcessor) loadPdf() (totalImages int, output chan *tasks, err error) { func (e *EPUBImageProcessor) loadPdf() (totalImages int, output chan *tasks, err error) {
pdf := pdfread.Load(e.Input) pdf := pdfread.Load(e.options.Input)
if pdf == nil { if pdf == nil {
err = fmt.Errorf("can't read pdf") err = fmt.Errorf("can't read pdf")
return return
@ -406,7 +406,7 @@ func (e *EPUBImageProcessor) loadPdf() (totalImages int, output chan *tasks, err
for i := 0; i < totalImages; i++ { for i := 0; i < totalImages; i++ {
var img image.Image var img image.Image
var err error var err error
if !e.Dry { if !e.options.Dry {
img, err = pdfimage.Extract(pdf, i+1) img, err = pdfimage.Extract(pdf, i+1)
} }

View File

@ -4,6 +4,7 @@ create a progress bar with custom settings.
package epubprogress package epubprogress
import ( import (
"encoding/json"
"fmt" "fmt"
"os" "os"
"time" "time"
@ -20,18 +21,21 @@ type Options struct {
TotalJob int TotalJob int
} }
type EpubProgress interface { type epubProgress interface {
Add(num int) error Add(num int) error
Close() error Close() error
} }
func New(o Options) EpubProgress { func New(o Options) epubProgress {
if o.Quiet { if o.Quiet {
return progressbar.DefaultSilent(int64(o.Max)) return progressbar.DefaultSilent(int64(o.Max))
} }
if o.Json { if o.Json {
return newEpubProgressJson(o) return &epubProgressJson{
o: o,
e: json.NewEncoder(os.Stdout),
}
} }
fmtJob := fmt.Sprintf("%%0%dd", len(fmt.Sprint(o.TotalJob))) fmtJob := fmt.Sprintf("%%0%dd", len(fmt.Sprint(o.TotalJob)))

View File

@ -2,23 +2,15 @@ package epubprogress
import ( import (
"encoding/json" "encoding/json"
"os"
) )
type EpubProgressJson struct { type epubProgressJson struct {
o Options o Options
e *json.Encoder e *json.Encoder
current int current int
} }
func newEpubProgressJson(o Options) EpubProgress { func (p *epubProgressJson) Add(num int) error {
return &EpubProgressJson{
o: o,
e: json.NewEncoder(os.Stdout),
}
}
func (p *EpubProgressJson) Add(num int) error {
p.current += num p.current += num
p.e.Encode(map[string]any{ p.e.Encode(map[string]any{
"type": "progress", "type": "progress",
@ -37,6 +29,6 @@ func (p *EpubProgressJson) Add(num int) error {
return nil return nil
} }
func (p *EpubProgressJson) Close() error { func (p *epubProgressJson) Close() error {
return nil return nil
} }

View File

@ -0,0 +1,23 @@
/*
Templates use to create xml files of the EPUB.
*/
package epubtemplates
import _ "embed"
var (
//go:embed "epubtemplates_container.xml.tmpl"
Container string
//go:embed "epubtemplates_applebooks.xml.tmpl"
AppleBooks string
//go:embed "epubtemplates_style.css.tmpl"
Style string
//go:embed "epubtemplates_text.xhtml.tmpl"
Text string
//go:embed "epubtemplates_blank.xhtml.tmpl"
Blank string
)

View File

@ -4,8 +4,8 @@ import (
"fmt" "fmt"
"github.com/beevik/etree" "github.com/beevik/etree"
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image" "github.com/celogeek/go-comic-converter/v2/internal/epubimage"
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options" "github.com/celogeek/go-comic-converter/v2/pkg/epuboptions"
) )
type ContentOptions struct { type ContentOptions struct {
@ -16,8 +16,8 @@ type ContentOptions struct {
Publisher string Publisher string
UpdatedAt string UpdatedAt string
ImageOptions *epuboptions.Image ImageOptions *epuboptions.Image
Cover *epubimage.Image Cover *epubimage.EPUBImage
Images []*epubimage.Image Images []*epubimage.EPUBImage
Current int Current int
Total int Total int
} }
@ -140,7 +140,7 @@ func getMeta(o *ContentOptions) []tag {
func getManifest(o *ContentOptions) []tag { func getManifest(o *ContentOptions) []tag {
var imageTags, pageTags, spaceTags []tag var imageTags, pageTags, spaceTags []tag
addTag := func(img *epubimage.Image, withSpace bool) { addTag := func(img *epubimage.EPUBImage, withSpace bool) {
imageTags = append(imageTags, imageTags = append(imageTags,
tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": fmt.Sprintf("image/%s", o.ImageOptions.Format)}, ""}, tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": fmt.Sprintf("image/%s", o.ImageOptions.Format)}, ""},
) )

View File

@ -5,11 +5,11 @@ import (
"strings" "strings"
"github.com/beevik/etree" "github.com/beevik/etree"
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image" "github.com/celogeek/go-comic-converter/v2/internal/epubimage"
) )
// create toc // create toc
func Toc(title string, hasTitle bool, stripFirstDirectoryFromToc bool, images []*epubimage.Image) string { func Toc(title string, hasTitle bool, stripFirstDirectoryFromToc bool, images []*epubimage.EPUBImage) string {
doc := etree.NewDocument() doc := etree.NewDocument()
doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`) doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
doc.CreateDirective("DOCTYPE html") doc.CreateDirective("DOCTYPE html")

View File

@ -63,7 +63,7 @@ func (e *EPUBZip) Copy(fz *zip.File) error {
} }
// Write image. They are already compressed, so we write them down directly. // Write image. They are already compressed, so we write them down directly.
func (e *EPUBZip) WriteRaw(raw *ZipImage) error { func (e *EPUBZip) WriteRaw(raw *EPUBZipImage) error {
m, err := e.wz.CreateRaw(raw.Header) m, err := e.wz.CreateRaw(raw.Header)
if err != nil { if err != nil {
return err return err

View File

@ -12,13 +12,13 @@ import (
"time" "time"
) )
type ZipImage struct { type EPUBZipImage struct {
Header *zip.FileHeader Header *zip.FileHeader
Data []byte Data []byte
} }
// create gzip encoded jpeg // create gzip encoded jpeg
func CompressImage(filename string, format string, img image.Image, quality int) (*ZipImage, error) { func CompressImage(filename string, format string, img image.Image, quality int) (*EPUBZipImage, error) {
var ( var (
data, cdata bytes.Buffer data, cdata bytes.Buffer
err error err error
@ -52,7 +52,7 @@ func CompressImage(filename string, format string, img image.Image, quality int)
} }
t := time.Now() t := time.Now()
return &ZipImage{ return &EPUBZipImage{
&zip.FileHeader{ &zip.FileHeader{
Name: filename, Name: filename,
CompressedSize64: uint64(cdata.Len()), CompressedSize64: uint64(cdata.Len()),

View File

@ -0,0 +1,54 @@
package epubzip
import (
"archive/zip"
"os"
)
type EPUBZipImageReader struct {
filename string
fh *os.File
fz *zip.Reader
files map[string]*zip.File
}
func NewImageReader(filename string) (*EPUBZipImageReader, error) {
fh, err := os.Open(filename)
if err != nil {
return nil, err
}
s, err := fh.Stat()
if err != nil {
return nil, err
}
fz, err := zip.NewReader(fh, s.Size())
if err != nil {
return nil, err
}
files := map[string]*zip.File{}
for _, z := range fz.File {
files[z.Name] = z
}
return &EPUBZipImageReader{filename, fh, fz, files}, nil
}
func (e *EPUBZipImageReader) Get(filename string) *zip.File {
return e.files[filename]
}
func (e *EPUBZipImageReader) Size(filename string) uint64 {
img := e.Get(filename)
if img != nil {
return img.CompressedSize64 + 30 + uint64(len(img.Name))
}
return 0
}
func (e *EPUBZipImageReader) Close() error {
return e.fh.Close()
}
func (e *EPUBZipImageReader) Remove() error {
return os.Remove(e.filename)
}

View File

@ -0,0 +1,52 @@
package epubzip
import (
"archive/zip"
"image"
"os"
"sync"
)
type EPUBZipImageWriter struct {
fh *os.File
fz *zip.Writer
format string
mut *sync.Mutex
}
func NewImageWriter(filename string, format string) (*EPUBZipImageWriter, error) {
fh, err := os.Create(filename)
if err != nil {
return nil, err
}
fz := zip.NewWriter(fh)
return &EPUBZipImageWriter{fh, fz, format, &sync.Mutex{}}, nil
}
func (e *EPUBZipImageWriter) Close() error {
if err := e.fz.Close(); err != nil {
e.fh.Close()
return err
}
return e.fh.Close()
}
func (e *EPUBZipImageWriter) Add(filename string, img image.Image, quality int) error {
zipImage, err := CompressImage(filename, e.format, img, quality)
if err != nil {
return err
}
e.mut.Lock()
defer e.mut.Unlock()
fh, err := e.fz.CreateRaw(zipImage.Header)
if err != nil {
return err
}
_, err = fh.Write(zipImage.Data)
if err != nil {
return err
}
return nil
}

30
main.go
View File

@ -14,8 +14,8 @@ import (
"runtime/debug" "runtime/debug"
"github.com/celogeek/go-comic-converter/v2/internal/converter" "github.com/celogeek/go-comic-converter/v2/internal/converter"
"github.com/celogeek/go-comic-converter/v2/internal/epub" "github.com/celogeek/go-comic-converter/v2/pkg/epub"
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options" "github.com/celogeek/go-comic-converter/v2/pkg/epuboptions"
"github.com/tcnksm/go-latest" "github.com/tcnksm/go-latest"
) )
@ -106,8 +106,7 @@ $ go install github.com/celogeek/go-comic-converter/v%d@%s
} }
profile := cmd.Options.GetProfile() profile := cmd.Options.GetProfile()
options := &epuboptions.EPUBOptions{
if err := epub.New(&epuboptions.Options{
Input: cmd.Options.Input, Input: cmd.Options.Input,
Output: cmd.Options.Output, Output: cmd.Options.Output,
LimitMb: cmd.Options.LimitMb, LimitMb: cmd.Options.LimitMb,
@ -122,7 +121,13 @@ $ go install github.com/celogeek/go-comic-converter/v%d@%s
Quiet: cmd.Options.Quiet, Quiet: cmd.Options.Quiet,
Json: cmd.Options.Json, Json: cmd.Options.Json,
Image: &epuboptions.Image{ Image: &epuboptions.Image{
Crop: &epuboptions.Crop{Enabled: cmd.Options.Crop, Left: cmd.Options.CropRatioLeft, Up: cmd.Options.CropRatioUp, Right: cmd.Options.CropRatioRight, Bottom: cmd.Options.CropRatioBottom}, Crop: &epuboptions.Crop{
Enabled: cmd.Options.Crop,
Left: cmd.Options.CropRatioLeft,
Up: cmd.Options.CropRatioUp,
Right: cmd.Options.CropRatioRight,
Bottom: cmd.Options.CropRatioBottom,
},
Quality: cmd.Options.Quality, Quality: cmd.Options.Quality,
Brightness: cmd.Options.Brightness, Brightness: cmd.Options.Brightness,
Contrast: cmd.Options.Contrast, Contrast: cmd.Options.Contrast,
@ -133,14 +138,25 @@ $ go install github.com/celogeek/go-comic-converter/v%d@%s
NoBlankImage: cmd.Options.NoBlankImage, NoBlankImage: cmd.Options.NoBlankImage,
Manga: cmd.Options.Manga, Manga: cmd.Options.Manga,
HasCover: cmd.Options.HasCover, HasCover: cmd.Options.HasCover,
View: &epuboptions.View{Width: profile.Width, Height: profile.Height, AspectRatio: cmd.Options.AspectRatio, PortraitOnly: cmd.Options.PortraitOnly, Color: epuboptions.Color{Foreground: cmd.Options.ForegroundColor, Background: cmd.Options.BackgroundColor}}, View: &epuboptions.View{
Width: profile.Width,
Height: profile.Height,
AspectRatio: cmd.Options.AspectRatio,
PortraitOnly: cmd.Options.PortraitOnly,
Color: epuboptions.Color{
Foreground: cmd.Options.ForegroundColor,
Background: cmd.Options.BackgroundColor,
},
},
GrayScale: cmd.Options.Grayscale, GrayScale: cmd.Options.Grayscale,
GrayScaleMode: cmd.Options.GrayscaleMode, GrayScaleMode: cmd.Options.GrayscaleMode,
Resize: !cmd.Options.NoResize, Resize: !cmd.Options.NoResize,
Format: cmd.Options.Format, Format: cmd.Options.Format,
AppleBookCompatibility: cmd.Options.AppleBookCompatibility, AppleBookCompatibility: cmd.Options.AppleBookCompatibility,
}, },
}).Write(); err != nil { }
if err := epub.Generate(options); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err) fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }

10
pkg/epub/epub.go Normal file
View File

@ -0,0 +1,10 @@
package epub
import (
"github.com/celogeek/go-comic-converter/v2/internal/epub"
"github.com/celogeek/go-comic-converter/v2/pkg/epuboptions"
)
func Generate(options *epuboptions.EPUBOptions) error {
return epub.New(options).Write()
}

View File

@ -41,7 +41,7 @@ type Image struct {
AppleBookCompatibility bool AppleBookCompatibility bool
} }
type Options struct { type EPUBOptions struct {
Input string Input string
Output string Output string
Title string Title string
@ -58,7 +58,7 @@ type Options struct {
Image *Image Image *Image
} }
func (o *Options) WorkersRatio(pct int) (nbWorkers int) { func (o *EPUBOptions) WorkersRatio(pct int) (nbWorkers int) {
nbWorkers = o.Workers * pct / 100 nbWorkers = o.Workers * pct / 100
if nbWorkers < 1 { if nbWorkers < 1 {
nbWorkers = 1 nbWorkers = 1
@ -66,6 +66,6 @@ func (o *Options) WorkersRatio(pct int) (nbWorkers int) {
return return
} }
func (o *Options) ImgStorage() string { func (o *EPUBOptions) Temp() string {
return fmt.Sprintf("%s.tmp", o.Output) return fmt.Sprintf("%s.tmp", o.Output)
} }