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
|
package storage
import (
"context"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/Backblaze/blazer/b2"
"github.com/SayaAndy/saya-today-article-metadata-add/config"
"github.com/SayaAndy/saya-today-article-metadata-add/internal/frontmatter"
)
var _ StorageClient = &B2StorageClient{}
type B2StorageClient struct {
prefix string
bucket *b2.Bucket
b2cl *b2.Client
draftModeCfg *config.DraftModeConfig
}
func NewB2StorageClient(cfg *config.StorageConfig, draftModeCfg *config.DraftModeConfig) (StorageClient, error) {
if cfg.Type != "b2" {
return nil, fmt.Errorf("invalid storage type for B2InputClient")
}
b2cfg := cfg.Config.(*config.B2Config)
b2cl, err := b2.NewClient(context.Background(), b2cfg.KeyID, b2cfg.ApplicationKey)
if err != nil {
return nil, err
}
bucket, err := b2cl.Bucket(context.Background(), b2cfg.BucketName)
if err != nil {
return nil, err
}
draftModeCfgCopy := *draftModeCfg
return &B2StorageClient{b2cl: b2cl, bucket: bucket, prefix: b2cfg.Prefix, draftModeCfg: &draftModeCfgCopy}, nil
}
func (sc *B2StorageClient) Scan() ([]string, error) {
filePaths := []string{}
iter := sc.bucket.List(context.Background(), b2.ListPrefix(sc.prefix))
for iter.Next() {
obj := iter.Object()
if obj == nil {
return nil, fmt.Errorf("failed to reference object in B2 bucket")
}
attrs, err := obj.Attrs(context.Background())
if err != nil {
return nil, fmt.Errorf("get attributes for object: %w", err)
}
if attrs.Status != b2.Uploaded {
continue
}
name := obj.Name()
if !strings.HasSuffix(name, ".md") {
continue
}
if sc.draftModeCfg.Enabled && !strings.HasSuffix(name, sc.draftModeCfg.DraftSuffix) {
continue
}
filePaths = append(filePaths, strings.TrimPrefix(name, sc.prefix))
}
if err := iter.Err(); err != nil {
return nil, fmt.Errorf("iterate over B2 objects: %w", err)
}
return filePaths, nil
}
func (sc *B2StorageClient) GetReader(path string) (io.ReadCloser, int64, error) {
obj := sc.bucket.Object(sc.prefix + path)
if obj == nil {
return nil, 0, fmt.Errorf("failed to reference object in B2 bucket")
}
attrs, err := obj.Attrs(context.Background())
if err != nil {
return nil, 0, fmt.Errorf("error getting attributes of an object: %w", err)
}
return obj.NewReader(context.Background()), attrs.Size, nil
}
func (sc *B2StorageClient) WriteMetadata(path string, metadata *frontmatter.Metadata) error {
draft := sc.bucket.Object(sc.prefix + path)
if draft == nil {
return fmt.Errorf("failed to reference draft object in B2 bucket")
}
draftAttrs, err := draft.Attrs(context.Background())
if err != nil {
return fmt.Errorf("error getting attributes of a draft object: %w", err)
}
geolocationParts := strings.Split(metadata.Geolocation, " ")
if (len(geolocationParts) == 1 && geolocationParts[0] != "") || len(geolocationParts) >= 4 {
return fmt.Errorf("invalid geolocation format, expecting '{x} {y} [areaError]' or an empty string")
}
if len(geolocationParts) >= 2 {
if _, err := strconv.ParseFloat(geolocationParts[0], 64); err != nil {
return fmt.Errorf("invalid geolocation parameter, expected float for X: %w", err)
}
if _, err := strconv.ParseFloat(geolocationParts[1], 64); err != nil {
return fmt.Errorf("invalid geolocation parameter, expected float for Y: %w", err)
}
}
if len(geolocationParts) == 3 {
if _, err := strconv.ParseFloat(geolocationParts[2], 64); err != nil {
return fmt.Errorf("invalid geolocation parameter, expected float for area error: %w", err)
}
}
medley := ""
if metadata.Medley != "" {
medley = fmt.Sprintf("%s %d", metadata.Medley, metadata.MedleyPart)
}
attrs := &b2.Attrs{
ContentType: "text/markdown; charset=utf-8",
Info: map[string]string{
"title": metadata.Title,
"short-description": metadata.ShortDescription,
"action-date": metadata.ActionDate,
"published-time": metadata.PublishedTime.Format(time.RFC3339),
"thumbnail": metadata.Thumbnail,
"tags": strings.Join(metadata.Tags, ","),
"geolocation": metadata.Geolocation,
"medley": medley,
"metadata-last-update-sha1": draftAttrs.SHA1,
}}
reader := draft.NewReader(context.Background())
content := make([]byte, draftAttrs.Size)
if _, err = reader.Read(content); err != nil {
return fmt.Errorf("failed to read a draft object back for writing (required for attribute setting): %w", err)
}
var prod *b2.Object
if sc.draftModeCfg.Enabled {
prodPath := strings.TrimSuffix(path, sc.draftModeCfg.DraftSuffix) + sc.draftModeCfg.ProdSuffix
prod = sc.bucket.Object(sc.prefix + prodPath)
if prod == nil {
return fmt.Errorf("failed to reference prod object in B2 bucket")
}
} else {
prod = draft
}
writer := prod.NewWriter(context.Background(), b2.WithAttrsOption(attrs))
defer writer.Close()
if _, err := writer.Write(content); err != nil {
return fmt.Errorf("failed to write an object back after attribute settings: %w", err)
}
return nil
}
func (sc *B2StorageClient) CompareDraftAndProd(path string) (changed bool) {
draft := sc.bucket.Object(sc.prefix + path)
if draft == nil {
return false
}
prodPath := strings.TrimSuffix(path, sc.draftModeCfg.DraftSuffix) + sc.draftModeCfg.ProdSuffix
prod := sc.bucket.Object(sc.prefix + prodPath)
if prod == nil {
return true
}
draftAttrs, err := draft.Attrs(context.Background())
if err != nil {
return false
}
prodAttrs, err := prod.Attrs(context.Background())
if err != nil {
return true
}
lastUpdateSha1, ok := prodAttrs.Info["metadata-last-update-sha1"]
if !ok {
return true
}
return draftAttrs.SHA1 != lastUpdateSha1
}
|