-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
410 lines (348 loc) · 8.85 KB
/
main.go
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright 2019 by David A. Golden. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package main
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/jung-kurt/gofpdf"
"github.com/shibukawa/configdir"
)
const vendorName = "xdg.me"
const appConfigName = "cardproxypdf"
const cacheDBName = "carddb.json"
const cacheImageFolder = "images"
const ringsURLGetAll = "http://ringsdb.com/api/public/cards/"
const ringsURL = "http://ringsdb.com"
const ringsImagePrefix = "/bundles/cards/"
var errIgnoreCache = errors.New("cache missing or out of date")
type App struct {
// command line
inputFile string
outputFile string
// app-wide data
cache *configdir.Config
err error
// pipeline stage outputs
deck []XMLCard
octgnToImgName map[string]string
}
type XMLCard struct {
Card string `xml:",chardata"`
Quantity int `xml:"qty,attr"`
OctgnID string `xml:"id,attr"`
ImagePath string // filled in later from metadata
}
type XMLSection struct {
Cards []XMLCard `xml:"card"`
}
type XMLDeck struct {
Sections []XMLSection `xml:"section"`
}
type RingsCard struct {
ID string `json:"octgnid"`
ImageSrc string `json:"imagesrc"`
}
func main() {
// Check for correct usage
if len(os.Args) != 3 {
log.Fatalf("usage: %s <input.o8d> <output.pdf>", os.Args[0])
}
app := &App{
cache: configdir.New(vendorName, appConfigName).QueryCacheFolder(),
inputFile: os.Args[1],
outputFile: os.Args[2],
}
// App uses the error monad pattern; any error will shortcut later steps.
app.LoadMetadata()
app.ParseInputFile()
app.PreloadImages()
app.CreatePDF()
if app.err != nil {
log.Fatalf("error: %v", app.err)
}
}
func (app *App) LoadMetadata() {
if app.err != nil {
return
}
// Try loading from cache
var err error
app.octgnToImgName, err = loadFromCache(app.cache)
// Return if it worked or fall through to refetching from the API
if err == nil {
return
}
if err != errIgnoreCache {
log.Printf("warning: failed loading metadata from cache: %v", err)
}
// Fetch from the API and cache the result
log.Print("fetching metadata from ringsdb.com")
var data []byte
data, app.err = httpGetBytes(ringsURLGetAll)
if app.err != nil {
return
}
app.octgnToImgName, app.err = convertRingsDataToMap(data)
if app.err != nil {
return
}
err = saveToCache(app.cache, app.octgnToImgName)
if err != nil {
log.Printf("warning: failed saving metadata to cache: %v", err)
}
}
func httpGetBytes(url string) ([]byte, error) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
// store URLs as just final filename so it's easier to combine
// into full URL or cache file path
func convertRingsDataToMap(body []byte) (map[string]string, error) {
var cardList []RingsCard
err := json.Unmarshal(body, &cardList)
if err != nil {
return nil, err
}
images := make(map[string]string)
for _, v := range cardList {
if v.ImageSrc == "" {
continue
}
images[v.ID] = strings.TrimPrefix(v.ImageSrc, ringsImagePrefix)
}
return images, nil
}
func loadFromCache(cache *configdir.Config) (map[string]string, error) {
if !cache.Exists(cacheDBName) {
return nil, errIgnoreCache
}
// Ignore cached file if more than 24 hours old.
stat, err := os.Stat(filepath.Join(cache.Path, cacheDBName))
if err != nil {
return nil, err
}
if time.Since(stat.ModTime()) > 24*time.Hour {
return nil, errIgnoreCache
}
// Read and unmarshal cached file
bytes, err := cache.ReadFile(cacheDBName)
if err != nil {
return nil, err
}
var images map[string]string
err = json.Unmarshal(bytes, &images)
if err != nil {
return nil, err
}
log.Print("loaded card metadata from cache")
return images, nil
}
func saveToCache(cache *configdir.Config, images map[string]string) error {
bytes, err := json.Marshal(images)
if err != nil {
return err
}
err = cache.WriteFile(cacheDBName, bytes)
if err != nil {
return err
}
log.Print("saved card metadata to cache")
return nil
}
func (app *App) ParseInputFile() {
if app.err != nil {
return
}
var data []byte
data, app.err = ioutil.ReadFile(app.inputFile)
if app.err != nil {
return
}
var deck XMLDeck
app.err = xml.Unmarshal(data, &deck)
if app.err != nil {
return
}
flat := make([]XMLCard, 0)
for _, section := range deck.Sections {
for _, card := range section.Cards {
card.ImagePath = app.octgnToImgName[card.OctgnID]
if card.ImagePath == "" {
log.Println("no image available for", card.Card, "(skipping it)")
continue
}
flat = append(flat, card)
}
}
app.deck = flat
}
func (app *App) PreloadImages() {
if app.err != nil {
return
}
wg := sync.WaitGroup{}
var errMap sync.Map
for _, card := range app.deck {
if !app.cache.Exists(filepath.Join(cacheImageFolder, card.ImagePath)) {
wg.Add(1)
go func(card XMLCard) {
defer wg.Done()
err := loadImageToCache(app.cache, card.ImagePath)
if err != nil {
errMap.Store(card.ImagePath, err)
return
}
log.Printf("Fetched %s to cache", card.ImagePath)
}(card)
}
}
wg.Wait()
var errs []string
errMap.Range(func(k, v interface{}) bool {
errs = append(errs, fmt.Sprintf("%s (%s)", k.(string), v.(error).Error()))
return true
})
if len(errs) > 0 {
app.err = fmt.Errorf("error(s) fetching images: %s", strings.Join(errs, "; "))
}
}
func loadImageToCache(cache *configdir.Config, imageName string) error {
cachePath := filepath.Join(cacheImageFolder, imageName)
urlPath := ringsURL + path.Join(ringsImagePrefix, imageName)
imageBytes, err := httpGetBytes(urlPath)
if err != nil {
return err
}
err = cache.WriteFile(cachePath, imageBytes)
if err != nil {
return err
}
return nil
}
func (app *App) CreatePDF() {
if app.err != nil {
return
}
if len(app.deck) == 0 {
log.Println("no cards in the deck; will not create PDF")
return
}
pdf := gofpdf.New("P", "mm", "Letter", "")
var deck []XMLCard
deck, app.err = addImagesToPdf(pdf, app.cache, app.deck)
if app.err != nil {
return
}
app.err = renderPDF(pdf, deck, app.outputFile)
}
func addImagesToPdf(pdf *gofpdf.Fpdf, cache *configdir.Config, deck []XMLCard) ([]XMLCard, error) {
deckWithValidImages := make([]XMLCard, 0)
for _, card := range deck {
imageBytes, err := cache.ReadFile(filepath.Join(cacheImageFolder, card.ImagePath))
if err != nil {
if os.IsNotExist(err) {
log.Println("no cached image for", card.Card, "(skipping it)")
continue
} else {
return nil, err
}
}
imageOpts := getImageOptions(imageBytes, card)
if (imageOpts == gofpdf.ImageOptions{}) {
_ = os.Remove(filepath.Join(cache.Path, cacheImageFolder, card.ImagePath))
continue
}
pdf.RegisterImageOptionsReader(card.ImagePath, imageOpts, bytes.NewReader(imageBytes))
deckWithValidImages = append(deckWithValidImages, card)
}
return deckWithValidImages, nil
}
func getImageOptions(bytes []byte, c XMLCard) gofpdf.ImageOptions {
mimeType := http.DetectContentType(bytes)
switch mimeType {
case "image/jpeg":
return gofpdf.ImageOptions{ImageType: "JPEG"}
case "image/png":
return gofpdf.ImageOptions{ImageType: "PNG"}
default:
log.Printf("unsupported image type for %s (%s): %s (skipping it)", c.ImagePath, c.Card, mimeType)
return gofpdf.ImageOptions{}
}
}
func renderPDF(pdf *gofpdf.Fpdf, deck []XMLCard, outputPath string) error {
images := make([]string, 0)
for _, card := range deck {
for i := 0; i < card.Quantity; i++ {
images = append(images, card.ImagePath)
}
}
var batch []string
for len(images) > 0 {
batch, images = splitAt(9, images)
err := renderSinglePage(pdf, batch)
if err != nil {
return fmt.Errorf("could not assemble PDF: %v", err)
}
}
err := pdf.OutputFileAndClose(outputPath)
if err != nil {
return fmt.Errorf("could not render PDF: %v", err)
}
return nil
}
func splitAt(n int, xs []string) ([]string, []string) {
if len(xs) < n {
n = len(xs)
}
return xs[0:n], xs[n:]
}
func renderSinglePage(pdf gofpdf.Pdf, images []string) error {
if len(images) > 9 {
return fmt.Errorf("too many images to render (%d > 9)", len(images))
}
pdf.AddPage()
var cardWidth = 63.5
var cardHeight = 88.0
var leftPadding = 4.0
var spacer = 4.0
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if len(images) == 0 {
return nil
}
fi, fj := float64(i), float64(j)
pdf.ImageOptions(
images[0],
leftPadding+spacer*(fj+1)+cardWidth*fj,
spacer*(fi+1)+cardHeight*fi,
cardWidth, cardHeight, false, gofpdf.ImageOptions{}, 0, "",
)
images = images[1:]
}
}
return nil
}