2025-10-15 14:36:43 +02:00
|
|
|
|
package epub
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2025-10-15 21:42:07 +02:00
|
|
|
|
"regexp"
|
2025-10-15 14:36:43 +02:00
|
|
|
|
"strings"
|
2025-10-16 18:57:05 +02:00
|
|
|
|
|
|
|
|
|
|
"github.com/antchfx/xmlquery"
|
2025-10-15 14:36:43 +02:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-10-15 21:42:07 +02:00
|
|
|
|
var (
|
2025-10-16 18:57:05 +02:00
|
|
|
|
cleanentitles = regexp.MustCompile(`&.+;`)
|
|
|
|
|
|
empty = regexp.MustCompile(`(?s)^[\s ]*$`)
|
|
|
|
|
|
newlines = regexp.MustCompile(`[\r\n]+`)
|
2025-10-15 21:42:07 +02:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-10-15 14:36:43 +02:00
|
|
|
|
// Content nav-point content
|
|
|
|
|
|
type Content struct {
|
|
|
|
|
|
Src string `xml:"src,attr" json:"src"`
|
|
|
|
|
|
Empty bool
|
|
|
|
|
|
Body string
|
|
|
|
|
|
Title string
|
|
|
|
|
|
XML []byte
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (c *Content) String(content []byte) error {
|
2025-10-16 18:57:05 +02:00
|
|
|
|
// parse XML, look for title and <p>.*</p> stuff
|
|
|
|
|
|
doc, err := xmlquery.Parse(
|
|
|
|
|
|
strings.NewReader(
|
|
|
|
|
|
cleanentitles.ReplaceAllString(string(content), " ")))
|
2025-10-15 14:36:43 +02:00
|
|
|
|
if err != nil {
|
2025-10-16 18:57:05 +02:00
|
|
|
|
panic(err)
|
2025-10-15 14:36:43 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-10-16 18:57:05 +02:00
|
|
|
|
// extract the title
|
|
|
|
|
|
for _, item := range xmlquery.Find(doc, "//title") {
|
|
|
|
|
|
c.Title = strings.TrimSpace(item.InnerText())
|
|
|
|
|
|
}
|
2025-10-15 14:36:43 +02:00
|
|
|
|
|
2025-10-16 18:57:05 +02:00
|
|
|
|
// extract all paragraphs, ignore any formatting and re-fill the
|
|
|
|
|
|
// paragraph, that is, we replaces all newlines inside with one
|
|
|
|
|
|
// space.
|
|
|
|
|
|
txt := strings.Builder{}
|
|
|
|
|
|
for _, item := range xmlquery.Find(doc, "//p") {
|
|
|
|
|
|
if !empty.MatchString(item.InnerText()) {
|
|
|
|
|
|
txt.WriteString(newlines.ReplaceAllString(item.InnerText(), " ") + "\n\n")
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-10-15 14:36:43 +02:00
|
|
|
|
|
2025-10-16 18:57:05 +02:00
|
|
|
|
c.Body = strings.TrimSpace(txt.String())
|
2025-10-15 14:36:43 +02:00
|
|
|
|
c.XML = content
|
|
|
|
|
|
|
|
|
|
|
|
if len(c.Body) == 0 {
|
|
|
|
|
|
c.Empty = true
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|