2025-10-15 00:54:19 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
|
|
import (
|
2025-10-15 14:36:43 +02:00
|
|
|
"fmt"
|
2025-10-16 12:24:47 +02:00
|
|
|
"log"
|
2025-10-15 21:42:07 +02:00
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2025-10-15 00:54:19 +02:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/tlinden/epuppy/pkg/epub"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func View(conf *Config) (int, error) {
|
2025-10-15 21:42:07 +02:00
|
|
|
switch filepath.Ext(conf.Document) {
|
|
|
|
|
case ".epub":
|
|
|
|
|
return ViewEpub(conf)
|
|
|
|
|
default:
|
|
|
|
|
return ViewText(conf)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ViewText(conf *Config) (int, error) {
|
|
|
|
|
data, err := os.ReadFile(conf.Document)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-16 12:24:47 +02:00
|
|
|
if conf.Dump {
|
|
|
|
|
return fmt.Println(string(data))
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-15 21:42:07 +02:00
|
|
|
return Pager(conf, conf.Document, string(data))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ViewEpub(conf *Config) (int, error) {
|
2025-10-15 00:54:19 +02:00
|
|
|
book, err := epub.Open(conf.Document)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return 0, err
|
|
|
|
|
}
|
2025-10-16 12:24:47 +02:00
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
|
if err := book.Close(); err != nil {
|
|
|
|
|
log.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
}()
|
2025-10-15 00:54:19 +02:00
|
|
|
|
|
|
|
|
buf := strings.Builder{}
|
|
|
|
|
head := strings.Builder{}
|
|
|
|
|
|
|
|
|
|
for _, creator := range book.Opf.Metadata.Creator {
|
|
|
|
|
head.WriteString(creator.Data)
|
|
|
|
|
head.WriteString(" ")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
head.WriteString("- ")
|
|
|
|
|
|
|
|
|
|
for _, title := range book.Opf.Metadata.Title {
|
|
|
|
|
head.WriteString(title)
|
|
|
|
|
head.WriteString(" ")
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-15 14:36:43 +02:00
|
|
|
// FIXME: since the switch to book.Files() in epub.Open() this
|
|
|
|
|
// returns invalid chapter numbering
|
|
|
|
|
chapter := 1
|
|
|
|
|
|
|
|
|
|
for _, content := range book.Content {
|
|
|
|
|
if len(content.Body) > 0 {
|
2025-10-15 21:42:07 +02:00
|
|
|
if content.Title != "" {
|
|
|
|
|
buf.WriteString(conf.Colors.Chapter.
|
|
|
|
|
Render(fmt.Sprintf("──────┤ %s ├──────", content.Title)))
|
|
|
|
|
|
|
|
|
|
}
|
2025-10-15 00:54:19 +02:00
|
|
|
buf.WriteString("\r\n\r\n")
|
2025-10-16 12:24:47 +02:00
|
|
|
|
|
|
|
|
if conf.Dump {
|
|
|
|
|
// avoid excess whitespaces when printing to stdout
|
|
|
|
|
buf.WriteString(content.Body)
|
|
|
|
|
} else {
|
|
|
|
|
buf.WriteString(conf.Colors.Body.Render(content.Body))
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-15 00:54:19 +02:00
|
|
|
buf.WriteString("\r\n\r\n\r\n\r\n")
|
2025-10-15 14:36:43 +02:00
|
|
|
chapter++
|
2025-10-15 00:54:19 +02:00
|
|
|
}
|
2025-10-16 12:24:47 +02:00
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if conf.Dump {
|
|
|
|
|
return fmt.Println(buf.String())
|
2025-10-15 00:54:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Pager(conf, head.String(), buf.String())
|
|
|
|
|
}
|