summaryrefslogtreecommitdiff
path: root/pngmeta/metareader.go
blob: ea726c9e6fedf4224040a5c356db9483ee8d2dfd (plain)
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
package pngmeta

import (
	"bytes"
	"elefant/models"
	"encoding/base64"
	"encoding/json"
	"errors"
	"io"
	"os"
	"path"
	"strings"
)

const (
	embType = "tEXt"
)

type PngEmbed struct {
	Key   string
	Value string
}

func (c PngEmbed) GetDecodedValue() (*models.CharCardSpec, error) {
	data, err := base64.StdEncoding.DecodeString(c.Value)
	if err != nil {
		return nil, err
	}
	card := &models.CharCardSpec{}
	if err := json.Unmarshal(data, &card); err != nil {
		return nil, err
	}
	return card, nil
}

func extractChar(fname string) (*PngEmbed, error) {
	data, err := os.ReadFile(fname)
	if err != nil {
		return nil, err
	}
	reader := bytes.NewReader(data)
	pr, err := NewPNGStepReader(reader)
	if err != nil {
		return nil, err
	}
	for {
		step, err := pr.Next()
		if err != nil {
			if errors.Is(err, io.EOF) {
				break
			}
		}
		if step.Type() != embType {
			if _, err := io.Copy(io.Discard, step); err != nil {
				return nil, err
			}
		} else {
			buf, err := io.ReadAll(step)
			if err != nil {
				return nil, err
			}
			dataInstep := string(buf)
			values := strings.Split(dataInstep, "\x00")
			if len(values) == 2 {
				return &PngEmbed{Key: values[0], Value: values[1]}, nil
			}
		}
		if err := step.Close(); err != nil {
			return nil, err
		}
	}
	return nil, errors.New("failed to find embedded char in png: " + fname)
}

func ReadCard(fname, uname string) (*models.CharCard, error) {
	pe, err := extractChar(fname)
	if err != nil {
		return nil, err
	}
	charSpec, err := pe.GetDecodedValue()
	if err != nil {
		return nil, err
	}
	return charSpec.Simplify(uname, fname), nil
}

func ReadDirCards(dirname, uname string) ([]*models.CharCard, error) {
	files, err := os.ReadDir(dirname)
	if err != nil {
		return nil, err
	}
	resp := []*models.CharCard{}
	for _, f := range files {
		if !strings.HasSuffix(f.Name(), ".png") {
			continue
		}
		fpath := path.Join(dirname, f.Name())
		cc, err := ReadCard(fpath, uname)
		if err != nil {
			// log err
			return nil, err
			// continue
		}
		resp = append(resp, cc)
	}
	return resp, nil
}