mirror of
https://github.com/celogeek/go-comic-converter.git
synced 2025-05-25 16:22:37 +02:00
Compare commits
No commits in common. "main" and "v2.7.0" have entirely different histories.
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,4 +1,2 @@
|
|||||||
.vscode
|
.vscode
|
||||||
.idea
|
.idea
|
||||||
.DS_Store
|
|
||||||
/tmp/
|
|
||||||
|
124
README.md
124
README.md
@ -38,19 +38,19 @@ First ensure to have a working version of GO: [Installation](https://go.dev/doc/
|
|||||||
|
|
||||||
Then install the last version of the tool:
|
Then install the last version of the tool:
|
||||||
```
|
```
|
||||||
$ go install github.com/celogeek/go-comic-converter/v3
|
$ go install github.com/celogeek/go-comic-converter/v2
|
||||||
```
|
```
|
||||||
|
|
||||||
To force install a specific version:
|
To force install a specific version:
|
||||||
```
|
```
|
||||||
# specific version
|
# specific version
|
||||||
$ go install github.com/celogeek/go-comic-converter/v3@v3.0.0
|
$ go install github.com/celogeek/go-comic-converter/v2@v2.6.9
|
||||||
|
|
||||||
# main branch
|
# main branch
|
||||||
$ go install github.com/celogeek/go-comic-converter/v3@main
|
$ go install github.com/celogeek/go-comic-converter/v2@main
|
||||||
|
|
||||||
# specific commit
|
# specific commit
|
||||||
$ go install github.com/celogeek/go-comic-converter/v3@COMMIT_HASH
|
$ go install github.com/celogeek/go-comic-converter/v2@141aeae
|
||||||
```
|
```
|
||||||
|
|
||||||
Add GOPATH to your PATH
|
Add GOPATH to your PATH
|
||||||
@ -58,39 +58,29 @@ Add GOPATH to your PATH
|
|||||||
$ export PATH=$(go env GOPATH)/bin:$PATH
|
$ export PATH=$(go env GOPATH)/bin:$PATH
|
||||||
```
|
```
|
||||||
|
|
||||||
# Upgrade from V2
|
|
||||||
|
|
||||||
The configuration file structure changes in the v3 compare to v2.
|
|
||||||
|
|
||||||
You need to recreate your config and save it again.
|
|
||||||
|
|
||||||
Use the `show`, `reset` and `save` option.
|
|
||||||
|
|
||||||
# Check last version
|
# Check last version
|
||||||
|
|
||||||
You can check if a new version is available with:
|
You can check if a new version is available with:
|
||||||
```
|
```
|
||||||
$ go-comic-converter -version
|
$ go-comic-converter -version
|
||||||
go-comic-converter
|
go-comic-converter
|
||||||
Path : github.com/celogeek/go-comic-converter/v3
|
Path : github.com/celogeek/go-comic-converter/v2
|
||||||
Sum : h1:tUFF2m/fGlOJOwC0/PlTopMfcBMprKvgr6TiQHQxEeo=
|
Sum : h1:tUFF2m/fGlOJOwC0/PlTopMfcBMprKvgr6TiQHQxEeo=
|
||||||
Version : v3.0.0
|
Version : v2.6.9
|
||||||
Available Version: v3.0.0
|
Available Version: v2.6.9
|
||||||
|
|
||||||
To install the latest version:
|
To install the latest version:
|
||||||
$ go install github.com/celogeek/go-comic-converter/v3@v3.0.0
|
$ go install github.com/celogeek/go-comic-converter/v2@v2.6.9
|
||||||
```
|
```
|
||||||
|
|
||||||
# Supported image files
|
# Supported image files
|
||||||
|
|
||||||
The supported image files are jpeg and png from the sources.
|
The supported image files are jpeg and png from the sources.
|
||||||
|
|
||||||
The extensions can be: `jpg`, `jpeg`, `png`, `webp`, `tiff`.
|
The extensions can be: `jpg`, `jpeg`, `png`, `webp`.
|
||||||
|
|
||||||
The case for extensions doesn't matter.
|
The case for extensions doesn't matter.
|
||||||
|
|
||||||
For the passthrough mode (format=copy), the supported extensions are: `jpg`, `jpeg`, `png`
|
|
||||||
|
|
||||||
# Usage
|
# Usage
|
||||||
|
|
||||||
## Convert directory
|
## Convert directory
|
||||||
@ -158,7 +148,7 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : true
|
Auto contrast : true
|
||||||
Auto rotate : true
|
Auto rotate : true
|
||||||
Auto split double page : true
|
Auto split double page : true
|
||||||
@ -206,7 +196,7 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : true
|
Auto contrast : true
|
||||||
Auto rotate : true
|
Auto rotate : true
|
||||||
Auto split double page : true
|
Auto split double page : true
|
||||||
@ -264,7 +254,7 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : false
|
Auto contrast : false
|
||||||
Auto rotate : false
|
Auto rotate : false
|
||||||
Auto split double page : false
|
Auto split double page : false
|
||||||
@ -295,12 +285,11 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : true
|
Auto contrast : true
|
||||||
Auto rotate : true
|
Auto rotate : true
|
||||||
Auto split double page : true
|
Auto split double page : true
|
||||||
Keep double page if split : true
|
Keep double page if split : true
|
||||||
Keep split double page aspect : true
|
|
||||||
No blank image : true
|
No blank image : true
|
||||||
Manga : true
|
Manga : true
|
||||||
Has cover : true
|
Has cover : true
|
||||||
@ -329,13 +318,15 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : false
|
Auto contrast : true
|
||||||
Auto rotate : false
|
Auto rotate : true
|
||||||
Auto split double page : false
|
Auto split double page : true
|
||||||
|
Keep double page if split : true
|
||||||
No blank image : true
|
No blank image : true
|
||||||
Manga : false
|
Manga : false
|
||||||
Has cover : true
|
Has cover : true
|
||||||
|
Limit : 200 Mb
|
||||||
Strip first directory from toc : false
|
Strip first directory from toc : false
|
||||||
Sort path mode : path=alphanumeric, file=alpha
|
Sort path mode : path=alphanumeric, file=alpha
|
||||||
Foreground color : #000
|
Foreground color : #000
|
||||||
@ -363,7 +354,7 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : false
|
Auto contrast : false
|
||||||
Auto rotate : false
|
Auto rotate : false
|
||||||
Auto split double page : false
|
Auto split double page : false
|
||||||
@ -398,14 +389,13 @@ Options:
|
|||||||
Grayscale : true
|
Grayscale : true
|
||||||
Grayscale mode : normal
|
Grayscale mode : normal
|
||||||
Crop : true
|
Crop : true
|
||||||
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 0% - Skip false
|
Crop ratio : 1 Left - 1 Up - 1 Right - 3 Bottom - Limit 10% - Skip true
|
||||||
Auto contrast : false
|
Auto contrast : false
|
||||||
Auto rotate : false
|
Auto rotate : false
|
||||||
Auto split double page : false
|
Auto split double page : false
|
||||||
No blank image : true
|
No blank image : true
|
||||||
Manga : true
|
Manga : true
|
||||||
Has cover : true
|
Has cover : true
|
||||||
Limit : 200 Mb
|
|
||||||
Strip first directory from toc : false
|
Strip first directory from toc : false
|
||||||
Sort path mode : path=alphanumeric, file=alpha
|
Sort path mode : path=alphanumeric, file=alpha
|
||||||
Foreground color : #000
|
Foreground color : #000
|
||||||
@ -445,34 +435,34 @@ Output:
|
|||||||
Config:
|
Config:
|
||||||
-profile string (default "SR")
|
-profile string (default "SR")
|
||||||
Profile to use:
|
Profile to use:
|
||||||
- KoAO - 1404 x 1872 - Kobo Aura ONE
|
- HR ( 2400x3840 ) - High Resolution
|
||||||
- KoF - 1440 x 1920 - Kobo Forma
|
- SR ( 1200x1920 ) - Standard Resolution
|
||||||
- KoE - 1404 x 1872 - Kobo Elipsa
|
- K1 ( 600x670 ) - Kindle 1
|
||||||
- KV - 1072 x 1448 - Kindle Paperwhite 3/4/Voyage/Oasis
|
- K11 ( 1072x1448 ) - Kindle 11
|
||||||
- KoG - 768 x 1024 - Kobo Glo
|
- K2 ( 600x670 ) - Kindle 2
|
||||||
- KoA - 758 x 1024 - Kobo Aura
|
- K34 ( 600x800 ) - Kindle Keyboard/Touch
|
||||||
- RM1 - 1404 x 1872 - reMarkable 1
|
- K578 ( 600x800 ) - Kindle
|
||||||
- RM2 - 1404 x 1872 - reMarkable 2
|
- KDX ( 824x1000 ) - Kindle DX/DXG
|
||||||
- K1 - 600 x 670 - Kindle 1
|
- KPW ( 758x1024 ) - Kindle Paperwhite 1/2
|
||||||
- K11 - 1072 x 1448 - Kindle 11
|
- KV ( 1072x1448 ) - Kindle Paperwhite 3/4/Voyage/Oasis
|
||||||
- K2 - 600 x 670 - Kindle 2
|
- KPW5 ( 1236x1648 ) - Kindle Paperwhite 5/Signature Edition
|
||||||
- K34 - 600 x 800 - Kindle Keyboard/Touch
|
- KO ( 1264x1680 ) - Kindle Oasis 2/3
|
||||||
- KPW5 - 1236 x 1648 - Kindle Paperwhite 5/Signature Edition
|
- KS ( 1860x2480 ) - Kindle Scribe
|
||||||
- KoAH2O - 1080 x 1430 - Kobo Aura H2O
|
- KoMT ( 600x800 ) - Kobo Mini/Touch
|
||||||
- KoN - 758 x 1024 - Kobo Nia
|
- KoG ( 768x1024 ) - Kobo Glo
|
||||||
- KoL - 1264 x 1680 - Kobo Libra H2O/Kobo Libra 2
|
- KoGHD ( 1072x1448 ) - Kobo Glo HD
|
||||||
- HR - 2400 x 3840 - High Resolution
|
- KoA ( 758x1024 ) - Kobo Aura
|
||||||
- KO - 1264 x 1680 - Kindle Oasis 2/3
|
- KoAHD ( 1080x1440 ) - Kobo Aura HD
|
||||||
- KS - 1860 x 2480 - Kindle Scribe
|
- KoAH2O ( 1080x1430 ) - Kobo Aura H2O
|
||||||
- KoMT - 600 x 800 - Kobo Mini/Touch
|
- KoAO ( 1404x1872 ) - Kobo Aura ONE
|
||||||
- KoAHD - 1080 x 1440 - Kobo Aura HD
|
- KoN ( 758x1024 ) - Kobo Nia
|
||||||
- KoC - 1072 x 1448 - Kobo Clara HD/Kobo Clara 2E
|
- KoC ( 1072x1448 ) - Kobo Clara HD/Kobo Clara 2E
|
||||||
- KoS - 1440 x 1920 - Kobo Sage
|
- KoL ( 1264x1680 ) - Kobo Libra H2O/Kobo Libra 2
|
||||||
- SR - 1200 x 1920 - Standard Resolution
|
- KoF ( 1440x1920 ) - Kobo Forma
|
||||||
- K578 - 600 x 800 - Kindle
|
- KoS ( 1440x1920 ) - Kobo Sage
|
||||||
- KDX - 824 x 1000 - Kindle DX/DXG
|
- KoE ( 1404x1872 ) - Kobo Elipsa
|
||||||
- KPW - 758 x 1024 - Kindle Paperwhite 1/2
|
- RM1 ( 1404x1872 ) - reMarkable 1
|
||||||
- KoGHD - 1072 x 1448 - Kobo Glo HD
|
- RM2 ( 1404x1872 ) - reMarkable 2
|
||||||
-quality int (default 85)
|
-quality int (default 85)
|
||||||
Quality of the image
|
Quality of the image
|
||||||
-grayscale (default true)
|
-grayscale (default true)
|
||||||
@ -492,9 +482,9 @@ Config:
|
|||||||
Crop ratio right: ratio of pixels allow to be non blank while cutting on the right.
|
Crop ratio right: ratio of pixels allow to be non blank while cutting on the right.
|
||||||
-crop-ratio-bottom int (default 3)
|
-crop-ratio-bottom int (default 3)
|
||||||
Crop ratio bottom: ratio of pixels allow to be non blank while cutting on the bottom.
|
Crop ratio bottom: ratio of pixels allow to be non blank while cutting on the bottom.
|
||||||
-crop-limit int
|
-crop-limit int (default 10)
|
||||||
Crop limit: maximum number of cropping in percentage allowed. 0 mean unlimited.
|
Crop limit: maximum number of cropping in percentage allowed. 0 mean unlimited.
|
||||||
-crop-skip-if-limit-reached
|
-crop-skip-if-limit-reached (default true)
|
||||||
Crop skip if limit reached.
|
Crop skip if limit reached.
|
||||||
-brightness int
|
-brightness int
|
||||||
Brightness readjustment: between -100 and 100, > 0 lighter, < 0 darker
|
Brightness readjustment: between -100 and 100, > 0 lighter, < 0 darker
|
||||||
@ -508,8 +498,6 @@ Config:
|
|||||||
Auto Split double page when width > height
|
Auto Split double page when width > height
|
||||||
-keepdoublepageifsplit (default true)
|
-keepdoublepageifsplit (default true)
|
||||||
Keep the double page if split
|
Keep the double page if split
|
||||||
-keepsplitdoublepageaspect (default true)
|
|
||||||
Keep aspect of split part of a double page (best for landscape rendering)
|
|
||||||
-noblankimage (default true)
|
-noblankimage (default true)
|
||||||
Remove blank image
|
Remove blank image
|
||||||
-manga
|
-manga
|
||||||
@ -529,10 +517,10 @@ Config:
|
|||||||
Foreground color in hexadecimal format RGB. Black=000, White=FFF
|
Foreground color in hexadecimal format RGB. Black=000, White=FFF
|
||||||
-background-color string (default "FFF")
|
-background-color string (default "FFF")
|
||||||
Background color in hexadecimal format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777
|
Background color in hexadecimal format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777
|
||||||
-resize (default true)
|
-noresize
|
||||||
Reduce image size if exceed device size
|
Do not reduce image size if exceed device size
|
||||||
-format string (default "jpeg")
|
-format string (default "jpeg")
|
||||||
Format of output images: jpeg (lossy), png (lossless), copy (no processing)
|
Format of output images: jpeg (lossy), png (lossless)
|
||||||
-aspect-ratio float
|
-aspect-ratio float
|
||||||
Aspect ratio (height/width) of the output
|
Aspect ratio (height/width) of the output
|
||||||
-1 = same as device
|
-1 = same as device
|
||||||
@ -595,7 +583,3 @@ This project is largely inspired from KCC (Kindle Comic Converter). Thanks:
|
|||||||
- [ciromattia](https://github.com/ciromattia/kcc)
|
- [ciromattia](https://github.com/ciromattia/kcc)
|
||||||
- [darodi fork](https://github.com/darodi/kcc)
|
- [darodi fork](https://github.com/darodi/kcc)
|
||||||
|
|
||||||
# UI
|
|
||||||
|
|
||||||
Thanks for UI contribution:
|
|
||||||
- [manueldidonna / Comic2Books](https://github.com/manueldidonna/comic2books)
|
|
||||||
|
21
go.mod
21
go.mod
@ -1,28 +1,29 @@
|
|||||||
module github.com/celogeek/go-comic-converter/v3
|
module github.com/celogeek/go-comic-converter/v2
|
||||||
|
|
||||||
go 1.23
|
go 1.22
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/beevik/etree v1.5.0
|
github.com/beevik/etree v1.3.0
|
||||||
github.com/disintegration/gift v1.2.1
|
github.com/disintegration/gift v1.2.1
|
||||||
github.com/fogleman/gg v1.3.0
|
github.com/fogleman/gg v1.3.0
|
||||||
github.com/gofrs/uuid v4.4.0+incompatible
|
github.com/gofrs/uuid v4.4.0+incompatible
|
||||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
|
||||||
github.com/nwaples/rardecode/v2 v2.1.0
|
github.com/nwaples/rardecode/v2 v2.0.0-beta.2
|
||||||
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0
|
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0
|
||||||
github.com/schollz/progressbar/v3 v3.18.0
|
github.com/schollz/progressbar/v3 v3.14.2
|
||||||
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e
|
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e
|
||||||
golang.org/x/image v0.24.0
|
golang.org/x/image v0.15.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/go-github v17.0.0+incompatible // indirect
|
github.com/google/go-github v17.0.0+incompatible // indirect
|
||||||
github.com/google/go-querystring v1.1.0 // indirect
|
github.com/google/go-querystring v1.1.0 // indirect
|
||||||
github.com/hashicorp/go-version v1.7.0 // indirect
|
github.com/hashicorp/go-version v1.6.0 // indirect
|
||||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
golang.org/x/net v0.35.0 // indirect
|
github.com/stretchr/testify v1.9.0 // indirect
|
||||||
golang.org/x/sys v0.30.0 // indirect
|
golang.org/x/net v0.24.0 // indirect
|
||||||
golang.org/x/term v0.29.0 // indirect
|
golang.org/x/sys v0.19.0 // indirect
|
||||||
|
golang.org/x/term v0.19.0 // indirect
|
||||||
)
|
)
|
||||||
|
44
go.sum
44
go.sum
@ -1,7 +1,6 @@
|
|||||||
github.com/beevik/etree v1.5.0 h1:iaQZFSDS+3kYZiGoc9uKeOkUY3nYMXOKLl6KIJxiJWs=
|
github.com/beevik/etree v1.3.0 h1:hQTc+pylzIKDb23yYprodCWWTt+ojFfUZyzU09a/hmU=
|
||||||
github.com/beevik/etree v1.5.0/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs=
|
github.com/beevik/etree v1.3.0/go.mod h1:aiPf89g/1k3AShMVAzriilpcE4R/Vuor90y83zVZWFc=
|
||||||
github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvdZ6pc=
|
github.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvdZ6pc=
|
||||||
@ -18,34 +17,39 @@ github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4r
|
|||||||
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
|
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
|
||||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||||
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
|
github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek=
|
||||||
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
|
||||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||||
github.com/nwaples/rardecode/v2 v2.1.0 h1:JQl9ZoBPDy+nIZGb1mx8+anfHp/LV3NE2MjMiv0ct/U=
|
github.com/nwaples/rardecode/v2 v2.0.0-beta.2 h1:e3mzJFJs4k83GXBEiTaQ5HgSc/kOK8q0rDaRO0MPaOk=
|
||||||
github.com/nwaples/rardecode/v2 v2.1.0/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw=
|
github.com/nwaples/rardecode/v2 v2.0.0-beta.2/go.mod h1:yntwv/HfMc/Hbvtq9I19D1n58te3h6KsqCf3GxyfBGY=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0 h1:fuFvfwIc+cpySYurvDNTs5LIHXP9Cj3reVRplj9Whv4=
|
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0 h1:fuFvfwIc+cpySYurvDNTs5LIHXP9Cj3reVRplj9Whv4=
|
||||||
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0/go.mod h1:Ql3QqeGiYGlPOtYz+F/L7J27spqDcdH9LhDHOrrdsD4=
|
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0/go.mod h1:Ql3QqeGiYGlPOtYz+F/L7J27spqDcdH9LhDHOrrdsD4=
|
||||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
github.com/schollz/progressbar/v3 v3.18.0 h1:uXdoHABRFmNIjUfte/Ex7WtuyVslrw2wVPQmCN62HpA=
|
github.com/schollz/progressbar/v3 v3.14.2 h1:EducH6uNLIWsr560zSV1KrTeUb/wZGAHqyMFIEa99ks=
|
||||||
github.com/schollz/progressbar/v3 v3.18.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
|
github.com/schollz/progressbar/v3 v3.14.2/go.mod h1:aQAZQnhF4JGFtRJiw/eobaXpsqpVQAftEQ+hLGXaRc4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e h1:IWllFTiDjjLIf2oeKxpIUmtiDV5sn71VgeQgg6vcE7k=
|
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e h1:IWllFTiDjjLIf2oeKxpIUmtiDV5sn71VgeQgg6vcE7k=
|
||||||
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e/go.mod h1:d7u6HkTYKSv5m6MCKkOQlHwaShTMl3HjqSGW3XtVhXM=
|
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e/go.mod h1:d7u6HkTYKSv5m6MCKkOQlHwaShTMl3HjqSGW3XtVhXM=
|
||||||
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
|
golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
|
||||||
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
|
golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
|
||||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
|
||||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||||
|
golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q=
|
||||||
|
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
@ -15,30 +15,30 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
"slices"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
"github.com/celogeek/go-comic-converter/v2/internal/converter/options"
|
||||||
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Converter struct {
|
type Converter struct {
|
||||||
Options *Options
|
Options *options.Options
|
||||||
Cmd *flag.FlagSet
|
Cmd *flag.FlagSet
|
||||||
|
|
||||||
order []order
|
order []converterOrder
|
||||||
isZeroValueErrs []error
|
isZeroValueErrs []error
|
||||||
startAt time.Time
|
startAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// New Create a new parser
|
// New Create a new parser
|
||||||
func New() *Converter {
|
func New() *Converter {
|
||||||
o := NewOptions()
|
o := options.New()
|
||||||
cmd := flag.NewFlagSet("go-comic-converter", flag.ExitOnError)
|
cmd := flag.NewFlagSet("go-comic-converter", flag.ExitOnError)
|
||||||
conv := &Converter{
|
conv := &Converter{
|
||||||
Options: o,
|
Options: o,
|
||||||
Cmd: cmd,
|
Cmd: cmd,
|
||||||
order: make([]order, 0),
|
order: make([]converterOrder, 0),
|
||||||
startAt: time.Now(),
|
startAt: time.Now(),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,9 +48,9 @@ func New() *Converter {
|
|||||||
utils.Printf("Usage of %s:\n", filepath.Base(os.Args[0]))
|
utils.Printf("Usage of %s:\n", filepath.Base(os.Args[0]))
|
||||||
for _, o := range conv.order {
|
for _, o := range conv.order {
|
||||||
switch v := o.(type) {
|
switch v := o.(type) {
|
||||||
case orderSection:
|
case converterOrderSection:
|
||||||
utils.Printf("\n%s:\n", o.Value())
|
utils.Printf("\n%s:\n", o.Value())
|
||||||
case orderName:
|
case converterOrderName:
|
||||||
utils.Println(conv.Usage(v.isString, cmd.Lookup(v.Value())))
|
utils.Println(conv.Usage(v.isString, cmd.Lookup(v.Value())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -69,31 +69,31 @@ func (c *Converter) LoadConfig() error {
|
|||||||
|
|
||||||
// AddSection Create a new section of config
|
// AddSection Create a new section of config
|
||||||
func (c *Converter) AddSection(section string) {
|
func (c *Converter) AddSection(section string) {
|
||||||
c.order = append(c.order, orderSection{value: section})
|
c.order = append(c.order, converterOrderSection{value: section})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddStringParam Add a string parameter
|
// AddStringParam Add a string parameter
|
||||||
func (c *Converter) AddStringParam(p *string, name string, value string, usage string) {
|
func (c *Converter) AddStringParam(p *string, name string, value string, usage string) {
|
||||||
c.Cmd.StringVar(p, name, value, usage)
|
c.Cmd.StringVar(p, name, value, usage)
|
||||||
c.order = append(c.order, orderName{value: name, isString: true})
|
c.order = append(c.order, converterOrderName{value: name, isString: true})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddIntParam Add an integer parameter
|
// AddIntParam Add an integer parameter
|
||||||
func (c *Converter) AddIntParam(p *int, name string, value int, usage string) {
|
func (c *Converter) AddIntParam(p *int, name string, value int, usage string) {
|
||||||
c.Cmd.IntVar(p, name, value, usage)
|
c.Cmd.IntVar(p, name, value, usage)
|
||||||
c.order = append(c.order, orderName{value: name})
|
c.order = append(c.order, converterOrderName{value: name})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddFloatParam Add an float parameter
|
// AddFloatParam Add an float parameter
|
||||||
func (c *Converter) AddFloatParam(p *float64, name string, value float64, usage string) {
|
func (c *Converter) AddFloatParam(p *float64, name string, value float64, usage string) {
|
||||||
c.Cmd.Float64Var(p, name, value, usage)
|
c.Cmd.Float64Var(p, name, value, usage)
|
||||||
c.order = append(c.order, orderName{value: name})
|
c.order = append(c.order, converterOrderName{value: name})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddBoolParam Add a boolean parameter
|
// AddBoolParam Add a boolean parameter
|
||||||
func (c *Converter) AddBoolParam(p *bool, name string, value bool, usage string) {
|
func (c *Converter) AddBoolParam(p *bool, name string, value bool, usage string) {
|
||||||
c.Cmd.BoolVar(p, name, value, usage)
|
c.Cmd.BoolVar(p, name, value, usage)
|
||||||
c.order = append(c.order, orderName{value: name})
|
c.order = append(c.order, converterOrderName{value: name})
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitParse Initialize the parser with all section and parameter.
|
// InitParse Initialize the parser with all section and parameter.
|
||||||
@ -105,36 +105,35 @@ func (c *Converter) InitParse() {
|
|||||||
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, "Profile to use: \n"+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.Image.Quality, "quality", c.Options.Image.Quality, "Quality of the image")
|
c.AddIntParam(&c.Options.Quality, "quality", c.Options.Quality, "Quality of the image")
|
||||||
c.AddBoolParam(&c.Options.Image.GrayScale, "grayscale", c.Options.Image.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.Image.GrayScaleMode, "grayscale-mode", c.Options.Image.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.Image.Crop.Enabled, "crop", c.Options.Image.Crop.Enabled, "Crop images")
|
c.AddBoolParam(&c.Options.Crop, "crop", c.Options.Crop, "Crop images")
|
||||||
c.AddIntParam(&c.Options.Image.Crop.Left, "crop-ratio-left", c.Options.Image.Crop.Left, "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.Image.Crop.Up, "crop-ratio-up", c.Options.Image.Crop.Up, "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.Image.Crop.Right, "crop-ratio-right", c.Options.Image.Crop.Right, "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.Image.Crop.Bottom, "crop-ratio-bottom", c.Options.Image.Crop.Bottom, "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.Image.Crop.Limit, "crop-limit", c.Options.Image.Crop.Limit, "Crop limit: maximum number of cropping in percentage allowed. 0 mean unlimited.")
|
c.AddIntParam(&c.Options.CropLimit, "crop-limit", c.Options.CropLimit, "Crop limit: maximum number of cropping in percentage allowed. 0 mean unlimited.")
|
||||||
c.AddBoolParam(&c.Options.Image.Crop.SkipIfLimitReached, "crop-skip-if-limit-reached", c.Options.Image.Crop.SkipIfLimitReached, "Crop skip if limit reached.")
|
c.AddBoolParam(&c.Options.CropSkipIfLimitReached, "crop-skip-if-limit-reached", c.Options.CropSkipIfLimitReached, "Crop skip if limit reached.")
|
||||||
c.AddIntParam(&c.Options.Image.Brightness, "brightness", c.Options.Image.Brightness, "Brightness readjustment: between -100 and 100, > 0 lighter, < 0 darker")
|
c.AddIntParam(&c.Options.Brightness, "brightness", c.Options.Brightness, "Brightness readjustment: between -100 and 100, > 0 lighter, < 0 darker")
|
||||||
c.AddIntParam(&c.Options.Image.Contrast, "contrast", c.Options.Image.Contrast, "Contrast readjustment: between -100 and 100, > 0 more contrast, < 0 less contrast")
|
c.AddIntParam(&c.Options.Contrast, "contrast", c.Options.Contrast, "Contrast readjustment: between -100 and 100, > 0 more contrast, < 0 less contrast")
|
||||||
c.AddBoolParam(&c.Options.Image.AutoContrast, "autocontrast", c.Options.Image.AutoContrast, "Improve contrast automatically")
|
c.AddBoolParam(&c.Options.AutoContrast, "autocontrast", c.Options.AutoContrast, "Improve contrast automatically")
|
||||||
c.AddBoolParam(&c.Options.Image.AutoRotate, "autorotate", c.Options.Image.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.Image.AutoSplitDoublePage, "autosplitdoublepage", c.Options.Image.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.Image.KeepDoublePageIfSplit, "keepdoublepageifsplit", c.Options.Image.KeepDoublePageIfSplit, "Keep the double page if split")
|
c.AddBoolParam(&c.Options.KeepDoublePageIfSplit, "keepdoublepageifsplit", c.Options.KeepDoublePageIfSplit, "Keep the double page if split")
|
||||||
c.AddBoolParam(&c.Options.Image.KeepSplitDoublePageAspect, "keepsplitdoublepageaspect", c.Options.Image.KeepSplitDoublePageAspect, "Keep aspect of split part of a double page (best for landscape rendering)")
|
c.AddBoolParam(&c.Options.NoBlankImage, "noblankimage", c.Options.NoBlankImage, "Remove blank image")
|
||||||
c.AddBoolParam(&c.Options.Image.NoBlankImage, "noblankimage", c.Options.Image.NoBlankImage, "Remove blank image")
|
c.AddBoolParam(&c.Options.Manga, "manga", c.Options.Manga, "Manga mode (right to left)")
|
||||||
c.AddBoolParam(&c.Options.Image.Manga, "manga", c.Options.Image.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.Image.HasCover, "hascover", c.Options.Image.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 = alphanumeric for path and alpha for file\n2 = alphanumeric for path and file")
|
c.AddIntParam(&c.Options.SortPathMode, "sort", c.Options.SortPathMode, "Sort path mode\n0 = alpha for path and file\n1 = alphanumeric for path and alpha for file\n2 = alphanumeric for path and file")
|
||||||
c.AddStringParam(&c.Options.Image.View.Color.Foreground, "foreground-color", c.Options.Image.View.Color.Foreground, "Foreground color in hexadecimal format RGB. Black=000, White=FFF")
|
c.AddStringParam(&c.Options.ForegroundColor, "foreground-color", c.Options.ForegroundColor, "Foreground color in hexadecimal format RGB. Black=000, White=FFF")
|
||||||
c.AddStringParam(&c.Options.Image.View.Color.Background, "background-color", c.Options.Image.View.Color.Background, "Background color in hexadecimal 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 hexadecimal format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777")
|
||||||
c.AddBoolParam(&c.Options.Image.Resize, "resize", c.Options.Image.Resize, "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.Image.Format, "format", c.Options.Image.Format, "Format of output images: jpeg (lossy), png (lossless), copy (no processing)")
|
c.AddStringParam(&c.Options.Format, "format", c.Options.Format, "Format of output images: jpeg (lossy), png (lossless)")
|
||||||
c.AddFloatParam(&c.Options.Image.View.AspectRatio, "aspect-ratio", c.Options.Image.View.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.Image.View.PortraitOnly, "portrait-only", c.Options.Image.View.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 split")
|
c.AddIntParam(&c.Options.TitlePage, "titlepage", c.Options.TitlePage, "Title page\n0 = never\n1 = always\n2 = only if epub is split")
|
||||||
|
|
||||||
c.AddSection("Default config")
|
c.AddSection("Default config")
|
||||||
@ -151,7 +150,7 @@ func (c *Converter) InitParse() {
|
|||||||
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.Image.AppleBookCompatibility, "applebookcompatibility", c.Options.Image.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")
|
||||||
@ -229,59 +228,52 @@ func (c *Converter) isZeroValue(f *flag.Flag, value string) (ok bool, err error)
|
|||||||
|
|
||||||
// Parse all parameters
|
// Parse all parameters
|
||||||
func (c *Converter) Parse() {
|
func (c *Converter) Parse() {
|
||||||
if err := c.Cmd.Parse(os.Args[1:]); err != nil {
|
_ = c.Cmd.Parse(os.Args[1:])
|
||||||
utils.Fatalf("cannot parse command line options: %v", err)
|
|
||||||
}
|
|
||||||
if c.Options.Help {
|
if c.Options.Help {
|
||||||
c.Cmd.Usage()
|
c.Cmd.Usage()
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Options.Auto {
|
if c.Options.Auto {
|
||||||
c.Options.Image.AutoContrast = true
|
c.Options.AutoContrast = true
|
||||||
c.Options.Image.AutoRotate = true
|
c.Options.AutoRotate = true
|
||||||
c.Options.Image.AutoSplitDoublePage = true
|
c.Options.AutoSplitDoublePage = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Options.MaxQuality {
|
if c.Options.MaxQuality {
|
||||||
c.Options.Image.Format = "png"
|
c.Options.Format = "png"
|
||||||
c.Options.Image.GrayScale = false
|
c.Options.Grayscale = false
|
||||||
c.Options.Image.Resize = false
|
c.Options.NoResize = true
|
||||||
} else if c.Options.BestQuality {
|
} else if c.Options.BestQuality {
|
||||||
c.Options.Image.Format = "jpeg"
|
c.Options.Format = "jpeg"
|
||||||
c.Options.Image.Quality = 100
|
c.Options.Quality = 100
|
||||||
c.Options.Image.GrayScale = false
|
c.Options.Grayscale = false
|
||||||
c.Options.Image.Resize = false
|
c.Options.NoResize = true
|
||||||
} else if c.Options.GreatQuality {
|
} else if c.Options.GreatQuality {
|
||||||
c.Options.Image.Format = "jpeg"
|
c.Options.Format = "jpeg"
|
||||||
c.Options.Image.Quality = 90
|
c.Options.Quality = 90
|
||||||
c.Options.Image.GrayScale = true
|
c.Options.Grayscale = true
|
||||||
c.Options.Image.Resize = false
|
c.Options.NoResize = true
|
||||||
} else if c.Options.GoodQuality {
|
} else if c.Options.GoodQuality {
|
||||||
c.Options.Image.Format = "jpeg"
|
c.Options.Format = "jpeg"
|
||||||
c.Options.Image.Quality = 90
|
c.Options.Quality = 90
|
||||||
c.Options.Image.GrayScale = true
|
c.Options.Grayscale = true
|
||||||
c.Options.Image.Resize = true
|
c.Options.NoResize = false
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Options.NoFilter {
|
if c.Options.NoFilter {
|
||||||
c.Options.Image.Crop.Enabled = false
|
c.Options.Crop = false
|
||||||
c.Options.Image.Brightness = 0
|
c.Options.Brightness = 0
|
||||||
c.Options.Image.Contrast = 0
|
c.Options.Contrast = 0
|
||||||
c.Options.Image.AutoContrast = false
|
c.Options.AutoContrast = false
|
||||||
c.Options.Image.AutoRotate = false
|
c.Options.AutoRotate = false
|
||||||
c.Options.Image.NoBlankImage = false
|
c.Options.NoBlankImage = false
|
||||||
c.Options.Image.Resize = false
|
c.Options.NoResize = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Options.Image.AppleBookCompatibility {
|
if c.Options.AppleBookCompatibility {
|
||||||
c.Options.Image.AutoSplitDoublePage = true
|
c.Options.AutoSplitDoublePage = true
|
||||||
c.Options.Image.KeepDoublePageIfSplit = false
|
c.Options.KeepDoublePageIfSplit = false
|
||||||
c.Options.Image.KeepSplitDoublePageAspect = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Options.Image.View.PortraitOnly {
|
|
||||||
c.Options.Image.KeepSplitDoublePageAspect = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -301,10 +293,10 @@ func (c *Converter) Validate() error {
|
|||||||
var defaultOutput string
|
var defaultOutput string
|
||||||
inputBase := filepath.Clean(c.Options.Input)
|
inputBase := filepath.Clean(c.Options.Input)
|
||||||
if fi.IsDir() {
|
if fi.IsDir() {
|
||||||
defaultOutput = inputBase + ".epub"
|
defaultOutput = fmt.Sprintf("%s.epub", inputBase)
|
||||||
} else {
|
} else {
|
||||||
ext := filepath.Ext(inputBase)
|
ext := filepath.Ext(inputBase)
|
||||||
defaultOutput = inputBase[0:len(inputBase)-len(ext)] + ".epub"
|
defaultOutput = fmt.Sprintf("%s.epub", inputBase[0:len(inputBase)-len(ext)])
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Options.Output == "" {
|
if c.Options.Output == "" {
|
||||||
@ -355,12 +347,12 @@ func (c *Converter) Validate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Brightness
|
// Brightness
|
||||||
if c.Options.Image.Brightness < -100 || c.Options.Image.Brightness > 100 {
|
if c.Options.Brightness < -100 || c.Options.Brightness > 100 {
|
||||||
return errors.New("brightness should be between -100 and 100")
|
return errors.New("brightness should be between -100 and 100")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Contrast
|
// Contrast
|
||||||
if c.Options.Image.Contrast < -100 || c.Options.Image.Contrast > 100 {
|
if c.Options.Contrast < -100 || c.Options.Contrast > 100 {
|
||||||
return errors.New("contrast should be between -100 and 100")
|
return errors.New("contrast should be between -100 and 100")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -371,21 +363,21 @@ func (c *Converter) Validate() error {
|
|||||||
|
|
||||||
// Color
|
// Color
|
||||||
colorRegex := regexp.MustCompile("^[0-9A-F]{3}$")
|
colorRegex := regexp.MustCompile("^[0-9A-F]{3}$")
|
||||||
if !colorRegex.MatchString(c.Options.Image.View.Color.Foreground) {
|
if !colorRegex.MatchString(c.Options.ForegroundColor) {
|
||||||
return errors.New("foreground color must have color format in hexadecimal: [0-9A-F]{3}")
|
return errors.New("foreground color must have color format in hexadecimal: [0-9A-F]{3}")
|
||||||
}
|
}
|
||||||
|
|
||||||
if !colorRegex.MatchString(c.Options.Image.View.Color.Background) {
|
if !colorRegex.MatchString(c.Options.BackgroundColor) {
|
||||||
return errors.New("background color must have color format in hexadecimal: [0-9A-F]{3}")
|
return errors.New("background color must have color format in hexadecimal: [0-9A-F]{3}")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format
|
// Format
|
||||||
if !slices.Contains([]string{"jpeg", "png", "copy"}, c.Options.Image.Format) {
|
if !(c.Options.Format == "jpeg" || c.Options.Format == "png") {
|
||||||
return errors.New("format should be jpeg, png or copy")
|
return errors.New("format should be jpeg or png")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aspect Ratio
|
// Aspect Ratio
|
||||||
if c.Options.Image.View.AspectRatio < 0 && c.Options.Image.View.AspectRatio != -1 {
|
if c.Options.AspectRatio < 0 && c.Options.AspectRatio != -1 {
|
||||||
return errors.New("aspect ratio should be -1, 0 or > 0")
|
return errors.New("aspect ratio should be -1, 0 or > 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -395,12 +387,12 @@ func (c *Converter) Validate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Grayscale Mode
|
// Grayscale Mode
|
||||||
if c.Options.Image.GrayScaleMode < 0 || c.Options.Image.GrayScaleMode > 2 {
|
if c.Options.GrayscaleMode < 0 || c.Options.GrayscaleMode > 2 {
|
||||||
return errors.New("grayscale mode should be 0, 1 or 2")
|
return errors.New("grayscale mode should be 0, 1 or 2")
|
||||||
}
|
}
|
||||||
|
|
||||||
// crop
|
// crop
|
||||||
if c.Options.Image.Crop.Limit < 0 || c.Options.Image.Crop.Limit > 100 {
|
if c.Options.CropLimit < 0 || c.Options.CropLimit > 100 {
|
||||||
return errors.New("crop limit should be between 0 and 100")
|
return errors.New("crop limit should be between 0 and 100")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -410,7 +402,8 @@ func (c *Converter) Validate() error {
|
|||||||
// Fatal Helper to show usage, err and exit 1
|
// Fatal 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()
|
||||||
utils.Fatalf("\nError: %s\n", err)
|
utils.Printf("\nError: %s\n", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Converter) Stats() {
|
func (c *Converter) Stats() {
|
@ -1,27 +1,27 @@
|
|||||||
package converter
|
package converter
|
||||||
|
|
||||||
// Name or Section
|
// Name or Section
|
||||||
type order interface {
|
type converterOrder interface {
|
||||||
Value() string
|
Value() string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Section
|
// Section
|
||||||
type orderSection struct {
|
type converterOrderSection struct {
|
||||||
value string
|
value string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s orderSection) Value() string {
|
func (s converterOrderSection) Value() string {
|
||||||
return s.value
|
return s.value
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name
|
// Name
|
||||||
//
|
//
|
||||||
// isString is used to quote the default value.
|
// isString is used to quote the default value.
|
||||||
type orderName struct {
|
type converterOrderName struct {
|
||||||
value string
|
value string
|
||||||
isString bool
|
isString bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s orderName) Value() string {
|
func (s converterOrderName) Value() string {
|
||||||
return s.value
|
return s.value
|
||||||
}
|
}
|
337
internal/converter/options/converter_options.go
Normal file
337
internal/converter/options/converter_options.go
Normal file
@ -0,0 +1,337 @@
|
|||||||
|
// Package options manage options with default value from config.
|
||||||
|
package options
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
"github.com/celogeek/go-comic-converter/v2/internal/converter/profiles"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
// Output
|
||||||
|
Input string `yaml:"-"`
|
||||||
|
Output string `yaml:"-"`
|
||||||
|
Author string `yaml:"-"`
|
||||||
|
Title string `yaml:"-"`
|
||||||
|
|
||||||
|
// Config
|
||||||
|
Profile string `yaml:"profile"`
|
||||||
|
Quality int `yaml:"quality"`
|
||||||
|
Grayscale bool `yaml:"grayscale"`
|
||||||
|
GrayscaleMode int `yaml:"grayscale_mode"` // 0 = normal, 1 = average, 2 = luminance
|
||||||
|
Crop bool `yaml:"crop"`
|
||||||
|
CropRatioLeft int `yaml:"crop_ratio_left"`
|
||||||
|
CropRatioUp int `yaml:"crop_ratio_up"`
|
||||||
|
CropRatioRight int `yaml:"crop_ratio_right"`
|
||||||
|
CropRatioBottom int `yaml:"crop_ratio_bottom"`
|
||||||
|
CropLimit int `yaml:"crop_limit"`
|
||||||
|
CropSkipIfLimitReached bool `yaml:"crop_skip_if_limit_reached"`
|
||||||
|
Brightness int `yaml:"brightness"`
|
||||||
|
Contrast int `yaml:"contrast"`
|
||||||
|
AutoContrast bool `yaml:"auto_contrast"`
|
||||||
|
AutoRotate bool `yaml:"auto_rotate"`
|
||||||
|
AutoSplitDoublePage bool `yaml:"auto_split_double_page"`
|
||||||
|
KeepDoublePageIfSplit bool `yaml:"keep_double_page_if_split"`
|
||||||
|
NoBlankImage bool `yaml:"no_blank_image"`
|
||||||
|
Manga bool `yaml:"manga"`
|
||||||
|
HasCover bool `yaml:"has_cover"`
|
||||||
|
LimitMb int `yaml:"limit_mb"`
|
||||||
|
StripFirstDirectoryFromToc bool `yaml:"strip_first_directory_from_toc"`
|
||||||
|
SortPathMode int `yaml:"sort_path_mode"`
|
||||||
|
ForegroundColor string `yaml:"foreground_color"`
|
||||||
|
BackgroundColor string `yaml:"background_color"`
|
||||||
|
NoResize bool `yaml:"noresize"`
|
||||||
|
Format string `yaml:"format"`
|
||||||
|
AspectRatio float64 `yaml:"aspect_ratio"`
|
||||||
|
PortraitOnly bool `yaml:"portrait_only"`
|
||||||
|
AppleBookCompatibility bool `yaml:"apple_book_compatibility"`
|
||||||
|
TitlePage int `yaml:"title_page"`
|
||||||
|
|
||||||
|
// Default Config
|
||||||
|
Show bool `yaml:"-"`
|
||||||
|
Save bool `yaml:"-"`
|
||||||
|
Reset bool `yaml:"-"`
|
||||||
|
|
||||||
|
// Shortcut
|
||||||
|
Auto bool `yaml:"-"`
|
||||||
|
NoFilter bool `yaml:"-"`
|
||||||
|
MaxQuality bool `yaml:"-"`
|
||||||
|
BestQuality bool `yaml:"-"`
|
||||||
|
GreatQuality bool `yaml:"-"`
|
||||||
|
GoodQuality bool `yaml:"-"`
|
||||||
|
|
||||||
|
// Other
|
||||||
|
Workers int `yaml:"-"`
|
||||||
|
Dry bool `yaml:"-"`
|
||||||
|
DryVerbose bool `yaml:"-"`
|
||||||
|
Quiet bool `yaml:"-"`
|
||||||
|
Json bool `yaml:"-"`
|
||||||
|
Version bool `yaml:"-"`
|
||||||
|
Help bool `yaml:"-"`
|
||||||
|
|
||||||
|
// Internal
|
||||||
|
profiles profiles.Profiles
|
||||||
|
}
|
||||||
|
|
||||||
|
// New Initialize default options.
|
||||||
|
func New() *Options {
|
||||||
|
return &Options{
|
||||||
|
Profile: "SR",
|
||||||
|
Quality: 85,
|
||||||
|
Grayscale: true,
|
||||||
|
Crop: true,
|
||||||
|
CropRatioLeft: 1,
|
||||||
|
CropRatioUp: 1,
|
||||||
|
CropRatioRight: 1,
|
||||||
|
CropRatioBottom: 3,
|
||||||
|
CropLimit: 10,
|
||||||
|
CropSkipIfLimitReached: true,
|
||||||
|
NoBlankImage: true,
|
||||||
|
HasCover: true,
|
||||||
|
KeepDoublePageIfSplit: true,
|
||||||
|
SortPathMode: 1,
|
||||||
|
ForegroundColor: "000",
|
||||||
|
BackgroundColor: "FFF",
|
||||||
|
Format: "jpeg",
|
||||||
|
TitlePage: 1,
|
||||||
|
profiles: profiles.New(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) Header() string {
|
||||||
|
return "Go Comic Converter\n\nOptions:"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) String() string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(o.Header())
|
||||||
|
for _, v := range []struct {
|
||||||
|
K string
|
||||||
|
V any
|
||||||
|
}{
|
||||||
|
{"Input", o.Input},
|
||||||
|
{"Output", o.Output},
|
||||||
|
{"Author", o.Author},
|
||||||
|
{"Title", o.Title},
|
||||||
|
{"Workers", o.Workers},
|
||||||
|
} {
|
||||||
|
b.WriteString(fmt.Sprintf("\n %-32s: %v", v.K, v.V))
|
||||||
|
}
|
||||||
|
b.WriteString(o.ShowConfig())
|
||||||
|
b.WriteRune('\n')
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) MarshalJSON() ([]byte, error) {
|
||||||
|
out := map[string]any{
|
||||||
|
"input": o.Input,
|
||||||
|
"output": o.Output,
|
||||||
|
"author": o.Author,
|
||||||
|
"title": o.Title,
|
||||||
|
"workers": o.Workers,
|
||||||
|
"profile": o.GetProfile(),
|
||||||
|
"format": o.Format,
|
||||||
|
"grayscale": o.Grayscale,
|
||||||
|
"crop": o.Crop,
|
||||||
|
"autocontrast": o.AutoContrast,
|
||||||
|
"autorotate": o.AutoRotate,
|
||||||
|
"noblankimage": o.NoBlankImage,
|
||||||
|
"manga": o.Manga,
|
||||||
|
"hascover": o.HasCover,
|
||||||
|
"stripfirstdirectoryfromtoc": o.StripFirstDirectoryFromToc,
|
||||||
|
"sortpathmode": o.SortPathMode,
|
||||||
|
"foregroundcolor": o.ForegroundColor,
|
||||||
|
"backgroundcolor": o.BackgroundColor,
|
||||||
|
"resize": !o.NoResize,
|
||||||
|
"aspectratio": o.AspectRatio,
|
||||||
|
"portraitonly": o.PortraitOnly,
|
||||||
|
"titlepage": o.TitlePage,
|
||||||
|
}
|
||||||
|
if o.Format == "jpeg" {
|
||||||
|
out["quality"] = o.Quality
|
||||||
|
}
|
||||||
|
if o.Grayscale {
|
||||||
|
out["grayscale_mode"] = o.GrayscaleMode
|
||||||
|
}
|
||||||
|
if o.Crop {
|
||||||
|
out["crop_ratio"] = map[string]any{
|
||||||
|
"left": o.CropRatioLeft,
|
||||||
|
"right": o.CropRatioRight,
|
||||||
|
"up": o.CropRatioUp,
|
||||||
|
"bottom": o.CropRatioBottom,
|
||||||
|
}
|
||||||
|
out["crop_limit"] = o.CropLimit
|
||||||
|
out["crop_skip_if_limit_reached"] = o.CropSkipIfLimitReached
|
||||||
|
}
|
||||||
|
if o.Brightness != 0 {
|
||||||
|
out["brightness"] = o.Brightness
|
||||||
|
}
|
||||||
|
if o.Contrast != 0 {
|
||||||
|
out["contrast"] = o.Contrast
|
||||||
|
}
|
||||||
|
if o.PortraitOnly || !o.AppleBookCompatibility {
|
||||||
|
out["autosplitdoublepage"] = o.AutoSplitDoublePage
|
||||||
|
if o.AutoSplitDoublePage {
|
||||||
|
out["keepdoublepageifsplit"] = o.KeepDoublePageIfSplit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if o.LimitMb != 0 {
|
||||||
|
out["limitmb"] = o.LimitMb
|
||||||
|
}
|
||||||
|
if !o.PortraitOnly {
|
||||||
|
out["applebookcompatibility"] = o.AppleBookCompatibility
|
||||||
|
}
|
||||||
|
return json.Marshal(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileName Config file: ~/.go-comic-converter.yaml
|
||||||
|
func (o *Options) FileName() string {
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".go-comic-converter.yaml")
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadConfig Load config files
|
||||||
|
func (o *Options) LoadConfig() error {
|
||||||
|
f, err := os.Open(o.FileName())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer func(f *os.File) {
|
||||||
|
_ = f.Close()
|
||||||
|
}(f)
|
||||||
|
err = yaml.NewDecoder(f).Decode(o)
|
||||||
|
if err != nil && err.Error() != "EOF" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShowConfig Get current settings for fields that can be saved
|
||||||
|
func (o *Options) ShowConfig() string {
|
||||||
|
var profileDesc string
|
||||||
|
profile := o.GetProfile()
|
||||||
|
if profile != nil {
|
||||||
|
profileDesc = fmt.Sprintf(
|
||||||
|
"%s - %s - %dx%d",
|
||||||
|
o.Profile,
|
||||||
|
profile.Description,
|
||||||
|
profile.Width,
|
||||||
|
profile.Height,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
sortpathmode := ""
|
||||||
|
switch o.SortPathMode {
|
||||||
|
case 0:
|
||||||
|
sortpathmode = "path=alpha, file=alpha"
|
||||||
|
case 1:
|
||||||
|
sortpathmode = "path=alphanumeric, file=alpha"
|
||||||
|
case 2:
|
||||||
|
sortpathmode = "path=alphanumeric, file=alphanumeric"
|
||||||
|
}
|
||||||
|
|
||||||
|
aspectRatio := "auto"
|
||||||
|
if o.AspectRatio > 0 {
|
||||||
|
aspectRatio = fmt.Sprintf("1:%.02f", o.AspectRatio)
|
||||||
|
} else if o.AspectRatio < 0 {
|
||||||
|
if profile != nil {
|
||||||
|
aspectRatio = fmt.Sprintf("1:%0.2f (device)", float64(profile.Height)/float64(profile.Width))
|
||||||
|
} else {
|
||||||
|
aspectRatio = "1:?? (device)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
titlePage := ""
|
||||||
|
switch o.TitlePage {
|
||||||
|
case 0:
|
||||||
|
titlePage = "never"
|
||||||
|
case 1:
|
||||||
|
titlePage = "always"
|
||||||
|
case 2:
|
||||||
|
titlePage = "when epub is split"
|
||||||
|
}
|
||||||
|
|
||||||
|
grayscaleMode := "normal"
|
||||||
|
switch o.GrayscaleMode {
|
||||||
|
case 1:
|
||||||
|
grayscaleMode = "average"
|
||||||
|
case 2:
|
||||||
|
grayscaleMode = "luminance"
|
||||||
|
}
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
for _, v := range []struct {
|
||||||
|
Key string
|
||||||
|
Value any
|
||||||
|
Condition bool
|
||||||
|
}{
|
||||||
|
{"Profile", profileDesc, true},
|
||||||
|
{"Format", o.Format, true},
|
||||||
|
{"Quality", o.Quality, o.Format == "jpeg"},
|
||||||
|
{"Grayscale", o.Grayscale, true},
|
||||||
|
{"Grayscale mode", grayscaleMode, o.Grayscale},
|
||||||
|
{"Crop", o.Crop, true},
|
||||||
|
{"Crop ratio", fmt.Sprintf("%d Left - %d Up - %d Right - %d Bottom - Limit %d%% - Skip %v", o.CropRatioLeft, o.CropRatioUp, o.CropRatioRight, o.CropRatioBottom, o.CropLimit, o.CropSkipIfLimitReached), o.Crop},
|
||||||
|
{"Brightness", o.Brightness, o.Brightness != 0},
|
||||||
|
{"Contrast", o.Contrast, o.Contrast != 0},
|
||||||
|
{"Auto contrast", o.AutoContrast, true},
|
||||||
|
{"Auto rotate", o.AutoRotate, true},
|
||||||
|
{"Auto split double page", o.AutoSplitDoublePage, o.PortraitOnly || !o.AppleBookCompatibility},
|
||||||
|
{"Keep double page if split", o.KeepDoublePageIfSplit, (o.PortraitOnly || !o.AppleBookCompatibility) && o.AutoSplitDoublePage},
|
||||||
|
{"No blank image", o.NoBlankImage, true},
|
||||||
|
{"Manga", o.Manga, true},
|
||||||
|
{"Has cover", o.HasCover, true},
|
||||||
|
{"Limit", fmt.Sprintf("%d Mb", o.LimitMb), o.LimitMb != 0},
|
||||||
|
{"Strip first directory from toc", o.StripFirstDirectoryFromToc, true},
|
||||||
|
{"Sort path mode", sortpathmode, true},
|
||||||
|
{"Foreground color", fmt.Sprintf("#%s", o.ForegroundColor), true},
|
||||||
|
{"Background color", fmt.Sprintf("#%s", o.BackgroundColor), true},
|
||||||
|
{"Resize", !o.NoResize, true},
|
||||||
|
{"Aspect ratio", aspectRatio, true},
|
||||||
|
{"Portrait only", o.PortraitOnly, true},
|
||||||
|
{"Title page", titlePage, true},
|
||||||
|
{"Apple book compatibility", o.AppleBookCompatibility, !o.PortraitOnly},
|
||||||
|
} {
|
||||||
|
if v.Condition {
|
||||||
|
b.WriteString(fmt.Sprintf("\n %-32s: %v", v.Key, v.Value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetConfig reset all settings to default value
|
||||||
|
func (o *Options) ResetConfig() error {
|
||||||
|
if err := New().SaveConfig(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return o.LoadConfig()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveConfig save all current settings as default value
|
||||||
|
func (o *Options) SaveConfig() error {
|
||||||
|
f, err := os.Create(o.FileName())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func(f *os.File) {
|
||||||
|
_ = f.Close()
|
||||||
|
}(f)
|
||||||
|
return yaml.NewEncoder(f).Encode(o)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetProfile shortcut to get current profile
|
||||||
|
func (o *Options) GetProfile() *profiles.Profile {
|
||||||
|
return o.profiles.Get(o.Profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AvailableProfiles all available profiles
|
||||||
|
func (o *Options) AvailableProfiles() string {
|
||||||
|
return o.profiles.String()
|
||||||
|
}
|
@ -1,11 +1,9 @@
|
|||||||
// Package converter profiles manage supported profiles for go-comic-converter.
|
// Package profiles manage supported profiles for go-comic-converter.
|
||||||
package converter
|
package profiles
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Profile struct {
|
type Profile struct {
|
||||||
@ -15,16 +13,11 @@ type Profile struct {
|
|||||||
Height int `json:"height"`
|
Height int `json:"height"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p Profile) String() string {
|
type Profiles []Profile
|
||||||
return p.Code + " - " + p.Description + " - " + utils.IntToString(p.Width) + "x" + utils.IntToString(p.Height)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Profiles map[string]Profile
|
// New Initialize list of all supported profiles.
|
||||||
|
func New() Profiles {
|
||||||
// NewProfiles Initialize list of all supported profiles.
|
return []Profile{
|
||||||
func NewProfiles() Profiles {
|
|
||||||
res := make(Profiles)
|
|
||||||
for _, r := range []Profile{
|
|
||||||
// High Resolution for Tablet
|
// High Resolution for Tablet
|
||||||
{"HR", "High Resolution", 2400, 3840},
|
{"HR", "High Resolution", 2400, 3840},
|
||||||
{"SR", "Standard Resolution", 1200, 1920},
|
{"SR", "Standard Resolution", 1200, 1920},
|
||||||
@ -57,21 +50,28 @@ func NewProfiles() Profiles {
|
|||||||
// reMarkable
|
// reMarkable
|
||||||
{"RM1", "reMarkable 1", 1404, 1872},
|
{"RM1", "reMarkable 1", 1404, 1872},
|
||||||
{"RM2", "reMarkable 2", 1404, 1872},
|
{"RM2", "reMarkable 2", 1404, 1872},
|
||||||
} {
|
|
||||||
res[r.Code] = r
|
|
||||||
}
|
}
|
||||||
return res
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p Profiles) String() string {
|
func (p Profiles) 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(
|
||||||
" - %-7s - %4d x %-4d - %s",
|
" - %-7s ( %9s ) - %s",
|
||||||
v.Code,
|
v.Code,
|
||||||
v.Width, v.Height,
|
fmt.Sprintf("%dx%d", v.Width, v.Height),
|
||||||
v.Description,
|
v.Description,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
return strings.Join(s, "\n")
|
return strings.Join(s, "\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get Lookup profile by code
|
||||||
|
func (p Profiles) Get(name string) *Profile {
|
||||||
|
for _, profile := range p {
|
||||||
|
if profile.Code == name {
|
||||||
|
return &profile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
@ -14,38 +14,34 @@ import (
|
|||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
|
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimagepassthrough"
|
epubimageprocessor "github.com/celogeek/go-comic-converter/v2/internal/epub/imageprocessor"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimageprocessor"
|
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubprogress"
|
epubprogress "github.com/celogeek/go-comic-converter/v2/internal/epub/progress"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubtemplates"
|
epubtemplates "github.com/celogeek/go-comic-converter/v2/internal/epub/templates"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubtree"
|
epubtree "github.com/celogeek/go-comic-converter/v2/internal/epub/tree"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubzip"
|
epubzip "github.com/celogeek/go-comic-converter/v2/internal/epub/zip"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type EPUB interface {
|
type EPub struct {
|
||||||
Write() error
|
*epuboptions.Options
|
||||||
}
|
|
||||||
|
|
||||||
type epub struct {
|
|
||||||
epuboptions.EPUBOptions
|
|
||||||
UID string
|
UID string
|
||||||
Publisher string
|
Publisher string
|
||||||
UpdatedAt string
|
UpdatedAt string
|
||||||
|
|
||||||
templateProcessor *template.Template
|
templateProcessor *template.Template
|
||||||
imageProcessor epubimageprocessor.EPUBImageProcessor
|
imageProcessor *epubimageprocessor.EPUBImageProcessor
|
||||||
}
|
}
|
||||||
|
|
||||||
type epubPart struct {
|
type epubPart struct {
|
||||||
Cover epubimage.EPUBImage
|
Cover *epubimage.Image
|
||||||
Images []epubimage.EPUBImage
|
Images []*epubimage.Image
|
||||||
|
Reader *zip.ReadCloser
|
||||||
}
|
}
|
||||||
|
|
||||||
// New initialize EPUB
|
// New initialize EPUB
|
||||||
func New(options epuboptions.EPUBOptions) EPUB {
|
func New(options *epuboptions.Options) *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{
|
||||||
@ -53,25 +49,18 @@ func New(options epuboptions.EPUBOptions) EPUB {
|
|||||||
"zoom": func(s int, z float32) int { return int(float32(s) * z) },
|
"zoom": func(s int, z float32) int { return int(float32(s) * z) },
|
||||||
})
|
})
|
||||||
|
|
||||||
var imageProcessor epubimageprocessor.EPUBImageProcessor
|
return &EPub{
|
||||||
if options.Image.Format == "copy" {
|
Options: options,
|
||||||
imageProcessor = epubimagepassthrough.New(options)
|
|
||||||
} else {
|
|
||||||
imageProcessor = epubimageprocessor.New(options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return epub{
|
|
||||||
EPUBOptions: 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: imageProcessor,
|
imageProcessor: epubimageprocessor.New(options),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// render templates
|
// render templates
|
||||||
func (e epub) render(templateString string, data map[string]any) string {
|
func (e *EPub) render(templateString string, data map[string]any) string {
|
||||||
var result strings.Builder
|
var result strings.Builder
|
||||||
tmpl := template.Must(e.templateProcessor.Parse(templateString))
|
tmpl := template.Must(e.templateProcessor.Parse(templateString))
|
||||||
if err := tmpl.Execute(&result, data); err != nil {
|
if err := tmpl.Execute(&result, data); err != nil {
|
||||||
@ -81,12 +70,12 @@ 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.EPUBImage, zipImg *zip.File) error {
|
func (e *EPub) writeImage(wz *epubzip.EPUBZip, img *epubimage.Image, 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": "Image " + utils.IntToString(img.Id) + " Part " + utils.IntToString(img.Part),
|
"Title": fmt.Sprintf("Image %d Part %d", img.Id, img.Part),
|
||||||
"ViewPort": e.Image.View.Port(),
|
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height),
|
||||||
"ImagePath": img.ImgPath(),
|
"ImagePath": img.ImgPath(),
|
||||||
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""),
|
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""),
|
||||||
})),
|
})),
|
||||||
@ -99,38 +88,38 @@ func (e epub) writeImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, zipImg *zi
|
|||||||
}
|
}
|
||||||
|
|
||||||
// write blank page
|
// write blank page
|
||||||
func (e epub) writeBlank(wz epubzip.EPUBZip, img epubimage.EPUBImage) error {
|
func (e *EPub) writeBlank(wz *epubzip.EPUBZip, img *epubimage.Image) 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": "Blank Page " + utils.IntToString(img.Id),
|
"Title": fmt.Sprintf("Blank Page %d", img.Id),
|
||||||
"ViewPort": e.Image.View.Port(),
|
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height),
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// write title image
|
// write title image
|
||||||
func (e epub) writeCoverImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, part, totalParts int) error {
|
func (e *EPub) writeCoverImage(wz *epubzip.EPUBZip, img *epubimage.Image, part, totalParts int) error {
|
||||||
title := "Cover"
|
title := "Cover"
|
||||||
text := ""
|
text := ""
|
||||||
if totalParts > 1 {
|
if totalParts > 1 {
|
||||||
text = utils.IntToString(part) + " / " + utils.IntToString(totalParts)
|
text = fmt.Sprintf("%d / %d", part, totalParts)
|
||||||
title = title + " " + text
|
title = fmt.Sprintf("%s %s", title, text)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := wz.WriteContent(
|
if err := wz.WriteContent(
|
||||||
"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": e.Image.View.Port(),
|
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height),
|
||||||
"ImagePath": "Images/cover.jpeg",
|
"ImagePath": fmt.Sprintf("Images/cover.%s", e.Image.Format),
|
||||||
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""),
|
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""),
|
||||||
})),
|
})),
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
coverTitle, err := e.imageProcessor.CoverTitleData(epubimageprocessor.CoverTitleDataOptions{
|
coverTitle, err := e.imageProcessor.CoverTitleData(&epubimageprocessor.CoverTitleDataOptions{
|
||||||
Src: img.Raw,
|
Src: img.Raw,
|
||||||
Name: "cover",
|
Name: "cover",
|
||||||
Text: text,
|
Text: text,
|
||||||
@ -153,7 +142,7 @@ func (e epub) writeCoverImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, part,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// write title image
|
// write title image
|
||||||
func (e epub) writeTitleImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, title string) error {
|
func (e *EPub) writeTitleImage(wz *epubzip.EPUBZip, img *epubimage.Image, title string) error {
|
||||||
titleAlign := ""
|
titleAlign := ""
|
||||||
if !e.Image.View.PortraitOnly {
|
if !e.Image.View.PortraitOnly {
|
||||||
if e.Image.Manga {
|
if e.Image.Manga {
|
||||||
@ -168,7 +157,7 @@ func (e epub) writeTitleImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, title
|
|||||||
"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": e.Image.View.Port(),
|
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height),
|
||||||
})),
|
})),
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return err
|
return err
|
||||||
@ -179,15 +168,15 @@ func (e epub) writeTitleImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, 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": e.Image.View.Port(),
|
"ViewPort": fmt.Sprintf("width=%d,height=%d", e.Image.View.Width, e.Image.View.Height),
|
||||||
"ImagePath": "Images/title.jpeg",
|
"ImagePath": fmt.Sprintf("Images/title.%s", e.Image.Format),
|
||||||
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, titleAlign),
|
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, titleAlign),
|
||||||
})),
|
})),
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
coverTitle, err := e.imageProcessor.CoverTitleData(epubimageprocessor.CoverTitleDataOptions{
|
coverTitle, err := e.imageProcessor.CoverTitleData(&epubimageprocessor.CoverTitleDataOptions{
|
||||||
Src: img.Raw,
|
Src: img.Raw,
|
||||||
Name: "title",
|
Name: "title",
|
||||||
Text: title,
|
Text: title,
|
||||||
@ -209,11 +198,11 @@ func (e epub) writeTitleImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, title
|
|||||||
}
|
}
|
||||||
|
|
||||||
// extract image and split it into part
|
// extract image and split it into part
|
||||||
func (e epub) getParts() (parts []epubPart, imgStorage epubzip.StorageImageReader, err error) {
|
func (e *EPub) getParts() (parts []*epubPart, imgStorage *epubzip.StorageImageReader, err error) {
|
||||||
images, err := e.imageProcessor.Load()
|
images, err := e.imageProcessor.Load()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort result by id and part
|
// sort result by id and part
|
||||||
@ -224,23 +213,23 @@ func (e epub) getParts() (parts []epubPart, imgStorage epubzip.StorageImageReade
|
|||||||
return images[i].Id < images[j].Id
|
return images[i].Id < images[j].Id
|
||||||
})
|
})
|
||||||
|
|
||||||
parts = make([]epubPart, 0)
|
parts = make([]*epubPart, 0)
|
||||||
cover := images[0]
|
cover := images[0]
|
||||||
if e.Image.HasCover || (cover.DoublePage && !e.Image.KeepDoublePageIfSplit) {
|
if e.Image.HasCover {
|
||||||
images = images[1:]
|
images = images[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if e.Dry {
|
if e.Dry {
|
||||||
parts = append(parts, epubPart{
|
parts = append(parts, &epubPart{
|
||||||
Cover: cover,
|
Cover: cover,
|
||||||
Images: images,
|
Images: images,
|
||||||
})
|
})
|
||||||
return
|
return parts, nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
imgStorage, err = epubzip.NewStorageImageReader(e.ImgStorage())
|
imgStorage, err = epubzip.NewStorageImageReader(e.ImgStorage())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
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
|
||||||
@ -250,37 +239,37 @@ func (e epub) getParts() (parts []epubPart, imgStorage epubzip.StorageImageReade
|
|||||||
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.EPUBImage, 0)
|
currentImages := make([]*epubimage.Image, 0)
|
||||||
part := 1
|
part := 1
|
||||||
|
|
||||||
for _, img := range images {
|
for _, img := range images {
|
||||||
imgSize := imgStorage.Size(img.EPUBImgPath()) + xhtmlSize
|
imgSize := imgStorage.Size(img.EPUBImgPath()) + xhtmlSize
|
||||||
if maxSize > 0 && len(currentImages) > 0 && currentSize+imgSize > maxSize {
|
if maxSize > 0 && len(currentImages) > 0 && currentSize+imgSize > maxSize {
|
||||||
parts = append(parts, epubPart{
|
parts = append(parts, &epubPart{
|
||||||
Cover: cover,
|
Cover: cover,
|
||||||
Images: currentImages,
|
Images: currentImages,
|
||||||
})
|
})
|
||||||
part += 1
|
part += 1
|
||||||
currentSize = baseSize
|
currentSize = baseSize
|
||||||
currentImages = make([]epubimage.EPUBImage, 0)
|
currentImages = make([]*epubimage.Image, 0)
|
||||||
}
|
}
|
||||||
currentSize += imgSize
|
currentSize += imgSize
|
||||||
currentImages = append(currentImages, img)
|
currentImages = append(currentImages, img)
|
||||||
}
|
}
|
||||||
if len(currentImages) > 0 {
|
if len(currentImages) > 0 {
|
||||||
parts = append(parts, epubPart{
|
parts = append(parts, &epubPart{
|
||||||
Cover: cover,
|
Cover: cover,
|
||||||
Images: currentImages,
|
Images: currentImages,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return parts, imgStorage, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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.EPUBImage, skipFiles bool) string {
|
func (e *EPub) getTree(images []*epubimage.Image, skipFiles bool) string {
|
||||||
t := epubtree.New()
|
t := epubtree.New()
|
||||||
for _, img := range images {
|
for _, img := range images {
|
||||||
if skipFiles {
|
if skipFiles {
|
||||||
@ -297,7 +286,7 @@ func (e epub) getTree(images []epubimage.EPUBImage, skipFiles bool) string {
|
|||||||
return c.WriteString("")
|
return c.WriteString("")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e epub) computeAspectRatio(epubParts []epubPart) float64 {
|
func (e *EPub) computeAspectRatio(epubParts []*epubPart) float64 {
|
||||||
var (
|
var (
|
||||||
bestAspectRatio float64
|
bestAspectRatio float64
|
||||||
bestAspectRatioCount int
|
bestAspectRatioCount int
|
||||||
@ -324,10 +313,9 @@ func (e epub) computeAspectRatio(epubParts []epubPart) float64 {
|
|||||||
return bestAspectRatio
|
return bestAspectRatio
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e epub) computeViewPort(epubParts []epubPart) (int, int) {
|
func (e *EPub) computeViewPort(epubParts []*epubPart) {
|
||||||
if e.Image.View.AspectRatio == -1 {
|
if e.Image.View.AspectRatio == -1 {
|
||||||
//keep device size
|
return //keep device size
|
||||||
return e.Image.View.Width, e.Image.View.Height
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// readjusting view port
|
// readjusting view port
|
||||||
@ -338,26 +326,26 @@ func (e epub) computeViewPort(epubParts []epubPart) (int, int) {
|
|||||||
|
|
||||||
viewWidth, viewHeight := int(float64(e.Image.View.Height)/bestAspectRatio), int(float64(e.Image.View.Width)*bestAspectRatio)
|
viewWidth, viewHeight := int(float64(e.Image.View.Height)/bestAspectRatio), int(float64(e.Image.View.Width)*bestAspectRatio)
|
||||||
if viewWidth > e.Image.View.Width {
|
if viewWidth > e.Image.View.Width {
|
||||||
return e.Image.View.Width, viewHeight
|
e.Image.View.Height = viewHeight
|
||||||
} else {
|
} else {
|
||||||
return viewWidth, e.Image.View.Height
|
e.Image.View.Width = viewWidth
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e epub) writePart(path string, currentPart, totalParts int, part epubPart, imgStorage epubzip.StorageImageReader) error {
|
func (e *EPub) writePart(path string, currentPart, totalParts int, part *epubPart, imgStorage *epubzip.StorageImageReader) error {
|
||||||
hasTitlePage := e.TitlePage == 1 || (e.TitlePage == 2 && totalParts > 1)
|
hasTitlePage := e.TitlePage == 1 || (e.TitlePage == 2 && totalParts > 1)
|
||||||
|
|
||||||
wz, err := epubzip.New(path)
|
wz, err := epubzip.New(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer func(wz epubzip.EPUBZip) {
|
defer func(wz *epubzip.EPUBZip) {
|
||||||
_ = wz.Close()
|
_ = wz.Close()
|
||||||
}(wz)
|
}(wz)
|
||||||
|
|
||||||
title := e.Title
|
title := e.Title
|
||||||
if totalParts > 1 {
|
if totalParts > 1 {
|
||||||
title = title + " [" + utils.IntToString(currentPart) + "/" + utils.IntToString(totalParts) + "]"
|
title = fmt.Sprintf("%s [%d/%d]", title, currentPart, totalParts)
|
||||||
}
|
}
|
||||||
|
|
||||||
type zipContent struct {
|
type zipContent struct {
|
||||||
@ -367,7 +355,7 @@ func (e epub) writePart(path string, currentPart, totalParts int, part epubPart,
|
|||||||
content := []zipContent{
|
content := []zipContent{
|
||||||
{"META-INF/container.xml", epubtemplates.Container},
|
{"META-INF/container.xml", epubtemplates.Container},
|
||||||
{"META-INF/com.apple.ibooks.display-options.xml", epubtemplates.AppleBooks},
|
{"META-INF/com.apple.ibooks.display-options.xml", epubtemplates.AppleBooks},
|
||||||
{"OEBPS/content.opf", epubtemplates.Content{
|
{"OEBPS/content.opf", epubtemplates.Content(&epubtemplates.ContentOptions{
|
||||||
Title: title,
|
Title: title,
|
||||||
HasTitlePage: hasTitlePage,
|
HasTitlePage: hasTitlePage,
|
||||||
UID: e.UID,
|
UID: e.UID,
|
||||||
@ -379,7 +367,7 @@ func (e epub) writePart(path string, currentPart, totalParts int, part epubPart,
|
|||||||
Images: part.Images,
|
Images: part.Images,
|
||||||
Current: currentPart,
|
Current: currentPart,
|
||||||
Total: totalParts,
|
Total: totalParts,
|
||||||
}.String()},
|
})},
|
||||||
{"OEBPS/toc.xhtml", epubtemplates.Toc(title, hasTitlePage, e.StripFirstDirectoryFromToc, part.Images)},
|
{"OEBPS/toc.xhtml", epubtemplates.Toc(title, hasTitlePage, e.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.Image.View,
|
||||||
@ -425,7 +413,7 @@ func (e epub) writePart(path string, currentPart, totalParts int, part epubPart,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// create the zip
|
// create the zip
|
||||||
func (e epub) Write() error {
|
func (e *EPub) Write() error {
|
||||||
epubParts, imgStorage, err := e.getParts()
|
epubParts, imgStorage, err := e.getParts()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -436,7 +424,7 @@ func (e epub) Write() error {
|
|||||||
utils.Printf("TOC:\n - %s\n%s\n", e.Title, e.getTree(p.Images, true))
|
utils.Printf("TOC:\n - %s\n%s\n", e.Title, e.getTree(p.Images, true))
|
||||||
if e.DryVerbose {
|
if e.DryVerbose {
|
||||||
if e.Image.HasCover {
|
if e.Image.HasCover {
|
||||||
utils.Printf("Cover:\n%s\n", e.getTree([]epubimage.EPUBImage{p.Cover}, false))
|
utils.Printf("Cover:\n%s\n", e.getTree([]*epubimage.Image{p.Cover}, false))
|
||||||
}
|
}
|
||||||
utils.Printf("Files:\n%s\n", e.getTree(p.Images, false))
|
utils.Printf("Files:\n%s\n", e.getTree(p.Images, false))
|
||||||
}
|
}
|
||||||
@ -458,17 +446,17 @@ func (e epub) Write() error {
|
|||||||
Json: e.Json,
|
Json: e.Json,
|
||||||
})
|
})
|
||||||
|
|
||||||
e.Image.View.Width, e.Image.View.Height = e.computeViewPort(epubParts)
|
e.computeViewPort(epubParts)
|
||||||
for i, part := range epubParts {
|
for i, part := range epubParts {
|
||||||
ext := filepath.Ext(e.Output)
|
ext := filepath.Ext(e.Output)
|
||||||
suffix := ""
|
suffix := ""
|
||||||
if totalParts > 1 {
|
if totalParts > 1 {
|
||||||
fmtLen := utils.FormatNumberOfDigits(totalParts)
|
fmtLen := len(fmt.Sprint(totalParts))
|
||||||
fmtPart := "Part " + fmtLen + " of " + fmtLen
|
fmtPart := fmt.Sprintf(" Part %%0%dd of %%0%dd", fmtLen, fmtLen)
|
||||||
suffix = fmt.Sprintf(fmtPart, i+1, totalParts)
|
suffix = fmt.Sprintf(fmtPart, i+1, totalParts)
|
||||||
}
|
}
|
||||||
|
|
||||||
path := e.Output[0:len(e.Output)-len(ext)] + suffix + ext
|
path := fmt.Sprintf("%s%s%s", e.Output[0:len(e.Output)-len(ext)], suffix, ext)
|
||||||
|
|
||||||
if err := e.writePart(
|
if err := e.writePart(
|
||||||
path,
|
path,
|
@ -1,14 +1,13 @@
|
|||||||
// Package epubimage EPUBImage helpers to transform image.
|
// Package epubimage Image helpers to transform image.
|
||||||
package epubimage
|
package epubimage
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"image"
|
"image"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type EPUBImage struct {
|
type Image struct {
|
||||||
Id int
|
Id int
|
||||||
Part int
|
Part int
|
||||||
Raw image.Image
|
Raw image.Image
|
||||||
@ -25,72 +24,63 @@ type EPUBImage struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SpaceKey key name of the blank page after the image
|
// SpaceKey key name of the blank page after the image
|
||||||
func (i EPUBImage) SpaceKey() string {
|
func (i *Image) SpaceKey() string {
|
||||||
return "space_" + utils.IntToString(i.Id)
|
return fmt.Sprintf("space_%d", i.Id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpacePath path of the blank page
|
// SpacePath path of the blank page
|
||||||
func (i EPUBImage) SpacePath() string {
|
func (i *Image) SpacePath() string {
|
||||||
return "Text/" + i.SpaceKey() + ".xhtml"
|
return fmt.Sprintf("Text/%s.xhtml", i.SpaceKey())
|
||||||
}
|
}
|
||||||
|
|
||||||
// EPUBSpacePath path of the blank page into the EPUB
|
// EPUBSpacePath path of the blank page into the EPUB
|
||||||
func (i EPUBImage) EPUBSpacePath() string {
|
func (i *Image) EPUBSpacePath() string {
|
||||||
return "OEBPS/" + i.SpacePath()
|
return fmt.Sprintf("OEBPS/%s", i.SpacePath())
|
||||||
}
|
|
||||||
|
|
||||||
func (i EPUBImage) PartKey() string {
|
|
||||||
return utils.IntToString(i.Id) + "_p" + utils.IntToString(i.Part)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PageKey key for page
|
// PageKey key for page
|
||||||
func (i EPUBImage) PageKey() string {
|
func (i *Image) PageKey() string {
|
||||||
return "page_" + i.PartKey()
|
return fmt.Sprintf("page_%d_p%d", i.Id, i.Part)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PagePath page path linked to the image
|
// PagePath page path linked to the image
|
||||||
func (i EPUBImage) PagePath() string {
|
func (i *Image) PagePath() string {
|
||||||
return "Text/" + i.PageKey() + ".xhtml"
|
return fmt.Sprintf("Text/%s.xhtml", i.PageKey())
|
||||||
}
|
}
|
||||||
|
|
||||||
// EPUBPagePath page path into the EPUB
|
// EPUBPagePath page path into the EPUB
|
||||||
func (i EPUBImage) EPUBPagePath() string {
|
func (i *Image) EPUBPagePath() string {
|
||||||
return "OEBPS/" + i.PagePath()
|
return fmt.Sprintf("OEBPS/%s", i.PagePath())
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImgKey key for image
|
// ImgKey key for image
|
||||||
func (i EPUBImage) ImgKey() string {
|
func (i *Image) ImgKey() string {
|
||||||
return "img_" + i.PartKey()
|
return fmt.Sprintf("img_%d_p%d", i.Id, i.Part)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImgPath image path
|
// ImgPath image path
|
||||||
func (i EPUBImage) ImgPath() string {
|
func (i *Image) ImgPath() string {
|
||||||
return "Images/" + i.ImgKey() + "." + i.Format
|
return fmt.Sprintf("Images/%s.%s", i.ImgKey(), i.Format)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EPUBImgPath image path into the EPUB
|
// EPUBImgPath image path into the EPUB
|
||||||
func (i EPUBImage) EPUBImgPath() string {
|
func (i *Image) EPUBImgPath() string {
|
||||||
return "OEBPS/" + i.ImgPath()
|
return fmt.Sprintf("OEBPS/%s", i.ImgPath())
|
||||||
}
|
|
||||||
|
|
||||||
// MediaType of the epub image
|
|
||||||
func (i EPUBImage) MediaType() string {
|
|
||||||
return "image/" + i.Format
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImgStyle style to apply to the image.
|
// ImgStyle style to apply to the image.
|
||||||
//
|
//
|
||||||
// center by default.
|
// center by default.
|
||||||
// align to left or right if it's part of the split double page.
|
// align to left or right if it's part of the split double page.
|
||||||
func (i EPUBImage) ImgStyle(viewWidth, viewHeight int, align string) string {
|
func (i *Image) 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
|
||||||
|
|
||||||
style := make([]string, 0, 4)
|
var style []string
|
||||||
|
|
||||||
style = append(style, "width:"+utils.IntToString(relWidth)+"px")
|
style = append(style, fmt.Sprintf("width:%dpx", relWidth))
|
||||||
style = append(style, "height:"+utils.IntToString(relHeight)+"px")
|
style = append(style, fmt.Sprintf("height:%dpx", relHeight))
|
||||||
style = append(style, "top:"+utils.FloatToString(marginH*100/float64(viewHeight), 2)+"%")
|
style = append(style, fmt.Sprintf("top:%.2f%%", marginH*100/float64(viewHeight)))
|
||||||
if align == "" {
|
if align == "" {
|
||||||
switch i.Position {
|
switch i.Position {
|
||||||
case "rendition:page-spread-left":
|
case "rendition:page-spread-left":
|
||||||
@ -98,7 +88,7 @@ func (i EPUBImage) ImgStyle(viewWidth, viewHeight int, align string) string {
|
|||||||
case "rendition:page-spread-right":
|
case "rendition:page-spread-right":
|
||||||
style = append(style, "left:0")
|
style = append(style, "left:0")
|
||||||
default:
|
default:
|
||||||
style = append(style, "left:"+utils.FloatToString(marginW*100/float64(viewWidth), 2)+"%")
|
style = append(style, fmt.Sprintf("left:%.2f%%", marginW*100/float64(viewWidth)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
style = append(style, align)
|
style = append(style, align)
|
||||||
@ -107,7 +97,7 @@ func (i EPUBImage) ImgStyle(viewWidth, viewHeight int, align string) string {
|
|||||||
return strings.Join(style, "; ")
|
return strings.Join(style, "; ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i EPUBImage) RelSize(viewWidth, viewHeight int) (relWidth, relHeight int) {
|
func (i *Image) 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
|
||||||
|
|
@ -10,14 +10,14 @@ import (
|
|||||||
|
|
||||||
// AutoContrast Automatically improve contrast
|
// AutoContrast Automatically improve contrast
|
||||||
func AutoContrast() gift.Filter {
|
func AutoContrast() gift.Filter {
|
||||||
return autocontrast{}
|
return &autocontrast{}
|
||||||
}
|
}
|
||||||
|
|
||||||
type autocontrast struct {
|
type autocontrast struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// compute the color number between 0 and 1 that hold half of the pixel
|
// compute the color number between 0 and 1 that hold half of the pixel
|
||||||
func (f autocontrast) mean(src image.Image) float32 {
|
func (f *autocontrast) mean(src image.Image) float32 {
|
||||||
bucket := map[int]int{}
|
bucket := map[int]int{}
|
||||||
for x := src.Bounds().Min.X; x < src.Bounds().Max.X; x++ {
|
for x := src.Bounds().Min.X; x < src.Bounds().Max.X; x++ {
|
||||||
for y := src.Bounds().Min.Y; y < src.Bounds().Max.Y; y++ {
|
for y := src.Bounds().Min.Y; y < src.Bounds().Max.Y; y++ {
|
||||||
@ -44,7 +44,7 @@ func (f autocontrast) mean(src image.Image) float32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ensure value stay into 0 to 1 bound
|
// ensure value stay into 0 to 1 bound
|
||||||
func (f autocontrast) cap(v float32) float32 {
|
func (f *autocontrast) cap(v float32) float32 {
|
||||||
if v < 0 {
|
if v < 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@ -55,12 +55,12 @@ func (f autocontrast) cap(v float32) float32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// power of 2 for float32
|
// power of 2 for float32
|
||||||
func (f autocontrast) pow2(v float32) float32 {
|
func (f *autocontrast) pow2(v float32) float32 {
|
||||||
return v * v
|
return v * v
|
||||||
}
|
}
|
||||||
|
|
||||||
// Draw into the dst after applying the filter
|
// Draw into the dst after applying the filter
|
||||||
func (f autocontrast) Draw(dst draw.Image, src image.Image, options *gift.Options) {
|
func (f *autocontrast) Draw(dst draw.Image, src image.Image, options *gift.Options) {
|
||||||
// half of the pixel has this color idx
|
// half of the pixel has this color idx
|
||||||
colorMean := f.mean(src)
|
colorMean := f.mean(src)
|
||||||
|
|
||||||
@ -84,7 +84,7 @@ func (f autocontrast) Draw(dst draw.Image, src image.Image, options *gift.Option
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Bounds calculates the appropriate bounds of an image after applying the filter.
|
// Bounds calculates the appropriate bounds of an image after applying the filter.
|
||||||
func (autocontrast) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
func (*autocontrast) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
||||||
dstBounds = srcBounds
|
dstBounds = srcBounds
|
||||||
return
|
return
|
||||||
}
|
}
|
@ -28,8 +28,10 @@ type cutRatioOptions struct {
|
|||||||
func findMargin(img image.Image, bounds image.Rectangle, cutRatio cutRatioOptions, limit int, skipIfLimitReached bool) image.Rectangle {
|
func findMargin(img image.Image, bounds image.Rectangle, cutRatio cutRatioOptions, limit int, skipIfLimitReached bool) image.Rectangle {
|
||||||
imgArea := bounds
|
imgArea := bounds
|
||||||
|
|
||||||
|
maxCropX, maxCropY := imgArea.Dx()*limit/100, imgArea.Dy()*limit/100
|
||||||
|
|
||||||
LEFT:
|
LEFT:
|
||||||
for x := imgArea.Min.X; x < imgArea.Max.X; x++ {
|
for x, maxCrop := imgArea.Min.X, maxCropX; x < imgArea.Max.X && (limit == 0 || maxCrop > 0); x, maxCrop = x+1, maxCrop-1 {
|
||||||
allowNonBlank := imgArea.Dy() * cutRatio.Left / 100
|
allowNonBlank := imgArea.Dy() * cutRatio.Left / 100
|
||||||
for y := imgArea.Min.Y; y < imgArea.Max.Y; y++ {
|
for y := imgArea.Min.Y; y < imgArea.Max.Y; y++ {
|
||||||
if !colorIsBlank(img.At(x, y)) {
|
if !colorIsBlank(img.At(x, y)) {
|
||||||
@ -40,10 +42,13 @@ LEFT:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
imgArea.Min.X++
|
imgArea.Min.X++
|
||||||
|
if limit > 0 && maxCrop == 1 && skipIfLimitReached {
|
||||||
|
return bounds
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
UP:
|
UP:
|
||||||
for y := imgArea.Min.Y; y < imgArea.Max.Y; y++ {
|
for y, maxCrop := imgArea.Min.Y, maxCropY; y < imgArea.Max.Y && (limit == 0 || maxCrop > 0); y, maxCrop = y+1, maxCrop-1 {
|
||||||
allowNonBlank := imgArea.Dx() * cutRatio.Up / 100
|
allowNonBlank := imgArea.Dx() * cutRatio.Up / 100
|
||||||
for x := imgArea.Min.X; x < imgArea.Max.X; x++ {
|
for x := imgArea.Min.X; x < imgArea.Max.X; x++ {
|
||||||
if !colorIsBlank(img.At(x, y)) {
|
if !colorIsBlank(img.At(x, y)) {
|
||||||
@ -54,10 +59,13 @@ UP:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
imgArea.Min.Y++
|
imgArea.Min.Y++
|
||||||
|
if limit > 0 && maxCrop == 1 && skipIfLimitReached {
|
||||||
|
return bounds
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
RIGHT:
|
RIGHT:
|
||||||
for x := imgArea.Max.X - 1; x >= imgArea.Min.X; x-- {
|
for x, maxCrop := imgArea.Max.X-1, maxCropX; x >= imgArea.Min.X && (limit == 0 || maxCrop > 0); x, maxCrop = x-1, maxCrop-1 {
|
||||||
allowNonBlank := imgArea.Dy() * cutRatio.Right / 100
|
allowNonBlank := imgArea.Dy() * cutRatio.Right / 100
|
||||||
for y := imgArea.Min.Y; y < imgArea.Max.Y; y++ {
|
for y := imgArea.Min.Y; y < imgArea.Max.Y; y++ {
|
||||||
if !colorIsBlank(img.At(x, y)) {
|
if !colorIsBlank(img.At(x, y)) {
|
||||||
@ -68,10 +76,13 @@ RIGHT:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
imgArea.Max.X--
|
imgArea.Max.X--
|
||||||
|
if limit > 0 && maxCrop == 1 && skipIfLimitReached {
|
||||||
|
return bounds
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
BOTTOM:
|
BOTTOM:
|
||||||
for y := imgArea.Max.Y - 1; y >= imgArea.Min.Y; y-- {
|
for y, maxCrop := imgArea.Max.Y-1, maxCropY; y >= imgArea.Min.Y && (limit == 0 || maxCrop > 0); y, maxCrop = y-1, maxCrop-1 {
|
||||||
allowNonBlank := imgArea.Dx() * cutRatio.Bottom / 100
|
allowNonBlank := imgArea.Dx() * cutRatio.Bottom / 100
|
||||||
for x := imgArea.Min.X; x < imgArea.Max.X; x++ {
|
for x := imgArea.Min.X; x < imgArea.Max.X; x++ {
|
||||||
if !colorIsBlank(img.At(x, y)) {
|
if !colorIsBlank(img.At(x, y)) {
|
||||||
@ -82,42 +93,10 @@ BOTTOM:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
imgArea.Max.Y--
|
imgArea.Max.Y--
|
||||||
}
|
if limit > 0 && maxCrop == 1 && skipIfLimitReached {
|
||||||
|
|
||||||
// no limit or blankImage
|
|
||||||
if limit == 0 || imgArea.Dx() == 0 || imgArea.Dy() == 0 {
|
|
||||||
return imgArea
|
|
||||||
}
|
|
||||||
|
|
||||||
exceedX, exceedY := limitExceed(bounds, imgArea, limit)
|
|
||||||
if skipIfLimitReached && (exceedX > 0 || exceedY > 0) {
|
|
||||||
return bounds
|
return bounds
|
||||||
}
|
}
|
||||||
|
}
|
||||||
imgArea.Min.X, imgArea.Max.X = correctLine(imgArea.Min.X, imgArea.Max.X, bounds.Min.X, bounds.Max.X, exceedX)
|
|
||||||
imgArea.Min.Y, imgArea.Max.Y = correctLine(imgArea.Min.Y, imgArea.Max.Y, bounds.Min.Y, bounds.Max.Y, exceedY)
|
|
||||||
|
|
||||||
return imgArea
|
return imgArea
|
||||||
}
|
}
|
||||||
|
|
||||||
func limitExceed(bounds, newBounds image.Rectangle, limit int) (int, int) {
|
|
||||||
return bounds.Dx() - newBounds.Dx() - bounds.Dx()*limit/100, bounds.Dy() - newBounds.Dy() - bounds.Dy()*limit/100
|
|
||||||
}
|
|
||||||
|
|
||||||
func correctLine(min, max, bMin, bMax, exceed int) (int, int) {
|
|
||||||
if exceed <= 0 {
|
|
||||||
return min, max
|
|
||||||
}
|
|
||||||
|
|
||||||
min -= exceed / 2
|
|
||||||
max += exceed / 2
|
|
||||||
if min < bMin {
|
|
||||||
max += bMin - min
|
|
||||||
min = bMin
|
|
||||||
}
|
|
||||||
if max > bMax {
|
|
||||||
min -= max - bMax
|
|
||||||
max = bMax
|
|
||||||
}
|
|
||||||
return min, max
|
|
||||||
}
|
|
@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
// CoverTitle Create a title with the cover image
|
// CoverTitle Create a title with the cover image
|
||||||
func CoverTitle(title string, align string, pctWidth int, pctMargin int, maxFontSize int, borderSize int) gift.Filter {
|
func CoverTitle(title string, align string, pctWidth int, pctMargin int, maxFontSize int, borderSize int) gift.Filter {
|
||||||
return coverTitle{title, align, pctWidth, pctMargin, maxFontSize, borderSize}
|
return &coverTitle{title, align, pctWidth, pctMargin, maxFontSize, borderSize}
|
||||||
}
|
}
|
||||||
|
|
||||||
type coverTitle struct {
|
type coverTitle struct {
|
||||||
@ -26,12 +26,12 @@ type coverTitle struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Bounds size is the same as source
|
// Bounds size is the same as source
|
||||||
func (p coverTitle) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
func (p *coverTitle) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
||||||
return srcBounds
|
return srcBounds
|
||||||
}
|
}
|
||||||
|
|
||||||
// Draw blur the src image, and create a box with the title in the middle
|
// Draw blur the src image, and create a box with the title in the middle
|
||||||
func (p coverTitle) Draw(dst draw.Image, src image.Image, _ *gift.Options) {
|
func (p *coverTitle) Draw(dst draw.Image, src image.Image, _ *gift.Options) {
|
||||||
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Src)
|
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Src)
|
||||||
if p.title == "" {
|
if p.title == "" {
|
||||||
return
|
return
|
@ -11,14 +11,14 @@ import (
|
|||||||
//
|
//
|
||||||
// This will cut in the middle of the page.
|
// This will cut in the middle of the page.
|
||||||
func CropSplitDoublePage(right bool) gift.Filter {
|
func CropSplitDoublePage(right bool) gift.Filter {
|
||||||
return cropSplitDoublePage{right}
|
return &cropSplitDoublePage{right}
|
||||||
}
|
}
|
||||||
|
|
||||||
type cropSplitDoublePage struct {
|
type cropSplitDoublePage struct {
|
||||||
right bool
|
right bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p cropSplitDoublePage) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
func (p *cropSplitDoublePage) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
||||||
if p.right {
|
if p.right {
|
||||||
dstBounds = image.Rect(
|
dstBounds = image.Rect(
|
||||||
srcBounds.Max.X/2, srcBounds.Min.Y,
|
srcBounds.Max.X/2, srcBounds.Min.Y,
|
||||||
@ -33,6 +33,6 @@ func (p cropSplitDoublePage) Bounds(srcBounds image.Rectangle) (dstBounds image.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p cropSplitDoublePage) Draw(dst draw.Image, src image.Image, options *gift.Options) {
|
func (p *cropSplitDoublePage) Draw(dst draw.Image, src image.Image, options *gift.Options) {
|
||||||
gift.Crop(dst.Bounds()).Draw(dst, src, options)
|
gift.Crop(dst.Bounds()).Draw(dst, src, options)
|
||||||
}
|
}
|
@ -12,13 +12,13 @@ import (
|
|||||||
//
|
//
|
||||||
// An image 0x0 is not a valid image, and failed to read.
|
// An image 0x0 is not a valid image, and failed to read.
|
||||||
func Pixel() gift.Filter {
|
func Pixel() gift.Filter {
|
||||||
return pixel{}
|
return &pixel{}
|
||||||
}
|
}
|
||||||
|
|
||||||
type pixel struct {
|
type pixel struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p pixel) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
func (p *pixel) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
||||||
if srcBounds.Dx() == 0 || srcBounds.Dy() == 0 {
|
if srcBounds.Dx() == 0 || srcBounds.Dy() == 0 {
|
||||||
dstBounds = image.Rect(0, 0, 1, 1)
|
dstBounds = image.Rect(0, 0, 1, 1)
|
||||||
} else {
|
} else {
|
||||||
@ -27,7 +27,7 @@ func (p pixel) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p pixel) Draw(dst draw.Image, src image.Image, _ *gift.Options) {
|
func (p *pixel) Draw(dst draw.Image, src image.Image, _ *gift.Options) {
|
||||||
if dst.Bounds().Dx() == 1 && dst.Bounds().Dy() == 1 {
|
if dst.Bounds().Dx() == 1 && dst.Bounds().Dy() == 1 {
|
||||||
dst.Set(0, 0, color.White)
|
dst.Set(0, 0, color.White)
|
||||||
return
|
return
|
@ -2,37 +2,34 @@
|
|||||||
package epubimageprocessor
|
package epubimageprocessor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"image"
|
"image"
|
||||||
"image/color"
|
"image/color"
|
||||||
"image/draw"
|
"image/draw"
|
||||||
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/disintegration/gift"
|
"github.com/disintegration/gift"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
|
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimagefilters"
|
epubimagefilters "github.com/celogeek/go-comic-converter/v2/internal/epub/imagefilters"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubprogress"
|
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubzip"
|
epubprogress "github.com/celogeek/go-comic-converter/v2/internal/epub/progress"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
epubzip "github.com/celogeek/go-comic-converter/v2/internal/epub/zip"
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EPUBImageProcessor interface {
|
type EPUBImageProcessor struct {
|
||||||
Load() (images []epubimage.EPUBImage, err error)
|
*epuboptions.Options
|
||||||
CoverTitleData(o CoverTitleDataOptions) (epubzip.Image, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ePUBImageProcessor struct {
|
func New(o *epuboptions.Options) *EPUBImageProcessor {
|
||||||
epuboptions.EPUBOptions
|
return &EPUBImageProcessor{o}
|
||||||
}
|
|
||||||
|
|
||||||
func New(o epuboptions.EPUBOptions) EPUBImageProcessor {
|
|
||||||
return ePUBImageProcessor{o}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load extract and convert images
|
// Load extract and convert images
|
||||||
func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
func (e *EPUBImageProcessor) Load() (images []*epubimage.Image, err error) {
|
||||||
images = make([]epubimage.EPUBImage, 0)
|
images = make([]*epubimage.Image, 0)
|
||||||
imageCount, imageInput, err := e.load()
|
imageCount, imageInput, err := e.load()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -41,7 +38,7 @@ func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
|||||||
// dry run, skip conversion
|
// dry run, skip conversion
|
||||||
if e.Dry {
|
if e.Dry {
|
||||||
for img := range imageInput {
|
for img := range imageInput {
|
||||||
images = append(images, epubimage.EPUBImage{
|
images = append(images, &epubimage.Image{
|
||||||
Id: img.Id,
|
Id: img.Id,
|
||||||
Path: img.Path,
|
Path: img.Path,
|
||||||
Name: img.Name,
|
Name: img.Name,
|
||||||
@ -52,7 +49,7 @@ func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
|||||||
return images, nil
|
return images, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
imageOutput := make(chan epubimage.EPUBImage)
|
imageOutput := make(chan *epubimage.Image)
|
||||||
|
|
||||||
// processing
|
// processing
|
||||||
bar := epubprogress.New(epubprogress.Options{
|
bar := epubprogress.New(epubprogress.Options{
|
||||||
@ -85,10 +82,11 @@ func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
|||||||
|
|
||||||
// do not keep double page if requested
|
// do not keep double page if requested
|
||||||
if !(img.DoublePage && input.Id > 0 &&
|
if !(img.DoublePage && input.Id > 0 &&
|
||||||
e.EPUBOptions.Image.AutoSplitDoublePage && !e.EPUBOptions.Image.KeepDoublePageIfSplit) {
|
e.Options.Image.AutoSplitDoublePage && !e.Options.Image.KeepDoublePageIfSplit) {
|
||||||
if err = imgStorage.Add(img.EPUBImgPath(), img.Raw, e.Image.Quality); err != nil {
|
if err = imgStorage.Add(img.EPUBImgPath(), img.Raw, e.Image.Quality); err != nil {
|
||||||
_ = bar.Close()
|
_ = bar.Close()
|
||||||
utils.Fatalf("error with %s: %s", input.Name, err)
|
utils.Printf("error with %s: %s", input.Name, err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
// do not keep raw image except for cover
|
// do not keep raw image except for cover
|
||||||
if img.Id > 0 {
|
if img.Id > 0 {
|
||||||
@ -108,7 +106,8 @@ func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
|||||||
img = e.transformImage(input, i+1, b)
|
img = e.transformImage(input, i+1, b)
|
||||||
if err = imgStorage.Add(img.EPUBImgPath(), img.Raw, e.Image.Quality); err != nil {
|
if err = imgStorage.Add(img.EPUBImgPath(), img.Raw, e.Image.Quality); err != nil {
|
||||||
_ = bar.Close()
|
_ = bar.Close()
|
||||||
utils.Fatalf("error with %s: %s", input.Name, err)
|
utils.Printf("error with %s: %s", input.Name, err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
img.Raw = nil
|
img.Raw = nil
|
||||||
imageOutput <- img
|
imageOutput <- img
|
||||||
@ -141,8 +140,8 @@ func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
|
|||||||
return images, nil
|
return images, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
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.EPUBOptions.Image.GrayScale {
|
if e.Options.Image.GrayScale {
|
||||||
return image.NewGray(r)
|
return image.NewGray(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,14 +173,12 @@ func (e ePUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw
|
|||||||
|
|
||||||
// transform image into 1 or 3 images
|
// transform image into 1 or 3 images
|
||||||
// only doublepage with autosplit has 3 versions
|
// only doublepage with autosplit has 3 versions
|
||||||
func (e ePUBImageProcessor) transformImage(input task, part int, right bool) epubimage.EPUBImage {
|
func (e *EPUBImageProcessor) transformImage(input *task, part int, right bool) *epubimage.Image {
|
||||||
g := gift.New()
|
g := gift.New()
|
||||||
src := input.Image
|
src := input.Image
|
||||||
srcBounds := src.Bounds()
|
srcBounds := src.Bounds()
|
||||||
|
|
||||||
// In portrait only, we don't need to keep aspect ratio between each split.
|
if part > 0 {
|
||||||
// We first cut, the crop.
|
|
||||||
if part > 0 && !e.Image.KeepSplitDoublePageAspect {
|
|
||||||
g.Add(epubimagefilters.CropSplitDoublePage(right))
|
g.Add(epubimagefilters.CropSplitDoublePage(right))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -208,18 +205,11 @@ func (e ePUBImageProcessor) transformImage(input task, part int, right bool) epu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// With landscape support, we need to keep aspect ratio between each split
|
|
||||||
// We first crop, then cut
|
|
||||||
if part > 0 && e.Image.KeepSplitDoublePageAspect {
|
|
||||||
g.Add(epubimagefilters.CropSplitDoublePage(right))
|
|
||||||
}
|
|
||||||
|
|
||||||
dstBounds := g.Bounds(src.Bounds())
|
dstBounds := g.Bounds(src.Bounds())
|
||||||
// Original && Cropped version need to landscape oriented
|
// Original && Cropped version need to landscape oriented
|
||||||
// Only part 0 can be a double page
|
isDoublePage := srcBounds.Dx() > srcBounds.Dy() && dstBounds.Dx() > dstBounds.Dy()
|
||||||
isDoublePage := part == 0 && srcBounds.Dx() > srcBounds.Dy() && dstBounds.Dx() > dstBounds.Dy()
|
|
||||||
|
|
||||||
if e.Image.AutoRotate && isDoublePage {
|
if part == 0 && e.Image.AutoRotate && isDoublePage {
|
||||||
g.Add(gift.Rotate90())
|
g.Add(gift.Rotate90())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -263,7 +253,7 @@ func (e ePUBImageProcessor) transformImage(input task, part int, right bool) epu
|
|||||||
dst := e.createImage(src, g.Bounds(src.Bounds()))
|
dst := e.createImage(src, g.Bounds(src.Bounds()))
|
||||||
g.Draw(dst, src)
|
g.Draw(dst, src)
|
||||||
|
|
||||||
return epubimage.EPUBImage{
|
return &epubimage.Image{
|
||||||
Id: input.Id,
|
Id: input.Id,
|
||||||
Part: part,
|
Part: part,
|
||||||
Raw: dst,
|
Raw: dst,
|
||||||
@ -291,7 +281,7 @@ type CoverTitleDataOptions struct {
|
|||||||
BorderSize int
|
BorderSize int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e ePUBImageProcessor) cover16LevelOfGray(bounds image.Rectangle) draw.Image {
|
func (e *EPUBImageProcessor) Cover16LevelOfGray(bounds image.Rectangle) draw.Image {
|
||||||
return image.NewPaletted(bounds, color.Palette{
|
return image.NewPaletted(bounds, color.Palette{
|
||||||
color.Gray{},
|
color.Gray{},
|
||||||
color.Gray{Y: 0x11},
|
color.Gray{Y: 0x11},
|
||||||
@ -313,20 +303,20 @@ func (e ePUBImageProcessor) cover16LevelOfGray(bounds image.Rectangle) draw.Imag
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CoverTitleData create a title page with the cover
|
// CoverTitleData create a title page with the cover
|
||||||
func (e ePUBImageProcessor) CoverTitleData(o CoverTitleDataOptions) (epubzip.Image, error) {
|
func (e *EPUBImageProcessor) CoverTitleData(o *CoverTitleDataOptions) (*epubzip.ZipImage, error) {
|
||||||
// Create a blur version of the cover
|
// Create a blur version of the cover
|
||||||
g := gift.New(epubimagefilters.CoverTitle(o.Text, o.Align, o.PctWidth, o.PctMargin, o.MaxFontSize, o.BorderSize))
|
g := gift.New(epubimagefilters.CoverTitle(o.Text, o.Align, o.PctWidth, o.PctMargin, o.MaxFontSize, o.BorderSize))
|
||||||
var dst draw.Image
|
var dst draw.Image
|
||||||
if o.Name == "cover" && e.Image.GrayScale {
|
if o.Name == "cover" && e.Image.GrayScale {
|
||||||
dst = e.cover16LevelOfGray(o.Src.Bounds())
|
dst = e.Cover16LevelOfGray(o.Src.Bounds())
|
||||||
} else {
|
} else {
|
||||||
dst = e.createImage(o.Src, g.Bounds(o.Src.Bounds()))
|
dst = e.createImage(o.Src, g.Bounds(o.Src.Bounds()))
|
||||||
}
|
}
|
||||||
g.Draw(dst, o.Src)
|
g.Draw(dst, o.Src)
|
||||||
|
|
||||||
return epubzip.CompressImage(
|
return epubzip.CompressImage(
|
||||||
"OEBPS/Images/"+o.Name+".jpeg",
|
fmt.Sprintf("OEBPS/Images/%s.%s", o.Name, e.Image.Format),
|
||||||
"jpeg",
|
e.Image.Format,
|
||||||
dst,
|
dst,
|
||||||
e.Image.Quality,
|
e.Image.Quality,
|
||||||
)
|
)
|
@ -18,7 +18,6 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"golang.org/x/image/font/gofont/gomonobold"
|
"golang.org/x/image/font/gofont/gomonobold"
|
||||||
_ "golang.org/x/image/tiff"
|
|
||||||
_ "golang.org/x/image/webp"
|
_ "golang.org/x/image/webp"
|
||||||
|
|
||||||
"github.com/fogleman/gg"
|
"github.com/fogleman/gg"
|
||||||
@ -27,9 +26,8 @@ import (
|
|||||||
pdfimage "github.com/raff/pdfreader/image"
|
pdfimage "github.com/raff/pdfreader/image"
|
||||||
"github.com/raff/pdfreader/pdfread"
|
"github.com/raff/pdfreader/pdfread"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/sortpath"
|
"github.com/celogeek/go-comic-converter/v2/internal/sortpath"
|
||||||
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type task struct {
|
type task struct {
|
||||||
@ -43,18 +41,18 @@ type task struct {
|
|||||||
var errNoImagesFound = errors.New("no images found")
|
var errNoImagesFound = errors.New("no images found")
|
||||||
|
|
||||||
// only accept jpg, png and webp as source file
|
// only accept jpg, png and webp as source file
|
||||||
func (e ePUBImageProcessor) isSupportedImage(path string) bool {
|
func (e *EPUBImageProcessor) isSupportedImage(path string) bool {
|
||||||
switch strings.ToLower(filepath.Ext(path)) {
|
switch strings.ToLower(filepath.Ext(path)) {
|
||||||
case ".jpg", ".jpeg", ".png", ".webp", ".tiff":
|
case ".jpg", ".jpeg", ".png", ".webp":
|
||||||
{
|
{
|
||||||
return !strings.HasPrefix(filepath.Base(path), ".")
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// load images from input
|
// Load images from input
|
||||||
func (e ePUBImageProcessor) load() (totalImages int, output chan task, err error) {
|
func (e *EPUBImageProcessor) load() (totalImages int, output chan *task, err error) {
|
||||||
fi, err := os.Stat(e.Input)
|
fi, err := os.Stat(e.Input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -78,7 +76,7 @@ func (e ePUBImageProcessor) load() (totalImages int, output chan task, err error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e ePUBImageProcessor) corruptedImage(path, name string) image.Image {
|
func (e *EPUBImageProcessor) corruptedImage(path, name string) image.Image {
|
||||||
var w, h float64 = 1200, 1920
|
var w, h float64 = 1200, 1920
|
||||||
f, _ := truetype.Parse(gomonobold.TTF)
|
f, _ := truetype.Parse(gomonobold.TTF)
|
||||||
face := truetype.NewFace(f, &truetype.Options{Size: 64, DPI: 72})
|
face := truetype.NewFace(f, &truetype.Options{Size: 64, DPI: 72})
|
||||||
@ -102,7 +100,7 @@ func (e ePUBImageProcessor) corruptedImage(path, name string) image.Image {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// load a directory of images
|
// load a directory of images
|
||||||
func (e ePUBImageProcessor) loadDir() (totalImages int, output chan task, err error) {
|
func (e *EPUBImageProcessor) loadDir() (totalImages int, output chan *task, err error) {
|
||||||
images := make([]string, 0)
|
images := make([]string, 0)
|
||||||
|
|
||||||
input := filepath.Clean(e.Input)
|
input := filepath.Clean(e.Input)
|
||||||
@ -134,16 +132,16 @@ func (e ePUBImageProcessor) loadDir() (totalImages int, output chan task, err er
|
|||||||
Id int
|
Id int
|
||||||
Path string
|
Path string
|
||||||
}
|
}
|
||||||
jobs := make(chan job)
|
jobs := make(chan *job)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(jobs)
|
defer close(jobs)
|
||||||
for i, path := range images {
|
for i, path := range images {
|
||||||
jobs <- job{i, path}
|
jobs <- &job{i, path}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// read in parallel and get an image
|
// read in parallel and get an image
|
||||||
output = make(chan task, e.Workers)
|
output = make(chan *task, e.Workers)
|
||||||
wg := &sync.WaitGroup{}
|
wg := &sync.WaitGroup{}
|
||||||
for range e.WorkersRatio(50) {
|
for range e.WorkersRatio(50) {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
@ -170,7 +168,7 @@ func (e ePUBImageProcessor) loadDir() (totalImages int, output chan task, err er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
img = e.corruptedImage(p, fn)
|
img = e.corruptedImage(p, fn)
|
||||||
}
|
}
|
||||||
output <- task{
|
output <- &task{
|
||||||
Id: job.Id,
|
Id: job.Id,
|
||||||
Image: img,
|
Image: img,
|
||||||
Path: p,
|
Path: p,
|
||||||
@ -191,7 +189,7 @@ func (e ePUBImageProcessor) loadDir() (totalImages int, output chan task, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// load a zip file that include images
|
// load a zip file that include images
|
||||||
func (e ePUBImageProcessor) loadCbz() (totalImages int, output chan task, err error) {
|
func (e *EPUBImageProcessor) loadCbz() (totalImages int, output chan *task, err error) {
|
||||||
r, err := zip.OpenReader(e.Input)
|
r, err := zip.OpenReader(e.Input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -227,15 +225,15 @@ func (e ePUBImageProcessor) loadCbz() (totalImages int, output chan task, err er
|
|||||||
Id int
|
Id int
|
||||||
F *zip.File
|
F *zip.File
|
||||||
}
|
}
|
||||||
jobs := make(chan job)
|
jobs := make(chan *job)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(jobs)
|
defer close(jobs)
|
||||||
for _, img := range images {
|
for _, img := range images {
|
||||||
jobs <- job{indexedNames[img.Name], img}
|
jobs <- &job{indexedNames[img.Name], img}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
output = make(chan task, e.Workers)
|
output = make(chan *task, e.Workers)
|
||||||
wg := &sync.WaitGroup{}
|
wg := &sync.WaitGroup{}
|
||||||
for range e.WorkersRatio(50) {
|
for range e.WorkersRatio(50) {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
@ -257,7 +255,7 @@ func (e ePUBImageProcessor) loadCbz() (totalImages int, output chan task, err er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
img = e.corruptedImage(p, fn)
|
img = e.corruptedImage(p, fn)
|
||||||
}
|
}
|
||||||
output <- task{
|
output <- &task{
|
||||||
Id: job.Id,
|
Id: job.Id,
|
||||||
Image: img,
|
Image: img,
|
||||||
Path: p,
|
Path: p,
|
||||||
@ -277,7 +275,7 @@ func (e ePUBImageProcessor) loadCbz() (totalImages int, output chan task, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// load a rar file that include images
|
// load a rar file that include images
|
||||||
func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err error) {
|
func (e *EPUBImageProcessor) loadCbr() (totalImages int, output chan *task, err error) {
|
||||||
var isSolid bool
|
var isSolid bool
|
||||||
files, err := rardecode.List(e.Input)
|
files, err := rardecode.List(e.Input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -313,13 +311,14 @@ func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
|
|||||||
Open func() (io.ReadCloser, error)
|
Open func() (io.ReadCloser, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
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.Dry {
|
||||||
r, rerr := rardecode.OpenReader(e.Input)
|
r, rerr := rardecode.OpenReader(e.Input)
|
||||||
if rerr != nil {
|
if rerr != nil {
|
||||||
utils.Fatalf("\nerror processing image %s: %s\n", e.Input, rerr)
|
utils.Printf("\nerror processing image %s: %s\n", e.Input, rerr)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer func(r *rardecode.ReadCloser) {
|
defer func(r *rardecode.ReadCloser) {
|
||||||
_ = r.Close()
|
_ = r.Close()
|
||||||
@ -330,15 +329,17 @@ func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
|
|||||||
if rerr == io.EOF {
|
if rerr == io.EOF {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
utils.Fatalf("\nerror processing image %s: %s\n", f.Name, rerr)
|
utils.Printf("\nerror processing image %s: %s\n", f.Name, rerr)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
if i, ok := indexedNames[f.Name]; ok {
|
if i, ok := indexedNames[f.Name]; ok {
|
||||||
var b bytes.Buffer
|
var b bytes.Buffer
|
||||||
_, rerr = io.Copy(&b, r)
|
_, rerr = io.Copy(&b, r)
|
||||||
if rerr != nil {
|
if rerr != nil {
|
||||||
utils.Fatalf("\nerror processing image %s: %s\n", f.Name, rerr)
|
utils.Printf("\nerror processing image %s: %s\n", f.Name, rerr)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
jobs <- job{i, f.Name, func() (io.ReadCloser, error) {
|
jobs <- &job{i, f.Name, func() (io.ReadCloser, error) {
|
||||||
return io.NopCloser(bytes.NewReader(b.Bytes())), nil
|
return io.NopCloser(bytes.NewReader(b.Bytes())), nil
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
@ -346,14 +347,14 @@ func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
|
|||||||
} else {
|
} else {
|
||||||
for _, img := range files {
|
for _, img := range files {
|
||||||
if i, ok := indexedNames[img.Name]; ok {
|
if i, ok := indexedNames[img.Name]; ok {
|
||||||
jobs <- job{i, img.Name, img.Open}
|
jobs <- &job{i, img.Name, img.Open}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// send file to the queue
|
// send file to the queue
|
||||||
output = make(chan task, e.Workers)
|
output = make(chan *task, e.Workers)
|
||||||
wg := &sync.WaitGroup{}
|
wg := &sync.WaitGroup{}
|
||||||
for range e.WorkersRatio(50) {
|
for range e.WorkersRatio(50) {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
@ -375,7 +376,7 @@ func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
img = e.corruptedImage(p, fn)
|
img = e.corruptedImage(p, fn)
|
||||||
}
|
}
|
||||||
output <- task{
|
output <- &task{
|
||||||
Id: job.Id,
|
Id: job.Id,
|
||||||
Image: img,
|
Image: img,
|
||||||
Path: p,
|
Path: p,
|
||||||
@ -393,7 +394,7 @@ func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// extract image from a pdf
|
// extract image from a pdf
|
||||||
func (e ePUBImageProcessor) loadPdf() (totalImages int, output chan task, err error) {
|
func (e *EPUBImageProcessor) loadPdf() (totalImages int, output chan *task, err error) {
|
||||||
pdf := pdfread.Load(e.Input)
|
pdf := pdfread.Load(e.Input)
|
||||||
if pdf == nil {
|
if pdf == nil {
|
||||||
err = fmt.Errorf("can't read pdf")
|
err = fmt.Errorf("can't read pdf")
|
||||||
@ -401,8 +402,8 @@ func (e ePUBImageProcessor) loadPdf() (totalImages int, output chan task, err er
|
|||||||
}
|
}
|
||||||
|
|
||||||
totalImages = len(pdf.Pages())
|
totalImages = len(pdf.Pages())
|
||||||
pageFmt := "page " + utils.FormatNumberOfDigits(totalImages)
|
pageFmt := fmt.Sprintf("page %%0%dd", len(fmt.Sprintf("%d", totalImages)))
|
||||||
output = make(chan task)
|
output = make(chan *task)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(output)
|
defer close(output)
|
||||||
defer pdf.Close()
|
defer pdf.Close()
|
||||||
@ -417,7 +418,7 @@ func (e ePUBImageProcessor) loadPdf() (totalImages int, output chan task, err er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
img = e.corruptedImage("", name)
|
img = e.corruptedImage("", name)
|
||||||
}
|
}
|
||||||
output <- task{
|
output <- &task{
|
||||||
Id: i,
|
Id: i,
|
||||||
Image: img,
|
Image: img,
|
||||||
Path: "",
|
Path: "",
|
71
internal/epub/options/epub_options.go
Normal file
71
internal/epub/options/epub_options.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
// Package epuboptions Options for EPUB creation.
|
||||||
|
package epuboptions
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type Crop struct {
|
||||||
|
Enabled bool
|
||||||
|
Left, Up, Right, Bottom int
|
||||||
|
Limit int
|
||||||
|
SkipIfLimitReached bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Color struct {
|
||||||
|
Foreground, Background string
|
||||||
|
}
|
||||||
|
|
||||||
|
type View struct {
|
||||||
|
Width, Height int
|
||||||
|
AspectRatio float64
|
||||||
|
PortraitOnly bool
|
||||||
|
Color Color
|
||||||
|
}
|
||||||
|
|
||||||
|
type Image struct {
|
||||||
|
Crop *Crop
|
||||||
|
Quality int
|
||||||
|
Brightness int
|
||||||
|
Contrast int
|
||||||
|
AutoContrast bool
|
||||||
|
AutoRotate bool
|
||||||
|
AutoSplitDoublePage bool
|
||||||
|
KeepDoublePageIfSplit bool
|
||||||
|
NoBlankImage bool
|
||||||
|
Manga bool
|
||||||
|
HasCover bool
|
||||||
|
View *View
|
||||||
|
GrayScale bool
|
||||||
|
GrayScaleMode int
|
||||||
|
Resize bool
|
||||||
|
Format string
|
||||||
|
AppleBookCompatibility bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
Input string
|
||||||
|
Output string
|
||||||
|
Title string
|
||||||
|
TitlePage int
|
||||||
|
Author string
|
||||||
|
LimitMb int
|
||||||
|
StripFirstDirectoryFromToc bool
|
||||||
|
Dry bool
|
||||||
|
DryVerbose bool
|
||||||
|
SortPathMode int
|
||||||
|
Quiet bool
|
||||||
|
Json bool
|
||||||
|
Workers int
|
||||||
|
Image *Image
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) WorkersRatio(pct int) (nbWorkers int) {
|
||||||
|
nbWorkers = o.Workers * pct / 100
|
||||||
|
if nbWorkers < 1 {
|
||||||
|
nbWorkers = 1
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *Options) ImgStorage() string {
|
||||||
|
return fmt.Sprintf("%s.tmp", o.Output)
|
||||||
|
}
|
@ -2,14 +2,13 @@
|
|||||||
package epubprogress
|
package epubprogress
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/schollz/progressbar/v3"
|
"github.com/schollz/progressbar/v3"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
@ -21,36 +20,29 @@ 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 &jsonprogress{
|
return newEpubProgressJson(o)
|
||||||
o: o,
|
|
||||||
e: json.NewEncoder(os.Stdout),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fmtJob := utils.FormatNumberOfDigits(o.TotalJob)
|
fmtJob := fmt.Sprintf("%%0%dd", len(fmt.Sprint(o.TotalJob)))
|
||||||
|
fmtDesc := fmt.Sprintf("[%s/%s] %%-15s", fmtJob, fmtJob)
|
||||||
return progressbar.NewOptions(o.Max,
|
return progressbar.NewOptions(o.Max,
|
||||||
progressbar.OptionSetWriter(os.Stderr),
|
progressbar.OptionSetWriter(os.Stderr),
|
||||||
progressbar.OptionThrottle(65*time.Millisecond),
|
progressbar.OptionThrottle(65*time.Millisecond),
|
||||||
progressbar.OptionOnCompletion(func() {
|
progressbar.OptionOnCompletion(func() {
|
||||||
utils.Println()
|
utils.Println()
|
||||||
}),
|
}),
|
||||||
progressbar.OptionSetDescription(fmt.Sprintf(
|
progressbar.OptionSetDescription(fmt.Sprintf(fmtDesc, o.CurrentJob, o.TotalJob, o.Description)),
|
||||||
"["+fmtJob+"/"+fmtJob+"] %-15s",
|
|
||||||
o.CurrentJob,
|
|
||||||
o.TotalJob,
|
|
||||||
o.Description,
|
|
||||||
)),
|
|
||||||
progressbar.OptionSetWidth(60),
|
progressbar.OptionSetWidth(60),
|
||||||
progressbar.OptionShowCount(),
|
progressbar.OptionShowCount(),
|
||||||
progressbar.OptionSetRenderBlankState(true),
|
progressbar.OptionSetRenderBlankState(true),
|
@ -2,20 +2,28 @@ package epubprogress
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
type jsonprogress struct {
|
type Json struct {
|
||||||
o Options
|
o Options
|
||||||
e *json.Encoder
|
e *json.Encoder
|
||||||
current int
|
current int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *jsonprogress) Add(num int) error {
|
func newEpubProgressJson(o Options) EpubProgress {
|
||||||
|
return &Json{
|
||||||
|
o: o,
|
||||||
|
e: json.NewEncoder(os.Stdout),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Json) Add(num int) error {
|
||||||
p.current += num
|
p.current += num
|
||||||
return p.e.Encode(map[string]any{
|
return p.e.Encode(map[string]any{
|
||||||
"type": "epubprogress",
|
"type": "progress",
|
||||||
"data": map[string]any{
|
"data": map[string]any{
|
||||||
"epubprogress": map[string]any{
|
"progress": map[string]any{
|
||||||
"current": p.current,
|
"current": p.current,
|
||||||
"total": p.o.Max,
|
"total": p.o.Max,
|
||||||
},
|
},
|
||||||
@ -28,6 +36,6 @@ func (p *jsonprogress) Add(num int) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *jsonprogress) Close() error {
|
func (p *Json) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
21
internal/epub/templates/epub_templates.go
Normal file
21
internal/epub/templates/epub_templates.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
// Package epubtemplates 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
|
||||||
|
)
|
@ -1,23 +1,24 @@
|
|||||||
package epubtemplates
|
package epubtemplates
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/beevik/etree"
|
"github.com/beevik/etree"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
|
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options"
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Content struct {
|
type ContentOptions struct {
|
||||||
Title string
|
Title string
|
||||||
HasTitlePage bool
|
HasTitlePage bool
|
||||||
UID string
|
UID string
|
||||||
Author string
|
Author string
|
||||||
Publisher string
|
Publisher string
|
||||||
UpdatedAt string
|
UpdatedAt string
|
||||||
ImageOptions epuboptions.Image
|
ImageOptions *epuboptions.Image
|
||||||
Cover epubimage.EPUBImage
|
Cover *epubimage.Image
|
||||||
Images []epubimage.EPUBImage
|
Images []*epubimage.Image
|
||||||
Current int
|
Current int
|
||||||
Total int
|
Total int
|
||||||
}
|
}
|
||||||
@ -30,10 +31,10 @@ type tag struct {
|
|||||||
value string
|
value string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get create the content file
|
// Content create the content file
|
||||||
//
|
//
|
||||||
//goland:noinspection HttpUrlsUsage,HttpUrlsUsage,HttpUrlsUsage,HttpUrlsUsage
|
//goland:noinspection HttpUrlsUsage,HttpUrlsUsage,HttpUrlsUsage,HttpUrlsUsage
|
||||||
func (o Content) String() string {
|
func Content(o *ContentOptions) 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"`)
|
||||||
|
|
||||||
@ -43,8 +44,8 @@ func (o Content) String() string {
|
|||||||
pkg.CreateAttr("version", "3.0")
|
pkg.CreateAttr("version", "3.0")
|
||||||
pkg.CreateAttr("prefix", "rendition: http://www.idpf.org/vocab/rendition/#")
|
pkg.CreateAttr("prefix", "rendition: http://www.idpf.org/vocab/rendition/#")
|
||||||
|
|
||||||
addToElement := func(elm *etree.Element, meth func() []tag) {
|
addToElement := func(elm *etree.Element, meth func(o *ContentOptions) []tag) {
|
||||||
for _, p := range meth() {
|
for _, p := range meth(o) {
|
||||||
meta := elm.CreateElement(p.name)
|
meta := elm.CreateElement(p.name)
|
||||||
for k, v := range p.attrs {
|
for k, v := range p.attrs {
|
||||||
meta.CreateAttr(k, v)
|
meta.CreateAttr(k, v)
|
||||||
@ -59,10 +60,10 @@ func (o Content) String() string {
|
|||||||
metadata := pkg.CreateElement("metadata")
|
metadata := pkg.CreateElement("metadata")
|
||||||
metadata.CreateAttr("xmlns:dc", "http://purl.org/dc/elements/1.1/")
|
metadata.CreateAttr("xmlns:dc", "http://purl.org/dc/elements/1.1/")
|
||||||
metadata.CreateAttr("xmlns:opf", "http://www.idpf.org/2007/opf")
|
metadata.CreateAttr("xmlns:opf", "http://www.idpf.org/2007/opf")
|
||||||
addToElement(metadata, o.getMeta)
|
addToElement(metadata, getMeta)
|
||||||
|
|
||||||
manifest := pkg.CreateElement("manifest")
|
manifest := pkg.CreateElement("manifest")
|
||||||
addToElement(manifest, o.getManifest)
|
addToElement(manifest, getManifest)
|
||||||
|
|
||||||
spine := pkg.CreateElement("spine")
|
spine := pkg.CreateElement("spine")
|
||||||
if o.ImageOptions.Manga {
|
if o.ImageOptions.Manga {
|
||||||
@ -72,13 +73,13 @@ func (o Content) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if o.ImageOptions.View.PortraitOnly {
|
if o.ImageOptions.View.PortraitOnly {
|
||||||
addToElement(spine, o.getSpinePortrait)
|
addToElement(spine, getSpinePortrait)
|
||||||
} else {
|
} else {
|
||||||
addToElement(spine, o.getSpineAuto)
|
addToElement(spine, getSpineAuto)
|
||||||
}
|
}
|
||||||
|
|
||||||
guide := pkg.CreateElement("guide")
|
guide := pkg.CreateElement("guide")
|
||||||
addToElement(guide, o.getGuide)
|
addToElement(guide, getGuide)
|
||||||
|
|
||||||
doc.Indent(2)
|
doc.Indent(2)
|
||||||
r, _ := doc.WriteToString()
|
r, _ := doc.WriteToString()
|
||||||
@ -87,7 +88,7 @@ func (o Content) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// metadata part of the content
|
// metadata part of the content
|
||||||
func (o Content) getMeta() []tag {
|
func getMeta(o *ContentOptions) []tag {
|
||||||
metas := []tag{
|
metas := []tag{
|
||||||
{"meta", tagAttrs{"property": "dcterms:modified"}, o.UpdatedAt},
|
{"meta", tagAttrs{"property": "dcterms:modified"}, o.UpdatedAt},
|
||||||
{"meta", tagAttrs{"property": "schema:accessMode"}, "visual"},
|
{"meta", tagAttrs{"property": "schema:accessMode"}, "visual"},
|
||||||
@ -97,9 +98,9 @@ func (o Content) getMeta() []tag {
|
|||||||
{"meta", tagAttrs{"property": "schema:accessibilityHazard"}, "noSoundHazard"},
|
{"meta", tagAttrs{"property": "schema:accessibilityHazard"}, "noSoundHazard"},
|
||||||
{"meta", tagAttrs{"name": "book-type", "content": "comic"}, ""},
|
{"meta", tagAttrs{"name": "book-type", "content": "comic"}, ""},
|
||||||
{"opf:meta", tagAttrs{"name": "fixed-layout", "content": "true"}, ""},
|
{"opf:meta", tagAttrs{"name": "fixed-layout", "content": "true"}, ""},
|
||||||
{"opf:meta", tagAttrs{"name": "original-resolution", "content": o.ImageOptions.View.Dimension()}, ""},
|
{"opf:meta", tagAttrs{"name": "original-resolution", "content": fmt.Sprintf("%dx%d", o.ImageOptions.View.Width, o.ImageOptions.View.Height)}, ""},
|
||||||
{"dc:title", tagAttrs{}, o.Title},
|
{"dc:title", tagAttrs{}, o.Title},
|
||||||
{"dc:identifier", tagAttrs{"id": "ean"}, "urn:uuid:" + o.UID},
|
{"dc:identifier", tagAttrs{"id": "ean"}, fmt.Sprintf("urn:uuid:%s", o.UID)},
|
||||||
{"dc:language", tagAttrs{}, "en"},
|
{"dc:language", tagAttrs{}, "en"},
|
||||||
{"dc:creator", tagAttrs{}, o.Author},
|
{"dc:creator", tagAttrs{}, o.Author},
|
||||||
{"dc:publisher", tagAttrs{}, o.Publisher},
|
{"dc:publisher", tagAttrs{}, o.Publisher},
|
||||||
@ -133,18 +134,18 @@ func (o Content) getMeta() []tag {
|
|||||||
metas = append(
|
metas = append(
|
||||||
metas,
|
metas,
|
||||||
tag{"meta", tagAttrs{"name": "calibre:series", "content": o.Title}, ""},
|
tag{"meta", tagAttrs{"name": "calibre:series", "content": o.Title}, ""},
|
||||||
tag{"meta", tagAttrs{"name": "calibre:series_index", "content": utils.IntToString(o.Current)}, ""},
|
tag{"meta", tagAttrs{"name": "calibre:series_index", "content": fmt.Sprint(o.Current)}, ""},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return metas
|
return metas
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o Content) getManifest() []tag {
|
func getManifest(o *ContentOptions) []tag {
|
||||||
var imageTags, pageTags, spaceTags []tag
|
var imageTags, pageTags, spaceTags []tag
|
||||||
addTag := func(img epubimage.EPUBImage, withSpace bool) {
|
addTag := func(img *epubimage.Image, withSpace bool) {
|
||||||
imageTags = append(imageTags,
|
imageTags = append(imageTags,
|
||||||
tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": img.MediaType()}, ""},
|
tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": fmt.Sprintf("image/%s", o.ImageOptions.Format)}, ""},
|
||||||
)
|
)
|
||||||
pageTags = append(pageTags,
|
pageTags = append(pageTags,
|
||||||
tag{"item", tagAttrs{"id": img.PageKey(), "href": img.PagePath(), "media-type": "application/xhtml+xml"}, ""},
|
tag{"item", tagAttrs{"id": img.PageKey(), "href": img.PagePath(), "media-type": "application/xhtml+xml"}, ""},
|
||||||
@ -160,13 +161,13 @@ func (o Content) getManifest() []tag {
|
|||||||
{"item", tagAttrs{"id": "toc", "href": "toc.xhtml", "properties": "nav", "media-type": "application/xhtml+xml"}, ""},
|
{"item", tagAttrs{"id": "toc", "href": "toc.xhtml", "properties": "nav", "media-type": "application/xhtml+xml"}, ""},
|
||||||
{"item", tagAttrs{"id": "css", "href": "Text/style.css", "media-type": "text/css"}, ""},
|
{"item", tagAttrs{"id": "css", "href": "Text/style.css", "media-type": "text/css"}, ""},
|
||||||
{"item", tagAttrs{"id": "page_cover", "href": "Text/cover.xhtml", "media-type": "application/xhtml+xml"}, ""},
|
{"item", tagAttrs{"id": "page_cover", "href": "Text/cover.xhtml", "media-type": "application/xhtml+xml"}, ""},
|
||||||
{"item", tagAttrs{"id": "img_cover", "href": "Images/cover.jpeg", "media-type": "image/jpeg"}, ""},
|
{"item", tagAttrs{"id": "img_cover", "href": fmt.Sprintf("Images/cover.%s", o.ImageOptions.Format), "media-type": fmt.Sprintf("image/%s", o.ImageOptions.Format)}, ""},
|
||||||
}
|
}
|
||||||
|
|
||||||
if o.HasTitlePage {
|
if o.HasTitlePage {
|
||||||
items = append(items,
|
items = append(items,
|
||||||
tag{"item", tagAttrs{"id": "page_title", "href": "Text/title.xhtml", "media-type": "application/xhtml+xml"}, ""},
|
tag{"item", tagAttrs{"id": "page_title", "href": "Text/title.xhtml", "media-type": "application/xhtml+xml"}, ""},
|
||||||
tag{"item", tagAttrs{"id": "img_title", "href": "Images/title.jpeg", "media-type": "image/jpeg"}, ""},
|
tag{"item", tagAttrs{"id": "img_title", "href": fmt.Sprintf("Images/title.%s", o.ImageOptions.Format), "media-type": fmt.Sprintf("image/%s", o.ImageOptions.Format)}, ""},
|
||||||
)
|
)
|
||||||
|
|
||||||
if !o.ImageOptions.View.PortraitOnly {
|
if !o.ImageOptions.View.PortraitOnly {
|
||||||
@ -192,7 +193,7 @@ func (o Content) getManifest() []tag {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// spine part of the content
|
// spine part of the content
|
||||||
func (o Content) getSpineAuto() []tag {
|
func getSpineAuto(o *ContentOptions) []tag {
|
||||||
isOnTheRight := !o.ImageOptions.Manga
|
isOnTheRight := !o.ImageOptions.Manga
|
||||||
if o.ImageOptions.AppleBookCompatibility {
|
if o.ImageOptions.AppleBookCompatibility {
|
||||||
isOnTheRight = !isOnTheRight
|
isOnTheRight = !isOnTheRight
|
||||||
@ -211,7 +212,7 @@ func (o Content) getSpineAuto() []tag {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
getSpreadBlank := func() string {
|
getSpreadBlank := func() string {
|
||||||
return getSpread(false) + " layout-blank"
|
return fmt.Sprintf("%s layout-blank", getSpread(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
var spine []tag
|
var spine []tag
|
||||||
@ -227,7 +228,7 @@ func (o Content) getSpineAuto() []tag {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i, img := range o.Images {
|
for _, img := range o.Images {
|
||||||
if (img.DoublePage || img.Part == 1) && o.ImageOptions.Manga == isOnTheRight {
|
if (img.DoublePage || img.Part == 1) && o.ImageOptions.Manga == isOnTheRight {
|
||||||
spine = append(spine, tag{
|
spine = append(spine, tag{
|
||||||
"itemref",
|
"itemref",
|
||||||
@ -242,8 +243,6 @@ func (o Content) getSpineAuto() []tag {
|
|||||||
tagAttrs{"idref": img.PageKey(), "properties": img.Position},
|
tagAttrs{"idref": img.PageKey(), "properties": img.Position},
|
||||||
"",
|
"",
|
||||||
})
|
})
|
||||||
// save position, img is a value type
|
|
||||||
o.Images[i] = img
|
|
||||||
}
|
}
|
||||||
if o.ImageOptions.Manga == isOnTheRight {
|
if o.ImageOptions.Manga == isOnTheRight {
|
||||||
spine = append(spine, tag{
|
spine = append(spine, tag{
|
||||||
@ -256,7 +255,7 @@ func (o Content) getSpineAuto() []tag {
|
|||||||
return spine
|
return spine
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o Content) getSpinePortrait() []tag {
|
func getSpinePortrait(o *ContentOptions) []tag {
|
||||||
var spine []tag
|
var spine []tag
|
||||||
if o.HasTitlePage {
|
if o.HasTitlePage {
|
||||||
spine = append(spine,
|
spine = append(spine,
|
||||||
@ -274,7 +273,7 @@ func (o Content) getSpinePortrait() []tag {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getGuide Section guide of the content
|
// getGuide Section guide of the content
|
||||||
func (o Content) getGuide() []tag {
|
func getGuide(o *ContentOptions) []tag {
|
||||||
return []tag{
|
return []tag{
|
||||||
{"reference", tagAttrs{"type": "cover", "title": "cover", "href": "Text/cover.xhtml"}, ""},
|
{"reference", tagAttrs{"type": "cover", "title": "cover", "href": "Text/cover.xhtml"}, ""},
|
||||||
{"reference", tagAttrs{"type": "text", "title": "content", "href": o.Images[0].PagePath()}, ""},
|
{"reference", tagAttrs{"type": "text", "title": "content", "href": o.Images[0].PagePath()}, ""},
|
@ -15,5 +15,4 @@ img {
|
|||||||
margin:0;
|
margin:0;
|
||||||
padding:0;
|
padding:0;
|
||||||
z-index:0;
|
z-index:0;
|
||||||
object-fit: contain;
|
|
||||||
}
|
}
|
@ -6,13 +6,13 @@ import (
|
|||||||
|
|
||||||
"github.com/beevik/etree"
|
"github.com/beevik/etree"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
|
epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Toc create toc
|
// Toc create toc
|
||||||
//
|
//
|
||||||
//goland:noinspection HttpUrlsUsage
|
//goland:noinspection HttpUrlsUsage
|
||||||
func Toc(title string, hasTitle bool, stripFirstDirectoryFromToc bool, images []epubimage.EPUBImage) string {
|
func Toc(title string, hasTitle bool, stripFirstDirectoryFromToc bool, images []*epubimage.Image) 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")
|
@ -23,7 +23,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EPUBTree struct {
|
type Tree struct {
|
||||||
nodes map[string]*Node
|
nodes map[string]*Node
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,19 +33,19 @@ type Node struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New initialize tree with a root node
|
// New initialize tree with a root node
|
||||||
func New() *EPUBTree {
|
func New() *Tree {
|
||||||
return &EPUBTree{map[string]*Node{
|
return &Tree{map[string]*Node{
|
||||||
".": {".", []*Node{}},
|
".": {".", []*Node{}},
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Root root node
|
// Root root node
|
||||||
func (n *EPUBTree) Root() *Node {
|
func (n *Tree) Root() *Node {
|
||||||
return n.nodes["."]
|
return n.nodes["."]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the filename to the tree
|
// Add the filename to the tree
|
||||||
func (n *EPUBTree) Add(filename string) {
|
func (n *Tree) Add(filename string) {
|
||||||
cn := n.Root()
|
cn := n.Root()
|
||||||
cp := ""
|
cp := ""
|
||||||
for _, p := range strings.Split(filepath.Clean(filename), string(filepath.Separator)) {
|
for _, p := range strings.Split(filepath.Clean(filename), string(filepath.Separator)) {
|
@ -17,17 +17,17 @@ type EPUBZip struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New create a new EPUB
|
// New create a new EPUB
|
||||||
func New(path string) (EPUBZip, error) {
|
func New(path string) (*EPUBZip, error) {
|
||||||
w, err := os.Create(path)
|
w, err := os.Create(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return EPUBZip{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
wz := zip.NewWriter(w)
|
wz := zip.NewWriter(w)
|
||||||
return EPUBZip{w, wz}, nil
|
return &EPUBZip{w, wz}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close compress pipe and file.
|
// Close compress pipe and file.
|
||||||
func (e EPUBZip) Close() error {
|
func (e *EPUBZip) Close() error {
|
||||||
if err := e.wz.Close(); err != nil {
|
if err := e.wz.Close(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -37,10 +37,10 @@ func (e EPUBZip) Close() error {
|
|||||||
// WriteMagic Write mimetype, in a very specific way.
|
// WriteMagic Write mimetype, in a very specific way.
|
||||||
//
|
//
|
||||||
// This will be valid with epubcheck tools.
|
// This will be valid with epubcheck tools.
|
||||||
func (e EPUBZip) WriteMagic() error {
|
func (e *EPUBZip) WriteMagic() error {
|
||||||
t := time.Now().UTC()
|
t := time.Now().UTC()
|
||||||
//goland:noinspection GoDeprecation
|
//goland:noinspection GoDeprecation
|
||||||
fh := zip.FileHeader{
|
fh := &zip.FileHeader{
|
||||||
Name: "mimetype",
|
Name: "mimetype",
|
||||||
Method: zip.Store,
|
Method: zip.Store,
|
||||||
Modified: t,
|
Modified: t,
|
||||||
@ -53,7 +53,7 @@ func (e EPUBZip) WriteMagic() error {
|
|||||||
fh.CreatorVersion = fh.CreatorVersion&0xff00 | 20 // preserve compatibility byte
|
fh.CreatorVersion = fh.CreatorVersion&0xff00 | 20 // preserve compatibility byte
|
||||||
fh.ReaderVersion = 20
|
fh.ReaderVersion = 20
|
||||||
fh.SetMode(0600)
|
fh.SetMode(0600)
|
||||||
m, err := e.wz.CreateRaw(&fh)
|
m, err := e.wz.CreateRaw(fh)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -62,12 +62,12 @@ func (e EPUBZip) WriteMagic() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e EPUBZip) Copy(fz *zip.File) error {
|
func (e *EPUBZip) Copy(fz *zip.File) error {
|
||||||
return e.wz.Copy(fz)
|
return e.wz.Copy(fz)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteRaw Write image. They are already compressed, so we write them down directly.
|
// WriteRaw Write image. They are already compressed, so we write them down directly.
|
||||||
func (e EPUBZip) WriteRaw(raw Image) error {
|
func (e *EPUBZip) WriteRaw(raw *ZipImage) 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
|
||||||
@ -77,7 +77,7 @@ func (e EPUBZip) WriteRaw(raw Image) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WriteContent Write file. Compressed it using deflate.
|
// WriteContent Write file. Compressed it using deflate.
|
||||||
func (e EPUBZip) WriteContent(file string, content []byte) error {
|
func (e *EPUBZip) WriteContent(file string, content []byte) error {
|
||||||
m, err := e.wz.CreateHeader(&zip.FileHeader{
|
m, err := e.wz.CreateHeader(&zip.FileHeader{
|
||||||
Name: file,
|
Name: file,
|
||||||
Modified: time.Now(),
|
Modified: time.Now(),
|
@ -12,13 +12,13 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Image struct {
|
type ZipImage struct {
|
||||||
Header *zip.FileHeader
|
Header *zip.FileHeader
|
||||||
Data []byte
|
Data []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// CompressImage create gzip encoded jpeg
|
// CompressImage create gzip encoded jpeg
|
||||||
func CompressImage(filename string, format string, img image.Image, quality int) (Image, error) {
|
func CompressImage(filename string, format string, img image.Image, quality int) (*ZipImage, error) {
|
||||||
var (
|
var (
|
||||||
data, cdata bytes.Buffer
|
data, cdata bytes.Buffer
|
||||||
err error
|
err error
|
||||||
@ -33,27 +33,27 @@ func CompressImage(filename string, format string, img image.Image, quality int)
|
|||||||
err = fmt.Errorf("unknown format %q", format)
|
err = fmt.Errorf("unknown format %q", format)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Image{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
wcdata, err := flate.NewWriter(&cdata, flate.BestCompression)
|
wcdata, err := flate.NewWriter(&cdata, flate.BestCompression)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Image{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = wcdata.Write(data.Bytes())
|
_, err = wcdata.Write(data.Bytes())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Image{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = wcdata.Close()
|
err = wcdata.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Image{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
//goland:noinspection GoDeprecation
|
//goland:noinspection GoDeprecation
|
||||||
return Image{
|
return &ZipImage{
|
||||||
&zip.FileHeader{
|
&zip.FileHeader{
|
||||||
Name: filename,
|
Name: filename,
|
||||||
CompressedSize64: uint64(cdata.Len()),
|
CompressedSize64: uint64(cdata.Len()),
|
||||||
@ -66,39 +66,3 @@ func CompressImage(filename string, format string, img image.Image, quality int)
|
|||||||
cdata.Bytes(),
|
cdata.Bytes(),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func CompressRaw(filename string, uncompressedData []byte) (Image, error) {
|
|
||||||
var (
|
|
||||||
cdata bytes.Buffer
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
wcdata, err := flate.NewWriter(&cdata, flate.BestCompression)
|
|
||||||
if err != nil {
|
|
||||||
return Image{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = wcdata.Write(uncompressedData)
|
|
||||||
if err != nil {
|
|
||||||
return Image{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = wcdata.Close()
|
|
||||||
if err != nil {
|
|
||||||
return Image{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
t := time.Now()
|
|
||||||
//goland:noinspection GoDeprecation
|
|
||||||
return Image{
|
|
||||||
&zip.FileHeader{
|
|
||||||
Name: filename,
|
|
||||||
CompressedSize64: uint64(cdata.Len()),
|
|
||||||
UncompressedSize64: uint64(len(uncompressedData)),
|
|
||||||
CRC32: crc32.Checksum(uncompressedData, crc32.IEEETable),
|
|
||||||
Method: zip.Deflate,
|
|
||||||
ModifiedTime: uint16(t.Second()/2 + t.Minute()<<5 + t.Hour()<<11),
|
|
||||||
ModifiedDate: uint16(t.Day() + int(t.Month())<<5 + (t.Year()-1980)<<9),
|
|
||||||
},
|
|
||||||
cdata.Bytes(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
100
internal/epub/zip/epub_zip_storage_image.go
Normal file
100
internal/epub/zip/epub_zip_storage_image.go
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
package epubzip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"image"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type StorageImageWriter struct {
|
||||||
|
fh *os.File
|
||||||
|
fz *zip.Writer
|
||||||
|
format string
|
||||||
|
mut *sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStorageImageWriter(filename string, format string) (*StorageImageWriter, error) {
|
||||||
|
fh, err := os.Create(filename)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fz := zip.NewWriter(fh)
|
||||||
|
return &StorageImageWriter{fh, fz, format, &sync.Mutex{}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageWriter) Close() error {
|
||||||
|
if err := e.fz.Close(); err != nil {
|
||||||
|
_ = e.fh.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.fh.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageWriter) 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 StorageImageReader struct {
|
||||||
|
filename string
|
||||||
|
fh *os.File
|
||||||
|
fz *zip.Reader
|
||||||
|
|
||||||
|
files map[string]*zip.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStorageImageReader(filename string) (*StorageImageReader, 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 &StorageImageReader{filename, fh, fz, files}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageReader) Get(filename string) *zip.File {
|
||||||
|
return e.files[filename]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageReader) Size(filename string) uint64 {
|
||||||
|
img := e.Get(filename)
|
||||||
|
if img != nil {
|
||||||
|
return img.CompressedSize64 + 30 + uint64(len(img.Name))
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageReader) Close() error {
|
||||||
|
return e.fh.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageImageReader) Remove() error {
|
||||||
|
return os.Remove(e.filename)
|
||||||
|
}
|
@ -1,251 +0,0 @@
|
|||||||
// Package converter options manage options with default value from config.
|
|
||||||
package converter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
epuboptions.EPUBOptions
|
|
||||||
|
|
||||||
// Config
|
|
||||||
Profile string `yaml:"profile" json:"profile"`
|
|
||||||
|
|
||||||
// Default Config
|
|
||||||
Show bool `yaml:"-" json:"-"`
|
|
||||||
Save bool `yaml:"-" json:"-"`
|
|
||||||
Reset bool `yaml:"-" json:"-"`
|
|
||||||
|
|
||||||
// Shortcut
|
|
||||||
Auto bool `yaml:"-" json:"-"`
|
|
||||||
NoFilter bool `yaml:"-" json:"-"`
|
|
||||||
MaxQuality bool `yaml:"-" json:"-"`
|
|
||||||
BestQuality bool `yaml:"-" json:"-"`
|
|
||||||
GreatQuality bool `yaml:"-" json:"-"`
|
|
||||||
GoodQuality bool `yaml:"-" json:"-"`
|
|
||||||
|
|
||||||
// Other
|
|
||||||
Version bool `yaml:"-" json:"-"`
|
|
||||||
Help bool `yaml:"-" json:"-"`
|
|
||||||
|
|
||||||
// Internal
|
|
||||||
profiles Profiles
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewOptions Initialize default options.
|
|
||||||
func NewOptions() *Options {
|
|
||||||
return &Options{
|
|
||||||
Profile: "SR",
|
|
||||||
EPUBOptions: epuboptions.EPUBOptions{
|
|
||||||
Image: epuboptions.Image{
|
|
||||||
Quality: 85,
|
|
||||||
GrayScale: true,
|
|
||||||
Crop: epuboptions.Crop{
|
|
||||||
Enabled: true,
|
|
||||||
Left: 1,
|
|
||||||
Up: 1,
|
|
||||||
Right: 1,
|
|
||||||
Bottom: 3,
|
|
||||||
},
|
|
||||||
NoBlankImage: true,
|
|
||||||
HasCover: true,
|
|
||||||
KeepDoublePageIfSplit: true,
|
|
||||||
KeepSplitDoublePageAspect: true,
|
|
||||||
View: epuboptions.View{
|
|
||||||
Color: epuboptions.Color{
|
|
||||||
Foreground: "000",
|
|
||||||
Background: "FFF",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Resize: true,
|
|
||||||
Format: "jpeg",
|
|
||||||
},
|
|
||||||
TitlePage: 1,
|
|
||||||
SortPathMode: 1,
|
|
||||||
},
|
|
||||||
profiles: NewProfiles(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *Options) Header() string {
|
|
||||||
return "Go Comic Converter\n\nOptions:"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *Options) String() string {
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString(o.Header())
|
|
||||||
for _, v := range []struct {
|
|
||||||
K string
|
|
||||||
V any
|
|
||||||
}{
|
|
||||||
{"Input", o.Input},
|
|
||||||
{"Output", o.Output},
|
|
||||||
{"Author", o.Author},
|
|
||||||
{"Title", o.Title},
|
|
||||||
{"Workers", o.Workers},
|
|
||||||
} {
|
|
||||||
b.WriteString(fmt.Sprintf("\n %-32s: %v", v.K, v.V))
|
|
||||||
}
|
|
||||||
b.WriteString(o.ShowConfig())
|
|
||||||
b.WriteRune('\n')
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// FileName Config file: ~/.go-comic-converter.yaml
|
|
||||||
func (o *Options) FileName() string {
|
|
||||||
home, _ := os.UserHomeDir()
|
|
||||||
return filepath.Join(home, ".go-comic-converter.yaml")
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoadConfig Load config files
|
|
||||||
func (o *Options) LoadConfig() error {
|
|
||||||
f, err := os.Open(o.FileName())
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
defer func(f *os.File) {
|
|
||||||
_ = f.Close()
|
|
||||||
}(f)
|
|
||||||
err = yaml.NewDecoder(f).Decode(o)
|
|
||||||
if err != nil && err.Error() != "EOF" {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ShowConfig Get current settings for fields that can be saved
|
|
||||||
func (o *Options) ShowConfig() string {
|
|
||||||
var profileDesc string
|
|
||||||
profile := o.GetProfile()
|
|
||||||
if profile != nil {
|
|
||||||
profileDesc = profile.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
sortpathmode := ""
|
|
||||||
switch o.SortPathMode {
|
|
||||||
case 0:
|
|
||||||
sortpathmode = "path=alpha, file=alpha"
|
|
||||||
case 1:
|
|
||||||
sortpathmode = "path=alphanumeric, file=alpha"
|
|
||||||
case 2:
|
|
||||||
sortpathmode = "path=alphanumeric, file=alphanumeric"
|
|
||||||
}
|
|
||||||
|
|
||||||
aspectRatio := "auto"
|
|
||||||
if o.Image.View.AspectRatio > 0 {
|
|
||||||
aspectRatio = "1:" + utils.FloatToString(o.Image.View.AspectRatio, 2)
|
|
||||||
} else if o.Image.View.AspectRatio < 0 {
|
|
||||||
if profile != nil {
|
|
||||||
aspectRatio = "1:" + utils.FloatToString(float64(profile.Height)/float64(profile.Width), 2) + " (device)"
|
|
||||||
} else {
|
|
||||||
aspectRatio = "1:?? (device)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
titlePage := ""
|
|
||||||
switch o.TitlePage {
|
|
||||||
case 0:
|
|
||||||
titlePage = "never"
|
|
||||||
case 1:
|
|
||||||
titlePage = "always"
|
|
||||||
case 2:
|
|
||||||
titlePage = "when epub is split"
|
|
||||||
}
|
|
||||||
|
|
||||||
grayscaleMode := "normal"
|
|
||||||
switch o.Image.GrayScaleMode {
|
|
||||||
case 1:
|
|
||||||
grayscaleMode = "average"
|
|
||||||
case 2:
|
|
||||||
grayscaleMode = "luminance"
|
|
||||||
}
|
|
||||||
|
|
||||||
var b strings.Builder
|
|
||||||
for _, v := range []struct {
|
|
||||||
Key string
|
|
||||||
Value any
|
|
||||||
Condition bool
|
|
||||||
}{
|
|
||||||
{"Profile", profileDesc, true},
|
|
||||||
{"Format", o.Image.Format, true},
|
|
||||||
{"Quality", o.Image.Quality, o.Image.Format == "jpeg"},
|
|
||||||
{"Grayscale", o.Image.GrayScale, o.Image.Format != "copy"},
|
|
||||||
{"Grayscale mode", grayscaleMode, o.Image.Format != "copy" && o.Image.GrayScale},
|
|
||||||
{"Crop", o.Image.Crop.Enabled, o.Image.Format != "copy"},
|
|
||||||
{"Crop ratio",
|
|
||||||
utils.IntToString(o.Image.Crop.Left) + " Left - " +
|
|
||||||
utils.IntToString(o.Image.Crop.Up) + " Up - " +
|
|
||||||
utils.IntToString(o.Image.Crop.Right) + " Right - " +
|
|
||||||
utils.IntToString(o.Image.Crop.Bottom) + " Bottom - " +
|
|
||||||
"Limit " + utils.IntToString(o.Image.Crop.Limit) + "% - " +
|
|
||||||
"Skip " + utils.BoolToString(o.Image.Crop.SkipIfLimitReached),
|
|
||||||
o.Image.Format != "copy" && o.Image.Crop.Enabled},
|
|
||||||
{"Brightness", o.Image.Brightness, o.Image.Format != "copy" && o.Image.Brightness != 0},
|
|
||||||
{"Contrast", o.Image.Contrast, o.Image.Format != "copy" && o.Image.Contrast != 0},
|
|
||||||
{"Auto contrast", o.Image.AutoContrast, o.Image.Format != "copy"},
|
|
||||||
{"Auto rotate", o.Image.AutoRotate, o.Image.Format != "copy"},
|
|
||||||
{"Auto split double page", o.Image.AutoSplitDoublePage, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility)},
|
|
||||||
{"Keep double page if split", o.Image.KeepDoublePageIfSplit, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
|
|
||||||
{"Keep split double page aspect", o.Image.KeepSplitDoublePageAspect, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
|
|
||||||
{"No blank image", o.Image.NoBlankImage, o.Image.Format != "copy"},
|
|
||||||
{"Manga", o.Image.Manga, true},
|
|
||||||
{"Has cover", o.Image.HasCover, true},
|
|
||||||
{"Limit", utils.IntToString(o.LimitMb) + " Mb", o.LimitMb != 0},
|
|
||||||
{"Strip first directory from toc", o.StripFirstDirectoryFromToc, true},
|
|
||||||
{"Sort path mode", sortpathmode, true},
|
|
||||||
{"Foreground color", "#" + o.Image.View.Color.Foreground, true},
|
|
||||||
{"Background color", "#" + o.Image.View.Color.Background, true},
|
|
||||||
{"Resize", o.Image.Resize, o.Image.Format != "copy"},
|
|
||||||
{"Aspect ratio", aspectRatio, true},
|
|
||||||
{"Portrait only", o.Image.View.PortraitOnly, true},
|
|
||||||
{"Title page", titlePage, true},
|
|
||||||
{"Apple book compatibility", o.Image.AppleBookCompatibility, !o.Image.View.PortraitOnly},
|
|
||||||
} {
|
|
||||||
if v.Condition {
|
|
||||||
b.WriteString(fmt.Sprintf("\n %-32s: %v", v.Key, v.Value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResetConfig reset all settings to default value
|
|
||||||
func (o *Options) ResetConfig() error {
|
|
||||||
if err := NewOptions().SaveConfig(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return o.LoadConfig()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SaveConfig save all current settings as default value
|
|
||||||
func (o *Options) SaveConfig() error {
|
|
||||||
f, err := os.Create(o.FileName())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func(f *os.File) {
|
|
||||||
_ = f.Close()
|
|
||||||
}(f)
|
|
||||||
return yaml.NewEncoder(f).Encode(o)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetProfile shortcut to get current profile
|
|
||||||
func (o *Options) GetProfile() *Profile {
|
|
||||||
if p, ok := o.profiles[o.Profile]; ok {
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AvailableProfiles all available profiles
|
|
||||||
func (o *Options) AvailableProfiles() string {
|
|
||||||
return o.profiles.String()
|
|
||||||
}
|
|
@ -1,432 +0,0 @@
|
|||||||
package epubimagepassthrough
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/zip"
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"image"
|
|
||||||
"image/jpeg"
|
|
||||||
"image/png"
|
|
||||||
"io"
|
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/nwaples/rardecode/v2"
|
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimageprocessor"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubprogress"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubzip"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/sortpath"
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ePUBImagePassthrough struct {
|
|
||||||
epuboptions.EPUBOptions
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) Load() (images []epubimage.EPUBImage, err error) {
|
|
||||||
fi, err := os.Stat(e.Input)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if fi.IsDir() {
|
|
||||||
return e.loadDir()
|
|
||||||
} else {
|
|
||||||
switch ext := strings.ToLower(filepath.Ext(e.Input)); ext {
|
|
||||||
case ".cbz", ".zip":
|
|
||||||
return e.loadCbz()
|
|
||||||
case ".cbr", ".rar":
|
|
||||||
return e.loadCbr()
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unknown file format (%s): support .cbz, .zip, .cbr, .rar", ext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) CoverTitleData(o epubimageprocessor.CoverTitleDataOptions) (epubzip.Image, error) {
|
|
||||||
return epubimageprocessor.New(e.EPUBOptions).CoverTitleData(o)
|
|
||||||
}
|
|
||||||
|
|
||||||
var errNoImagesFound = errors.New("no images found")
|
|
||||||
|
|
||||||
func New(o epuboptions.EPUBOptions) epubimageprocessor.EPUBImageProcessor {
|
|
||||||
return ePUBImagePassthrough{o}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) loadDir() (images []epubimage.EPUBImage, err error) {
|
|
||||||
imagesPath := make([]string, 0)
|
|
||||||
|
|
||||||
input := filepath.Clean(e.Input)
|
|
||||||
err = filepath.WalkDir(input, func(path string, d fs.DirEntry, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !d.IsDir() && e.isSupportedImage(path) {
|
|
||||||
imagesPath = append(imagesPath, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(imagesPath) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Sort(sortpath.By(imagesPath, e.SortPathMode))
|
|
||||||
|
|
||||||
var imgStorage epubzip.StorageImageWriter
|
|
||||||
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer imgStorage.Close()
|
|
||||||
|
|
||||||
// processing
|
|
||||||
bar := epubprogress.New(epubprogress.Options{
|
|
||||||
Quiet: e.Quiet,
|
|
||||||
Json: e.Json,
|
|
||||||
Max: len(imagesPath),
|
|
||||||
Description: "Copying",
|
|
||||||
CurrentJob: 1,
|
|
||||||
TotalJob: 2,
|
|
||||||
})
|
|
||||||
defer bar.Close()
|
|
||||||
|
|
||||||
for i, imgPath := range imagesPath {
|
|
||||||
|
|
||||||
var img epubimage.EPUBImage
|
|
||||||
img, err = e.copyRawDataToStorage(
|
|
||||||
imgStorage,
|
|
||||||
func() ([]byte, error) {
|
|
||||||
f, err := os.Open(imgPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
return io.ReadAll(f)
|
|
||||||
},
|
|
||||||
i,
|
|
||||||
input,
|
|
||||||
imgPath,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
images = append(images, img)
|
|
||||||
_ = bar.Add(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(images) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) loadCbz() (images []epubimage.EPUBImage, err error) {
|
|
||||||
images = make([]epubimage.EPUBImage, 0)
|
|
||||||
|
|
||||||
input := filepath.Clean(e.Input)
|
|
||||||
r, err := zip.OpenReader(input)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer r.Close()
|
|
||||||
|
|
||||||
imagesZip := make([]*zip.File, 0)
|
|
||||||
for _, f := range r.File {
|
|
||||||
if !f.FileInfo().IsDir() && e.isSupportedImage(f.Name) {
|
|
||||||
imagesZip = append(imagesZip, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(imagesZip) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var names []string
|
|
||||||
for _, img := range imagesZip {
|
|
||||||
names = append(names, img.Name)
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Sort(sortpath.By(names, e.SortPathMode))
|
|
||||||
|
|
||||||
indexedNames := make(map[string]int)
|
|
||||||
for i, name := range names {
|
|
||||||
indexedNames[name] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
var imgStorage epubzip.StorageImageWriter
|
|
||||||
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer imgStorage.Close()
|
|
||||||
|
|
||||||
// processing
|
|
||||||
bar := epubprogress.New(epubprogress.Options{
|
|
||||||
Quiet: e.Quiet,
|
|
||||||
Json: e.Json,
|
|
||||||
Max: len(imagesZip),
|
|
||||||
Description: "Copying",
|
|
||||||
CurrentJob: 1,
|
|
||||||
TotalJob: 2,
|
|
||||||
})
|
|
||||||
defer bar.Close()
|
|
||||||
|
|
||||||
for _, imgZip := range imagesZip {
|
|
||||||
if _, ok := indexedNames[imgZip.Name]; !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var img epubimage.EPUBImage
|
|
||||||
img, err = e.copyRawDataToStorage(
|
|
||||||
imgStorage,
|
|
||||||
func() ([]byte, error) {
|
|
||||||
f, err := imgZip.Open()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
return io.ReadAll(f)
|
|
||||||
},
|
|
||||||
indexedNames[imgZip.Name],
|
|
||||||
"",
|
|
||||||
imgZip.Name,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
images = append(images, img)
|
|
||||||
_ = bar.Add(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(images) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) loadCbr() (images []epubimage.EPUBImage, err error) {
|
|
||||||
images = make([]epubimage.EPUBImage, 0)
|
|
||||||
|
|
||||||
var isSolid bool
|
|
||||||
files, err := rardecode.List(e.Input)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
names := make([]string, 0)
|
|
||||||
for _, f := range files {
|
|
||||||
if !f.IsDir && e.isSupportedImage(f.Name) {
|
|
||||||
if f.Solid {
|
|
||||||
isSolid = true
|
|
||||||
}
|
|
||||||
names = append(names, f.Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(names) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Sort(sortpath.By(names, e.SortPathMode))
|
|
||||||
|
|
||||||
indexedNames := make(map[string]int)
|
|
||||||
for i, name := range names {
|
|
||||||
indexedNames[name] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
var imgStorage epubzip.StorageImageWriter
|
|
||||||
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer imgStorage.Close()
|
|
||||||
|
|
||||||
// processing
|
|
||||||
bar := epubprogress.New(epubprogress.Options{
|
|
||||||
Quiet: e.Quiet,
|
|
||||||
Json: e.Json,
|
|
||||||
Max: len(names),
|
|
||||||
Description: "Copying",
|
|
||||||
CurrentJob: 1,
|
|
||||||
TotalJob: 2,
|
|
||||||
})
|
|
||||||
defer bar.Close()
|
|
||||||
|
|
||||||
if isSolid {
|
|
||||||
var r *rardecode.ReadCloser
|
|
||||||
r, err = rardecode.OpenReader(e.Input)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer r.Close()
|
|
||||||
|
|
||||||
for {
|
|
||||||
f, rerr := r.Next()
|
|
||||||
if rerr != nil {
|
|
||||||
if rerr == io.EOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
err = rerr
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := indexedNames[f.Name]; !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var img epubimage.EPUBImage
|
|
||||||
img, err = e.copyRawDataToStorage(
|
|
||||||
imgStorage,
|
|
||||||
func() ([]byte, error) {
|
|
||||||
return io.ReadAll(r)
|
|
||||||
},
|
|
||||||
indexedNames[f.Name],
|
|
||||||
"",
|
|
||||||
f.Name,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
images = append(images, img)
|
|
||||||
_ = bar.Add(1)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for _, file := range files {
|
|
||||||
if i, ok := indexedNames[file.Name]; ok {
|
|
||||||
var img epubimage.EPUBImage
|
|
||||||
img, err = e.copyRawDataToStorage(
|
|
||||||
imgStorage,
|
|
||||||
func() ([]byte, error) {
|
|
||||||
f, err := file.Open()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
return io.ReadAll(f)
|
|
||||||
},
|
|
||||||
i,
|
|
||||||
"",
|
|
||||||
file.Name,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
images = append(images, img)
|
|
||||||
_ = bar.Add(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(images) == 0 {
|
|
||||||
err = errNoImagesFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) isSupportedImage(path string) bool {
|
|
||||||
switch strings.ToLower(filepath.Ext(path)) {
|
|
||||||
case ".jpg", ".jpeg", ".png":
|
|
||||||
{
|
|
||||||
return !strings.HasPrefix(filepath.Base(path), ".")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ePUBImagePassthrough) copyRawDataToStorage(
|
|
||||||
imgStorage epubzip.StorageImageWriter,
|
|
||||||
getData func() ([]byte, error),
|
|
||||||
id int,
|
|
||||||
dirname string,
|
|
||||||
filename string,
|
|
||||||
) (img epubimage.EPUBImage, err error) {
|
|
||||||
var uncompressedData []byte
|
|
||||||
uncompressedData, err = getData()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
p, fn := filepath.Split(filepath.Clean(filename))
|
|
||||||
if p == dirname {
|
|
||||||
p = ""
|
|
||||||
} else {
|
|
||||||
p = p[len(dirname)+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
format string
|
|
||||||
decodeConfig func(r io.Reader) (image.Config, error)
|
|
||||||
decode func(r io.Reader) (image.Image, error)
|
|
||||||
)
|
|
||||||
|
|
||||||
switch filepath.Ext(fn) {
|
|
||||||
case ".png":
|
|
||||||
format = "png"
|
|
||||||
decodeConfig = png.DecodeConfig
|
|
||||||
decode = png.Decode
|
|
||||||
case ".jpg", ".jpeg":
|
|
||||||
format = "jpeg"
|
|
||||||
decodeConfig = jpeg.DecodeConfig
|
|
||||||
decode = jpeg.Decode
|
|
||||||
}
|
|
||||||
|
|
||||||
var config image.Config
|
|
||||||
config, err = decodeConfig(bytes.NewReader(uncompressedData))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var rawImage image.Image
|
|
||||||
if id == 0 {
|
|
||||||
rawImage, err = decode(bytes.NewReader(uncompressedData))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
img = epubimage.EPUBImage{
|
|
||||||
Id: id,
|
|
||||||
Part: 0,
|
|
||||||
Raw: rawImage,
|
|
||||||
Width: config.Width,
|
|
||||||
Height: config.Height,
|
|
||||||
IsBlank: false,
|
|
||||||
DoublePage: config.Width > config.Height,
|
|
||||||
Path: p,
|
|
||||||
Name: fn,
|
|
||||||
Format: format,
|
|
||||||
OriginalAspectRatio: float64(config.Height) / float64(config.Width),
|
|
||||||
}
|
|
||||||
|
|
||||||
err = imgStorage.AddRaw(img.EPUBImgPath(), uncompressedData)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
package epubtemplates
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed "applebooks.xml.tmpl"
|
|
||||||
var AppleBooks string
|
|
@ -1,7 +0,0 @@
|
|||||||
// Package epubtemplates Templates use to create xml files of the EPUB.
|
|
||||||
package epubtemplates
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed "blank.xhtml.tmpl"
|
|
||||||
var Blank string
|
|
@ -1,6 +0,0 @@
|
|||||||
package epubtemplates
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed "container.xml.tmpl"
|
|
||||||
var Container string
|
|
@ -1,6 +0,0 @@
|
|||||||
package epubtemplates
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed "style.css.tmpl"
|
|
||||||
var Style string
|
|
@ -1,6 +0,0 @@
|
|||||||
package epubtemplates
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed "text.xhtml.tmpl"
|
|
||||||
var Text string
|
|
@ -1,53 +0,0 @@
|
|||||||
package epubzip
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/zip"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
type StorageImageReader struct {
|
|
||||||
filename string
|
|
||||||
fh *os.File
|
|
||||||
fz *zip.Reader
|
|
||||||
|
|
||||||
files map[string]*zip.File
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStorageImageReader(filename string) (StorageImageReader, error) {
|
|
||||||
fh, err := os.Open(filename)
|
|
||||||
if err != nil {
|
|
||||||
return StorageImageReader{}, err
|
|
||||||
}
|
|
||||||
s, err := fh.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return StorageImageReader{}, err
|
|
||||||
}
|
|
||||||
fz, err := zip.NewReader(fh, s.Size())
|
|
||||||
if err != nil {
|
|
||||||
return StorageImageReader{}, err
|
|
||||||
}
|
|
||||||
files := map[string]*zip.File{}
|
|
||||||
for _, z := range fz.File {
|
|
||||||
files[z.Name] = z
|
|
||||||
}
|
|
||||||
return StorageImageReader{filename, fh, fz, files}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageReader) Get(filename string) *zip.File {
|
|
||||||
return e.files[filename]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageReader) Size(filename string) uint64 {
|
|
||||||
if img, ok := e.files[filename]; ok {
|
|
||||||
return img.CompressedSize64 + 30 + uint64(len(img.Name))
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageReader) Close() error {
|
|
||||||
return e.fh.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageReader) Remove() error {
|
|
||||||
return os.Remove(e.filename)
|
|
||||||
}
|
|
@ -1,73 +0,0 @@
|
|||||||
package epubzip
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/zip"
|
|
||||||
"image"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type StorageImageWriter struct {
|
|
||||||
fh *os.File
|
|
||||||
fz *zip.Writer
|
|
||||||
format string
|
|
||||||
mut *sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStorageImageWriter(filename string, format string) (StorageImageWriter, error) {
|
|
||||||
fh, err := os.Create(filename)
|
|
||||||
if err != nil {
|
|
||||||
return StorageImageWriter{}, err
|
|
||||||
}
|
|
||||||
fz := zip.NewWriter(fh)
|
|
||||||
return StorageImageWriter{fh, fz, format, &sync.Mutex{}}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageWriter) Close() error {
|
|
||||||
if err := e.fz.Close(); err != nil {
|
|
||||||
_ = e.fh.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return e.fh.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageWriter) 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
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e StorageImageWriter) AddRaw(filename string, uncompressedData []byte) error {
|
|
||||||
zipImage, err := CompressRaw(filename, uncompressedData)
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
@ -1,56 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Printf(format string, a ...interface{}) {
|
|
||||||
_, _ = fmt.Fprintf(os.Stderr, format, a...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Fatalf(format string, args ...interface{}) {
|
|
||||||
Printf(format, args...)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Println(a ...interface{}) {
|
|
||||||
_, _ = fmt.Fprintln(os.Stderr, a...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Fatalln(a ...interface{}) {
|
|
||||||
Println(a...)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func IntToString(i int) string {
|
|
||||||
return strconv.FormatInt(int64(i), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
func FloatToString(f float64, precision int) string {
|
|
||||||
return strconv.FormatFloat(f, 'f', precision, 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
func BoolToString(b bool) string {
|
|
||||||
if b {
|
|
||||||
return "true"
|
|
||||||
}
|
|
||||||
return "false"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NumberOfDigits(i int) int {
|
|
||||||
x, count := 10, 1
|
|
||||||
if i < 0 {
|
|
||||||
i = -i
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
for ; x <= i; count++ {
|
|
||||||
x *= 10
|
|
||||||
}
|
|
||||||
return count
|
|
||||||
}
|
|
||||||
|
|
||||||
func FormatNumberOfDigits(i int) string {
|
|
||||||
return "%0" + IntToString(NumberOfDigits(i)) + "d"
|
|
||||||
}
|
|
@ -1,62 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
func ExampleFloatToString() {
|
|
||||||
fmt.Println("test=" + FloatToString(3.14151617, 0) + "=")
|
|
||||||
fmt.Println("test=" + FloatToString(3.14151617, 1) + "=")
|
|
||||||
fmt.Println("test=" + FloatToString(3.14151617, 2) + "=")
|
|
||||||
fmt.Println("test=" + FloatToString(3.14151617, 4) + "=")
|
|
||||||
// Output: test=3=
|
|
||||||
// test=3.1=
|
|
||||||
// test=3.14=
|
|
||||||
// test=3.1415=
|
|
||||||
}
|
|
||||||
|
|
||||||
func ExampleIntToString() {
|
|
||||||
fmt.Println("test=" + IntToString(159) + "=")
|
|
||||||
// Output: test=159=
|
|
||||||
}
|
|
||||||
|
|
||||||
func ExampleNumberOfDigits() {
|
|
||||||
fmt.Println(NumberOfDigits(0))
|
|
||||||
fmt.Println(NumberOfDigits(4))
|
|
||||||
fmt.Println(NumberOfDigits(10))
|
|
||||||
fmt.Println(NumberOfDigits(14))
|
|
||||||
fmt.Println(NumberOfDigits(256))
|
|
||||||
fmt.Println(NumberOfDigits(2004))
|
|
||||||
fmt.Println(NumberOfDigits(-5))
|
|
||||||
fmt.Println(NumberOfDigits(-10))
|
|
||||||
fmt.Println(NumberOfDigits(-12))
|
|
||||||
|
|
||||||
// Output: 1
|
|
||||||
// 1
|
|
||||||
// 2
|
|
||||||
// 2
|
|
||||||
// 3
|
|
||||||
// 4
|
|
||||||
// 2
|
|
||||||
// 3
|
|
||||||
// 3
|
|
||||||
}
|
|
||||||
|
|
||||||
func ExampleFormatNumberOfDigits() {
|
|
||||||
fmt.Println(FormatNumberOfDigits(0))
|
|
||||||
fmt.Println(FormatNumberOfDigits(4))
|
|
||||||
fmt.Println(FormatNumberOfDigits(10))
|
|
||||||
fmt.Println(FormatNumberOfDigits(14))
|
|
||||||
fmt.Println(FormatNumberOfDigits(256))
|
|
||||||
fmt.Println(FormatNumberOfDigits(2004))
|
|
||||||
fmt.Println(FormatNumberOfDigits(-5))
|
|
||||||
fmt.Println(FormatNumberOfDigits(-10))
|
|
||||||
fmt.Println(FormatNumberOfDigits(-12))
|
|
||||||
// Output: %01d
|
|
||||||
// %01d
|
|
||||||
// %02d
|
|
||||||
// %02d
|
|
||||||
// %03d
|
|
||||||
// %04d
|
|
||||||
// %02d
|
|
||||||
// %03d
|
|
||||||
// %03d
|
|
||||||
}
|
|
14
internal/utils/utils.go
Normal file
14
internal/utils/utils.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Printf(format string, a ...interface{}) {
|
||||||
|
_, _ = fmt.Fprintf(os.Stderr, format, a...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Println(a ...interface{}) {
|
||||||
|
_, _ = fmt.Fprintln(os.Stderr, a...)
|
||||||
|
}
|
118
main.go
118
main.go
@ -14,9 +14,10 @@ import (
|
|||||||
|
|
||||||
"github.com/tcnksm/go-latest"
|
"github.com/tcnksm/go-latest"
|
||||||
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/converter"
|
"github.com/celogeek/go-comic-converter/v2/internal/converter"
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
"github.com/celogeek/go-comic-converter/v2/internal/epub"
|
||||||
"github.com/celogeek/go-comic-converter/v3/pkg/epub"
|
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options"
|
||||||
|
"github.com/celogeek/go-comic-converter/v2/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@ -27,25 +28,11 @@ func main() {
|
|||||||
cmd.InitParse()
|
cmd.InitParse()
|
||||||
cmd.Parse()
|
cmd.Parse()
|
||||||
|
|
||||||
switch {
|
if cmd.Options.Version {
|
||||||
case cmd.Options.Version:
|
|
||||||
version()
|
|
||||||
case cmd.Options.Save:
|
|
||||||
save(cmd)
|
|
||||||
case cmd.Options.Show:
|
|
||||||
show(cmd)
|
|
||||||
case cmd.Options.Reset:
|
|
||||||
reset(cmd)
|
|
||||||
default:
|
|
||||||
generate(cmd)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func version() {
|
|
||||||
bi, ok := debug.ReadBuildInfo()
|
bi, ok := debug.ReadBuildInfo()
|
||||||
if !ok {
|
if !ok {
|
||||||
utils.Fatalln("failed to fetch current version")
|
utils.Println("failed to fetch current version")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
githubTag := &latest.GithubTag{
|
githubTag := &latest.GithubTag{
|
||||||
@ -53,11 +40,9 @@ func version() {
|
|||||||
Repository: "go-comic-converter",
|
Repository: "go-comic-converter",
|
||||||
}
|
}
|
||||||
v, err := githubTag.Fetch()
|
v, err := githubTag.Fetch()
|
||||||
if err != nil {
|
if err != nil || len(v.Versions) < 1 {
|
||||||
utils.Fatalln("failed to fetch the latest version")
|
utils.Println("failed to fetch the latest version")
|
||||||
}
|
os.Exit(1)
|
||||||
if len(v.Versions) < 1 {
|
|
||||||
utils.Fatalln("no versions found")
|
|
||||||
}
|
}
|
||||||
latestVersion := v.Versions[0]
|
latestVersion := v.Versions[0]
|
||||||
|
|
||||||
@ -77,9 +62,10 @@ $ go install github.com/celogeek/go-comic-converter/v%d@%s
|
|||||||
latestVersion.Segments()[0],
|
latestVersion.Segments()[0],
|
||||||
latestVersion.Original(),
|
latestVersion.Original(),
|
||||||
)
|
)
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func save(cmd *converter.Converter) {
|
if cmd.Options.Save {
|
||||||
if err := cmd.Options.SaveConfig(); err != nil {
|
if err := cmd.Options.SaveConfig(); err != nil {
|
||||||
cmd.Fatal(err)
|
cmd.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -89,13 +75,15 @@ func save(cmd *converter.Converter) {
|
|||||||
cmd.Options.ShowConfig(),
|
cmd.Options.ShowConfig(),
|
||||||
cmd.Options.FileName(),
|
cmd.Options.FileName(),
|
||||||
)
|
)
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func show(cmd *converter.Converter) {
|
if cmd.Options.Show {
|
||||||
utils.Println(cmd.Options.Header(), cmd.Options.ShowConfig())
|
utils.Println(cmd.Options.Header(), cmd.Options.ShowConfig())
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func reset(cmd *converter.Converter) {
|
if cmd.Options.Reset {
|
||||||
if err := cmd.Options.ResetConfig(); err != nil {
|
if err := cmd.Options.ResetConfig(); err != nil {
|
||||||
cmd.Fatal(err)
|
cmd.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -105,16 +93,11 @@ func reset(cmd *converter.Converter) {
|
|||||||
cmd.Options.ShowConfig(),
|
cmd.Options.ShowConfig(),
|
||||||
cmd.Options.FileName(),
|
cmd.Options.FileName(),
|
||||||
)
|
)
|
||||||
}
|
return
|
||||||
|
|
||||||
func generate(cmd *converter.Converter) {
|
|
||||||
if err := cmd.Validate(); err != nil {
|
|
||||||
cmd.Fatal(err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if profile := cmd.Options.GetProfile(); profile != nil {
|
if err := cmd.Validate(); err != nil {
|
||||||
cmd.Options.Image.View.Width = profile.Width
|
cmd.Fatal(err)
|
||||||
cmd.Options.Image.View.Height = profile.Height
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if cmd.Options.Json {
|
if cmd.Options.Json {
|
||||||
@ -125,8 +108,61 @@ func generate(cmd *converter.Converter) {
|
|||||||
utils.Println(cmd.Options)
|
utils.Println(cmd.Options)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := epub.New(cmd.Options.EPUBOptions).Write(); err != nil {
|
profile := cmd.Options.GetProfile()
|
||||||
utils.Fatalf("Error: %v\n", err)
|
|
||||||
|
if err := epub.New(&epuboptions.Options{
|
||||||
|
Input: cmd.Options.Input,
|
||||||
|
Output: cmd.Options.Output,
|
||||||
|
LimitMb: cmd.Options.LimitMb,
|
||||||
|
Title: cmd.Options.Title,
|
||||||
|
TitlePage: cmd.Options.TitlePage,
|
||||||
|
Author: cmd.Options.Author,
|
||||||
|
StripFirstDirectoryFromToc: cmd.Options.StripFirstDirectoryFromToc,
|
||||||
|
SortPathMode: cmd.Options.SortPathMode,
|
||||||
|
Workers: cmd.Options.Workers,
|
||||||
|
Dry: cmd.Options.Dry,
|
||||||
|
DryVerbose: cmd.Options.DryVerbose,
|
||||||
|
Quiet: cmd.Options.Quiet,
|
||||||
|
Json: cmd.Options.Json,
|
||||||
|
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,
|
||||||
|
Limit: cmd.Options.CropLimit,
|
||||||
|
SkipIfLimitReached: cmd.Options.CropSkipIfLimitReached,
|
||||||
|
},
|
||||||
|
Quality: cmd.Options.Quality,
|
||||||
|
Brightness: cmd.Options.Brightness,
|
||||||
|
Contrast: cmd.Options.Contrast,
|
||||||
|
AutoContrast: cmd.Options.AutoContrast,
|
||||||
|
AutoRotate: cmd.Options.AutoRotate,
|
||||||
|
AutoSplitDoublePage: cmd.Options.AutoSplitDoublePage,
|
||||||
|
KeepDoublePageIfSplit: cmd.Options.KeepDoublePageIfSplit,
|
||||||
|
NoBlankImage: cmd.Options.NoBlankImage,
|
||||||
|
Manga: cmd.Options.Manga,
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
GrayScale: cmd.Options.Grayscale,
|
||||||
|
GrayScaleMode: cmd.Options.GrayscaleMode,
|
||||||
|
Resize: !cmd.Options.NoResize,
|
||||||
|
Format: cmd.Options.Format,
|
||||||
|
AppleBookCompatibility: cmd.Options.AppleBookCompatibility,
|
||||||
|
},
|
||||||
|
}).Write(); err != nil {
|
||||||
|
utils.Printf("Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
if !cmd.Options.Dry {
|
if !cmd.Options.Dry {
|
||||||
cmd.Stats()
|
cmd.Stats()
|
||||||
|
@ -1,6 +0,0 @@
|
|||||||
package epuboptions
|
|
||||||
|
|
||||||
type Color struct {
|
|
||||||
Foreground string `yaml:"foreground" json:"foreground"`
|
|
||||||
Background string `yaml:"background" json:"background"`
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
package epuboptions
|
|
||||||
|
|
||||||
type Crop struct {
|
|
||||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
|
||||||
Left int `yaml:"left" json:"left"`
|
|
||||||
Up int `yaml:"up" json:"up"`
|
|
||||||
Right int `yaml:"right" json:"right"`
|
|
||||||
Bottom int `yaml:"bottom" json:"bottom"`
|
|
||||||
Limit int `yaml:"limit" json:"limit"`
|
|
||||||
SkipIfLimitReached bool `yaml:"skip_if_limit_reached" json:"skip_if_limit_reached"`
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
// Package epuboptions for EPUB creation.
|
|
||||||
package epuboptions
|
|
||||||
|
|
||||||
type EPUBOptions struct {
|
|
||||||
// Output
|
|
||||||
Input string `yaml:"-" json:"input"`
|
|
||||||
Output string `yaml:"-" json:"output"`
|
|
||||||
Author string `yaml:"-" json:"author"`
|
|
||||||
Title string `yaml:"-" json:"title"`
|
|
||||||
|
|
||||||
//Config
|
|
||||||
TitlePage int `yaml:"title_page" json:"title_page"`
|
|
||||||
LimitMb int `yaml:"limit_mb" json:"limit_mb"`
|
|
||||||
StripFirstDirectoryFromToc bool `yaml:"strip_first_directory" json:"strip_first_directory"`
|
|
||||||
SortPathMode int `yaml:"sort_path_mode" json:"sort_path_mode"`
|
|
||||||
Image Image `yaml:"image" json:"image"`
|
|
||||||
|
|
||||||
// Other
|
|
||||||
Dry bool `yaml:"-" json:"dry"`
|
|
||||||
DryVerbose bool `yaml:"-" json:"dry_verbose"`
|
|
||||||
Quiet bool `yaml:"-" json:"-"`
|
|
||||||
Json bool `yaml:"-" json:"-"`
|
|
||||||
Workers int `yaml:"-" json:"workers"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o EPUBOptions) WorkersRatio(pct int) (nbWorkers int) {
|
|
||||||
nbWorkers = o.Workers * pct / 100
|
|
||||||
if nbWorkers < 1 {
|
|
||||||
nbWorkers = 1
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o EPUBOptions) ImgStorage() string {
|
|
||||||
return o.Output + ".tmp"
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
package epuboptions
|
|
||||||
|
|
||||||
type Image struct {
|
|
||||||
Crop Crop `yaml:"crop" json:"crop"`
|
|
||||||
Quality int `yaml:"quality" json:"quality"`
|
|
||||||
Brightness int `yaml:"brightness" json:"brightness"`
|
|
||||||
Contrast int `yaml:"contrast" json:"contrast"`
|
|
||||||
AutoContrast bool `yaml:"auto_contrast" json:"auto_contrast"`
|
|
||||||
AutoRotate bool `yaml:"auto_rotate" json:"auto_rotate"`
|
|
||||||
AutoSplitDoublePage bool `yaml:"auto_split_double_page" json:"auto_split_double_page"`
|
|
||||||
KeepDoublePageIfSplit bool `yaml:"keep_double_page_if_split" json:"keep_double_page_if_split"`
|
|
||||||
KeepSplitDoublePageAspect bool `yaml:"keep_split_double_page_aspect" json:"keep_split_double_page_aspect"`
|
|
||||||
NoBlankImage bool `yaml:"no_blank_image" json:"no_blank_image"`
|
|
||||||
Manga bool `yaml:"manga" json:"manga"`
|
|
||||||
HasCover bool `yaml:"has_cover" json:"has_cover"`
|
|
||||||
View View `yaml:"view" json:"view"`
|
|
||||||
GrayScale bool `yaml:"grayscale" json:"grayscale"`
|
|
||||||
GrayScaleMode int `yaml:"grayscale_mode" json:"gray_scale_mode"` // 0 = normal, 1 = average, 2 = luminance
|
|
||||||
Resize bool `yaml:"resize" json:"resize"`
|
|
||||||
Format string `yaml:"format" json:"format"`
|
|
||||||
AppleBookCompatibility bool `yaml:"apple_book_compatibility" json:"apple_book_compatibility"`
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
package epuboptions
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/celogeek/go-comic-converter/v3/internal/pkg/utils"
|
|
||||||
)
|
|
||||||
|
|
||||||
type View struct {
|
|
||||||
Width int `yaml:"-" json:"width"`
|
|
||||||
Height int `yaml:"-" json:"height"`
|
|
||||||
AspectRatio float64 `yaml:"aspect_ratio" json:"aspect_ratio"`
|
|
||||||
PortraitOnly bool `yaml:"portrait_only" json:"portrait_only"`
|
|
||||||
Color Color `yaml:"color" json:"color"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v View) Dimension() string {
|
|
||||||
return utils.IntToString(v.Width) + "x" + utils.IntToString(v.Height)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v View) Port() string {
|
|
||||||
return "width=" + utils.IntToString(v.Width) + ",height=" + utils.IntToString(v.Height)
|
|
||||||
}
|
|
Loading…
x
Reference in New Issue
Block a user