1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
package main
// Adding an EPUB to a calibre library, as its own command: it reads the
// EPUB epubify already wrote, so filing a book again never runs the
// pipeline. calibredb is told the metadata the EPUB carries, read back out
// of its package document, so that calibre's database and the file agree;
// and a book added again replaces its earlier version rather than adding a
// second copy, found by the identifier epubify writes (the PDF's hash).
import (
"archive/zip"
"bytes"
"context"
"database/sql"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// toCalibre adds each of args — a document in the database, whose last
// EPUB is taken, or an .epub file epubify wrote — to the library.
func toCalibre(ctx context.Context, st *store, lib string, args []string) error {
for _, a := range args {
var book []byte
var err error
what := a
if strings.HasSuffix(strings.ToLower(a), ".epub") {
book, err = os.ReadFile(a)
} else {
var doc, name string
if doc, name, err = st.findDoc(a); err == nil {
what = name
book, err = st.lastEPUB(doc)
}
}
if err != nil {
return err
}
m, err := readMeta(book)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
doc, ok := strings.CutPrefix(m.ID, "urn:sha256:")
if !ok {
return fmt.Errorf("%s: identifier %q is not epubify's", what, m.ID)
}
id, err := addToCalibre(ctx, lib, book, doc, m)
if err != nil {
return fmt.Errorf("%s: calibre: %w", what, err)
}
logf("calibre: %s is book %d in %s", m.Title, id, lib)
}
return nil
}
// lastEPUB is the EPUB of the document's most recent run that wrote one,
// flagged pages or not.
func (s *store) lastEPUB(doc string) ([]byte, error) {
var sum string
err := s.db.QueryRow(`SELECT epub FROM runs WHERE doc = ? AND epub IS NOT NULL ORDER BY id DESC LIMIT 1`, doc).Scan(&sum)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("no EPUB written for %s yet; run epubify convert first", doc[:12])
}
if err != nil {
return nil, err
}
return s.blob(sum)
}
// readMeta reads back what writeEPUB put into the package document: the
// fields calibre is told about.
func readMeta(book []byte) (bookMeta, error) {
z, err := zip.NewReader(bytes.NewReader(book), int64(len(book)))
if err != nil {
return bookMeta{}, fmt.Errorf("not an EPUB: %w", err)
}
var opf []byte
for _, f := range z.File {
if strings.HasSuffix(f.Name, ".opf") {
r, err := f.Open()
if err != nil {
return bookMeta{}, err
}
opf, err = io.ReadAll(r)
r.Close()
if err != nil {
return bookMeta{}, err
}
break
}
}
if opf == nil {
return bookMeta{}, fmt.Errorf("no package document")
}
var pkg struct {
Metadata struct {
Identifier string `xml:"identifier"`
Title string `xml:"title"`
Creator string `xml:"creator"`
Language string `xml:"language"`
Source string `xml:"source"`
Publisher string `xml:"publisher"`
Subjects []string `xml:"subject"`
Description string `xml:"description"`
Meta []struct {
Name string `xml:"name,attr"`
Content string `xml:"content,attr"`
} `xml:"meta"`
} `xml:"metadata"`
}
if err := xml.Unmarshal(opf, &pkg); err != nil {
return bookMeta{}, fmt.Errorf("package document: %w", err)
}
md := pkg.Metadata
m := bookMeta{ID: md.Identifier, Title: md.Title, Authors: md.Creator, Lang: md.Language,
Source: md.Source, Tags: md.Subjects, Description: md.Description}
m.Biblio.Publisher = md.Publisher
for _, x := range md.Meta {
switch x.Name {
case "calibre:series":
m.Series = x.Content
case "calibre:series_index":
m.SeriesIndex, _ = strconv.ParseFloat(x.Content, 64)
}
}
return m, nil
}
func calibredb(ctx context.Context, lib string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, "calibredb", append([]string{"--library-path", lib}, args...)...)
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("calibredb %s: %w: %s", args[0], err, strings.TrimSpace(string(out)))
}
return string(out), nil
}
var addedIDs = regexp.MustCompile(`Added book ids: ([\d, ]+)`)
// addToCalibre adds the EPUB, or replaces the format of the book that
// already has it (identifier epubify:<pdf sha256>), and sets calibre's
// metadata to what the EPUB carries, so that a book sent from calibre to a
// reader has the same tags and series as the file epubify wrote. What was
// edited in calibre by hand is overwritten: the command line is where it
// is set.
func addToCalibre(ctx context.Context, lib string, book []byte, doc string, m bookMeta) (int, error) {
// calibredb wants a file, and names the format by its extension.
dir, err := os.MkdirTemp("", "epubify-calibre-")
if err != nil {
return 0, err
}
defer os.RemoveAll(dir)
epub := filepath.Join(dir, doc[:12]+".epub")
if err := os.WriteFile(epub, book, 0o600); err != nil {
return 0, err
}
out, err := calibredb(ctx, lib, "search", "identifiers:epubify:"+doc)
id := 0
if err == nil {
first, _, _ := strings.Cut(strings.TrimSpace(out), ",")
id, _ = strconv.Atoi(first)
}
if id == 0 {
out, err := calibredb(ctx, lib, "add", "--duplicates", epub)
if err != nil {
return 0, err
}
m := addedIDs.FindStringSubmatch(out)
if m == nil {
return 0, fmt.Errorf("calibredb add: no book id in %q", strings.TrimSpace(out))
}
id, _ = strconv.Atoi(strings.TrimSpace(strings.Split(m[1], ",")[0]))
} else if _, err := calibredb(ctx, lib, "add_format", strconv.Itoa(id), epub); err != nil {
return id, err
}
// --field splits lists at commas, and a tag or series may contain one;
// calibre has no escape for that, so a comma in a tag becomes a
// semicolon here.
nocomma := func(s string) string { return strings.ReplaceAll(s, ",", ";") }
var tags []string
for _, t := range m.Tags {
tags = append(tags, nocomma(t))
}
fields := []string{
"title:" + m.Title,
"authors:" + strings.ReplaceAll(m.Authors, ",", " &"),
"tags:" + strings.Join(tags, ","),
"series:" + m.Series,
"series_index:" + strconv.FormatFloat(m.SeriesIndex, 'f', -1, 64),
"comments:" + m.Description,
"languages:" + m.Lang,
"identifiers:epubify:" + doc,
}
if m.Biblio.Publisher != "" {
fields = append(fields, "publisher:"+m.Biblio.Publisher)
}
args := []string{"set_metadata"}
for _, f := range fields {
args = append(args, "--field", f)
}
args = append(args, strconv.Itoa(id))
if _, err := calibredb(ctx, lib, args...); err != nil {
return id, err
}
return id, nil
}
|