-
Notifications
You must be signed in to change notification settings - Fork 245
/
qrops.go
306 lines (240 loc) · 7.31 KB
/
qrops.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
package server
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"image"
"net/url"
"strconv"
"github.com/yeqown/go-qrcode/v2"
"github.com/yeqown/go-qrcode/writer/standard"
"go.uber.org/zap"
"github.com/status-im/status-go/images"
"github.com/status-im/status-go/multiaccounts"
)
type WriterCloserByteBuffer struct {
*bytes.Buffer
}
func (wc WriterCloserByteBuffer) Close() error {
return nil
}
func NewWriterCloserByteBuffer() *WriterCloserByteBuffer {
return &WriterCloserByteBuffer{bytes.NewBuffer([]byte{})}
}
type QRConfig struct {
DecodedQRURL string
WithLogo bool
CorrectionLevel qrcode.EncodeOption
KeyUID string
ImageName string
Size int
Params url.Values
}
func NewQRConfig(params url.Values, logger *zap.Logger) (*QRConfig, error) {
config := &QRConfig{}
config.Params = params
err := config.setQrURL()
if err != nil {
logger.Error("[qrops-error] error in setting QRURL", zap.Error(err))
return nil, err
}
config.setAllowProfileImage()
config.setErrorCorrectionLevel()
err = config.setSize()
if err != nil {
logger.Error("[qrops-error] could not convert string to int for size param ", zap.Error(err))
return nil, err
}
if config.WithLogo {
err = config.setKeyUID()
if err != nil {
logger.Error(err.Error())
return nil, err
}
config.setImageName()
}
return config, nil
}
func (q *QRConfig) setQrURL() error {
qrURL, ok := q.Params["url"]
if !ok || len(qrURL) == 0 {
return errors.New("[qrops-error] no qr url provided")
}
decodedURL, err := base64.StdEncoding.DecodeString(qrURL[0])
if err != nil {
return err
}
q.DecodedQRURL = string(decodedURL)
return nil
}
func (q *QRConfig) setAllowProfileImage() {
allowProfileImage, ok := q.Params["allowProfileImage"]
if !ok || len(allowProfileImage) == 0 {
// we default to false when this flag was not provided
// so someone does not want to allowProfileImage on their QR Image
// fine then :)
q.WithLogo = false
}
LogoOnImage, err := strconv.ParseBool(allowProfileImage[0])
if err != nil {
// maybe for fun someone tries to send non-boolean values to this flag
// we also default to false in that case
q.WithLogo = false
}
// if we reach here its most probably true
q.WithLogo = LogoOnImage
}
func (q *QRConfig) setErrorCorrectionLevel() {
level, ok := q.Params["level"]
if !ok || len(level) == 0 {
// we default to MediumLevel of error correction when the level flag
// is not passed.
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionMedium)
}
levelInt, err := strconv.Atoi(level[0])
if err != nil || levelInt < 0 {
// if there is any issue with string to int conversion
// we still default to MediumLevel of error correction
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionMedium)
}
switch levelInt {
case 1:
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionLow)
case 2:
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionMedium)
case 3:
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionQuart)
case 4:
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionHighest)
default:
q.CorrectionLevel = qrcode.WithErrorCorrectionLevel(qrcode.ErrorCorrectionMedium)
}
}
func (q *QRConfig) setSize() error {
size, ok := q.Params["size"]
if ok {
imageToBeResized, err := strconv.Atoi(size[0])
if err != nil {
return err
}
if imageToBeResized <= 0 {
return errors.New("[qrops-error] Got an invalid size parameter, it should be greater than zero")
}
q.Size = imageToBeResized
}
return nil
}
func (q *QRConfig) setKeyUID() error {
keyUID, ok := q.Params["keyUid"]
// the keyUID was not passed, which is a requirement to get the multiaccount image,
// so we log this error
if !ok || len(keyUID) == 0 {
return errors.New("[qrops-error] A keyUID is required to put logo on image and it was not passed in the parameters")
}
q.KeyUID = keyUID[0]
return nil
}
func (q *QRConfig) setImageName() {
imageName, ok := q.Params["imageName"]
//if the imageName was not passed, we default to const images.LargeDimName
if !ok || len(imageName) == 0 {
q.ImageName = images.LargeDimName
}
q.ImageName = imageName[0]
}
func ToLogoImageFromBytes(imageBytes []byte, padding int) ([]byte, error) {
img, _, err := image.Decode(bytes.NewReader(imageBytes))
if err != nil {
return nil, fmt.Errorf("decoding image failed: %v", err)
}
paddedImg := images.AddPadding(img, padding)
circle := images.CreateCircle(img)
centeredImg := images.PlaceCircleInCenter(paddedImg, circle)
resultBytes, err := images.EncodePNG(centeredImg)
if err != nil {
return nil, fmt.Errorf("encoding PNG failed: %v", err)
}
return resultBytes, nil
}
func GetLogoImage(multiaccountsDB *multiaccounts.Database, keyUID string, imageName string) ([]byte, error) {
var (
padding int
LogoBytes []byte
)
staticImageData, err := images.Asset("_assets/tests/qr/status.png")
if err != nil { // Asset was not found.
return nil, err
}
identityImageObjectFromDB, err := multiaccountsDB.GetIdentityImage(keyUID, imageName)
if err != nil {
return nil, err
}
if identityImageObjectFromDB == nil {
padding = GetPadding(staticImageData)
LogoBytes, err = ToLogoImageFromBytes(staticImageData, padding)
} else {
padding = GetPadding(identityImageObjectFromDB.Payload)
LogoBytes, err = ToLogoImageFromBytes(identityImageObjectFromDB.Payload, padding)
}
return LogoBytes, err
}
func GetPadding(imgBytes []byte) int {
const (
defaultPadding = 20
)
size, _, err := images.GetImageDimensions(imgBytes)
if err != nil {
return defaultPadding
}
return size / 5
}
func generateQRBytes(params url.Values, logger *zap.Logger, multiaccountsDB *multiaccounts.Database) []byte {
qrGenerationConfig, err := NewQRConfig(params, logger)
if err != nil {
logger.Error("could not generate QRConfig please rectify the errors with input parameters", zap.Error(err))
return nil
}
qrc, err := qrcode.NewWith(qrGenerationConfig.DecodedQRURL,
qrcode.WithEncodingMode(qrcode.EncModeAuto),
qrGenerationConfig.CorrectionLevel,
)
if err != nil {
logger.Error("could not generate QRCode with provided options", zap.Error(err))
return nil
}
buf := NewWriterCloserByteBuffer()
nw := standard.NewWithWriter(buf)
err = qrc.Save(nw)
if err != nil {
logger.Error("could not save image", zap.Error(err))
return nil
}
payload := buf.Bytes()
if qrGenerationConfig.WithLogo {
logo, err := GetLogoImage(multiaccountsDB, qrGenerationConfig.KeyUID, qrGenerationConfig.ImageName)
if err != nil {
logger.Error("could not get logo image from multiaccountsDB", zap.Error(err))
return nil
}
qrWidth, qrHeight, err := images.GetImageDimensions(payload)
if err != nil {
logger.Error("could not get image dimensions from payload", zap.Error(err))
return nil
}
logo, err = images.ResizeImage(logo, qrWidth/5, qrHeight/5)
if err != nil {
logger.Error("could not resize logo image ", zap.Error(err))
return nil
}
payload = images.SuperimposeLogoOnQRImage(payload, logo)
}
if qrGenerationConfig.Size > 0 {
payload, err = images.ResizeImage(payload, qrGenerationConfig.Size, qrGenerationConfig.Size)
if err != nil {
logger.Error("could not resize final logo image ", zap.Error(err))
return nil
}
}
return payload
}