forked from alvinbaena/passkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pass.go
513 lines (414 loc) · 17.8 KB
/
pass.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package passkit
import (
"encoding/json"
"fmt"
"gopkg.in/go-playground/colors.v1"
"strconv"
"strings"
"time"
)
type BarcodeFormat string
type TextAlignment string
type DataDetectorType string
type DateStyle string
type NumberStyle string
type PassPersonalizationField string
type TransitType string
const (
expectedAuthTokenLen = 16
//PKTextAlignment
TextAlignmentLeft TextAlignment = "PKTextAlignmentLeft"
TextAlignmentCenter TextAlignment = "PKTextAlignmentCenter"
TextAlignmentRight TextAlignment = "PKTextAlignmentRight"
TextAlignmentNatural TextAlignment = "PKTextAlignmentNatural"
//PKBarcodeFormat
BarcodeFormatQR BarcodeFormat = "PKBarcodeFormatQR"
BarcodeFormatPDF417 BarcodeFormat = "PKBarcodeFormatPDF417"
BarcodeFormatAztec BarcodeFormat = "PKBarcodeFormatAztec"
BarcodeFormatCode128 BarcodeFormat = "PKBarcodeFormatCode128"
//PKDataDetectorType
DataDetectorTypePhoneNumber DataDetectorType = "PKDataDetectorTypePhoneNumber"
DataDetectorTypeLink DataDetectorType = "PKDataDetectorTypeLink"
DataDetectorTypeAddress DataDetectorType = "PKDataDetectorTypeAddress"
DataDetectorTypeCalendarEvent DataDetectorType = "PKDataDetectorTypeCalendarEvent"
//PKDateStyle
DateStyleNone DateStyle = "PKDateStyleNone"
DateStyleShort DateStyle = "PKDateStyleShort"
DateStyleMedium DateStyle = "PKDateStyleMedium"
DateStyleLong DateStyle = "PKDateStyleLong"
DateStyleFull DateStyle = "PKDateStyleFull"
//PKNumberStyle
NumberStyleDecimal NumberStyle = "PKNumberStyleDecimal"
NumberStylePercent NumberStyle = "PKNumberStylePercent"
NumberStyleScientific NumberStyle = "PKNumberStyleScientific"
NumberStyleSpellOut NumberStyle = "PKNumberStyleSpellOut"
//PKPassPersonalizationField
PassPersonalizationFieldName PassPersonalizationField = "PKPassPersonalizationFieldName"
PassPersonalizationFieldPostalCode PassPersonalizationField = "PKPassPersonalizationFieldPostalCode"
PassPersonalizationFieldEmailAddress PassPersonalizationField = "PKPassPersonalizationFieldEmailAddress"
PassPersonalizationFieldPhoneNumber PassPersonalizationField = "PKPassPersonalizationFieldPhoneNumber"
//PKTransitType
TransitTypeAir TransitType = "PKTransitTypeAir"
TransitTypeBoat TransitType = "PKTransitTypeBoat"
TransitTypeBus TransitType = "PKTransitTypeBus"
TransitTypeGeneric TransitType = "PKTransitTypeGeneric"
TransitTypeTrain TransitType = "PKTransitTypeTrain"
)
var (
BarcodeTypesBeforeIos9 = [3]BarcodeFormat{BarcodeFormatQR, BarcodeFormatPDF417, BarcodeFormatAztec}
)
type Validateable interface {
IsValid() bool
GetValidationErrors() []string
}
type Pass struct {
FormatVersion int `json:"formatVersion,omitempty"`
SerialNumber string `json:"serialNumber,omitempty"`
PassTypeIdentifier string `json:"passTypeIdentifier,omitempty"`
WebServiceURL string `json:"webServiceURL,omitempty"`
AuthenticationToken string `json:"authenticationToken,omitempty"`
Description string `json:"description,omitempty"`
TeamIdentifier string `json:"teamIdentifier,omitempty"`
OrganizationName string `json:"organizationName,omitempty"`
LogoText string `json:"logoText,omitempty"`
ForegroundColor string `json:"foregroundColor,omitempty"`
BackgroundColor string `json:"backgroundColor,omitempty"`
LabelColor string `json:"labelColor,omitempty"`
GroupingIdentifier string `json:"groupingIdentifier,omitempty"`
Beacons []Beacon `json:"beacons,omitempty"`
Locations []Location `json:"locations,omitempty"`
Barcodes []Barcode `json:"barcodes,omitempty"`
EventTicket *EventTicket `json:"eventTicket,omitempty"`
Coupon *Coupon `json:"coupon,omitempty"`
StoreCard *StoreCard `json:"storeCard,omitempty"`
BoardingPass *BoardingPass `json:"boardingPass,omitempty"`
Generic *GenericPass `json:"generic,omitempty"`
AppLaunchURL string `json:"appLaunchURL,omitempty"`
AssociatedStoreIdentifiers []int64 `json:"associatedStoreIdentifiers,omitempty"`
UserInfo map[string]interface{} `json:"userInfo,omitempty"`
MaxDistance int64 `json:"maxDistance,omitempty"`
RelevantDate *time.Time `json:"relevantDate,omitempty"`
ExpirationDate *time.Time `json:"expirationDate,omitempty"`
Voided bool `json:"voided,omitempty"`
Nfc *NFC `json:"nfc,omitempty"`
SharingProhibited bool `json:"sharingProhibited,omitempty"`
//Private
associatedApps []PWAssociatedApp `json:"-"`
}
func (p *Pass) SetForegroundColorHex(hex string) error {
h, err := colors.ParseHEX(hex)
if err != nil {
return err
}
p.ForegroundColor = h.ToRGB().String()
return nil
}
func (p *Pass) SetForegroundColorRGB(r, g, b uint8) error {
rgb, _ := colors.RGB(r, g, b)
p.ForegroundColor = rgb.String()
return nil
}
func (p *Pass) SetBackgroundColorHex(hex string) error {
h, err := colors.ParseHEX(hex)
if err != nil {
return err
}
p.BackgroundColor = h.ToRGB().String()
return nil
}
func (p *Pass) SetBackgroundColorRGB(r, g, b uint8) error {
rgb, _ := colors.RGB(r, g, b)
p.BackgroundColor = rgb.String()
return nil
}
func (p *Pass) SetLabelColorHex(hex string) error {
h, err := colors.ParseHEX(hex)
if err != nil {
return err
}
p.LabelColor = h.ToRGB().String()
return nil
}
func (p *Pass) SetLabelColorRGB(r, g, b uint8) error {
rgb, _ := colors.RGB(r, g, b)
p.LabelColor = rgb.String()
return nil
}
func (p *Pass) toJSON() ([]byte, error) {
return json.Marshal(p)
}
func (p *Pass) IsValid() bool {
return len(p.GetValidationErrors()) == 0
}
func (p *Pass) GetValidationErrors() []string {
var validationErrors []string
if strings.TrimSpace(p.SerialNumber) == "" || strings.TrimSpace(p.PassTypeIdentifier) == "" ||
strings.TrimSpace(p.TeamIdentifier) == "" || strings.TrimSpace(p.Description) == "" ||
p.FormatVersion == 0 || strings.TrimSpace(p.OrganizationName) == "" {
validationErrors = append(validationErrors, fmt.Sprintf("Not all required Fields are set. SerialNumber: %q, PassTypeIdentifier: %q, teamIdentifier: %q, Description: ,%q, FormatVersion: %q, OrganizationName: %q", p.SerialNumber, p.PassTypeIdentifier, p.TeamIdentifier, p.Description, p.FormatVersion, p.OrganizationName))
}
if p.EventTicket == nil && p.BoardingPass == nil && p.Coupon == nil && p.StoreCard == nil && p.Generic == nil {
validationErrors = append(validationErrors, fmt.Sprintf("No pass was set. EventTicket: %v, BoardingPass: %v, Coupon: %v, StoreCard: %v, Generic: %v", p.EventTicket, p.BoardingPass, p.Coupon, p.StoreCard, p.Generic))
}
if p.EventTicket != nil && (p.BoardingPass != nil || p.Coupon != nil || p.StoreCard != nil || p.Generic != nil) {
validationErrors = append(validationErrors, "Only one pass should be set")
} else if p.BoardingPass != nil && (p.EventTicket != nil || p.Coupon != nil || p.StoreCard != nil || p.Generic != nil) {
validationErrors = append(validationErrors, "Only one pass should be set")
} else if p.Coupon != nil && (p.BoardingPass != nil || p.EventTicket != nil || p.StoreCard != nil || p.Generic != nil) {
validationErrors = append(validationErrors, "Only one pass should be set")
} else if p.StoreCard != nil && (p.BoardingPass != nil || p.Coupon != nil || p.EventTicket != nil || p.Generic != nil) {
validationErrors = append(validationErrors, "Only one pass should be set")
} else if p.Generic != nil && (p.BoardingPass != nil || p.Coupon != nil || p.StoreCard != nil || p.EventTicket != nil) {
validationErrors = append(validationErrors, "Only one pass should be set")
}
if p.WebServiceURL != "" && (len(p.AuthenticationToken) < expectedAuthTokenLen) {
validationErrors = append(validationErrors,
"The authenticationToken needs to be at least "+strconv.Itoa(expectedAuthTokenLen)+" characters long")
}
if p.EventTicket != nil && !p.EventTicket.IsValid() {
validationErrors = append(validationErrors, p.EventTicket.GetValidationErrors()...)
} else if p.BoardingPass != nil && !p.BoardingPass.IsValid() {
validationErrors = append(validationErrors, p.BoardingPass.GetValidationErrors()...)
} else if p.Coupon != nil && !p.Coupon.IsValid() {
validationErrors = append(validationErrors, p.Coupon.GetValidationErrors()...)
} else if p.StoreCard != nil && !p.StoreCard.IsValid() {
validationErrors = append(validationErrors, p.StoreCard.GetValidationErrors()...)
} else if p.Generic != nil && !p.Generic.IsValid() {
validationErrors = append(validationErrors, p.Generic.GetValidationErrors()...)
}
// If appLaunchURL key is present, the associatedStoreIdentifiers key must also be present
if p.AppLaunchURL != "" && len(p.AssociatedStoreIdentifiers) == 0 {
validationErrors = append(validationErrors, "The appLaunchURL requires associatedStoreIdentifiers to be specified")
}
if !(p.EventTicket == nil && p.BoardingPass == nil && p.Coupon == nil && p.StoreCard == nil && p.Generic == nil) {
// groupingIdentifier key is optional for event tickets and boarding passes; otherwise not allowed
if strings.TrimSpace(p.GroupingIdentifier) != "" && p.EventTicket == nil && p.BoardingPass == nil {
validationErrors = append(validationErrors, "The groupingIdentifier is optional for event tickets and boarding passes, otherwise not allowed")
}
}
return validationErrors
}
func NewGenericPass() *GenericPass {
return &GenericPass{}
}
type GenericPass struct {
HeaderFields []Field `json:"headerFields,omitempty"`
PrimaryFields []Field `json:"primaryFields,omitempty"`
SecondaryFields []Field `json:"secondaryFields,omitempty"`
AuxiliaryFields []Field `json:"auxiliaryFields,omitempty"`
BackFields []Field `json:"backFields,omitempty"`
}
func (gp *GenericPass) AddHeaderField(field Field) {
gp.HeaderFields = append(gp.HeaderFields, field)
}
func (gp *GenericPass) AddPrimaryFields(field Field) {
gp.PrimaryFields = append(gp.PrimaryFields, field)
}
func (gp *GenericPass) AddSecondaryFields(field Field) {
gp.SecondaryFields = append(gp.SecondaryFields, field)
}
func (gp *GenericPass) AddAuxiliaryFields(field Field) {
gp.AuxiliaryFields = append(gp.AuxiliaryFields, field)
}
func (gp *GenericPass) AddBackFields(field Field) {
gp.BackFields = append(gp.BackFields, field)
}
func (gp *GenericPass) IsValid() bool {
return len(gp.GetValidationErrors()) == 0
}
func (gp *GenericPass) GetValidationErrors() []string {
var validationErrors []string
var fields [][]Field
fields = append(fields, gp.HeaderFields)
fields = append(fields, gp.PrimaryFields)
fields = append(fields, gp.SecondaryFields)
fields = append(fields, gp.AuxiliaryFields)
fields = append(fields, gp.BackFields)
for _, fieldList := range fields {
for _, field := range fieldList {
if !field.IsValid() {
validationErrors = append(validationErrors, field.GetValidationErrors()...)
}
}
}
return validationErrors
}
func NewBoardingPass(transitType TransitType) *BoardingPass {
return &BoardingPass{GenericPass: NewGenericPass(), TransitType: transitType}
}
type BoardingPass struct {
*GenericPass
TransitType TransitType `json:"transitType,omitempty"`
}
func (b *BoardingPass) IsValid() bool {
return len(b.GetValidationErrors()) == 0
}
func (b *BoardingPass) GetValidationErrors() []string {
var validationErrors []string
validationErrors = append(validationErrors, b.GenericPass.GetValidationErrors()...)
if string(b.TransitType) == "" {
validationErrors = append(validationErrors, "TransitType is not set")
}
return validationErrors
}
func NewCoupon() *Coupon {
return &Coupon{GenericPass: NewGenericPass()}
}
type Coupon struct {
*GenericPass
}
func NewEventTicket() *EventTicket {
return &EventTicket{GenericPass: NewGenericPass()}
}
type EventTicket struct {
*GenericPass
}
func NewStoreCard() *StoreCard {
return &StoreCard{GenericPass: NewGenericPass()}
}
type StoreCard struct {
*GenericPass
}
type Field struct {
Key string `json:"key,omitempty"`
Label string `json:"label,omitempty"`
Value interface{} `json:"value,omitempty"`
AttributedValue interface{} `json:"attributedValue,omitempty"`
ChangeMessage string `json:"changeMessage,omitempty"`
TextAlignment TextAlignment `json:"textAlignment,omitempty"`
DataDetectorTypes []DataDetectorType `json:"dataDetectorTypes,omitempty"`
CurrencyCode string `json:"currencyCode,omitempty"`
NumberStyle NumberStyle `json:"numberStyle,omitempty"`
DateStyle DateStyle `json:"dateStyle,omitempty"`
TimeStyle DateStyle `json:"timeStyle,omitempty"`
IsRelative bool `json:"isRelative,omitempty"`
IgnoreTimeZone bool `json:"ignoresTimeZone,omitempty"`
}
func (f *Field) IsValid() bool {
return len(f.GetValidationErrors()) == 0
}
func (f *Field) GetValidationErrors() []string {
var validationErrors []string
if f.Value == nil || f.Key == "" {
validationErrors = append(validationErrors, fmt.Sprintf("Not all required Fields are set. Key: %v Value: %v", f.Key, f.Value))
}
if f.Value != nil {
switch f.Value.(type) {
case string:
case int:
case int8:
case int16:
case int32:
case int64:
case float32:
case float64:
case time.Time:
default:
validationErrors = append(validationErrors, "Invalid value type. Allowed: string, int, float, time.Time")
}
}
if strings.TrimSpace(f.CurrencyCode) != "" && string(f.NumberStyle) != "" {
validationErrors = append(validationErrors, "CurrencyCode and numberStyle are both set")
}
if (strings.TrimSpace(f.CurrencyCode) != "" || string(f.NumberStyle) != "") && (string(f.DateStyle) != "" || string(f.TimeStyle) != "") {
validationErrors = append(validationErrors, "Can't be number/currency and date at the same time")
}
if strings.TrimSpace(f.ChangeMessage) != "" && !strings.Contains(f.ChangeMessage, "%@") {
validationErrors = append(validationErrors, "ChangeMessage needs to contain %@ placeholder")
}
if strings.TrimSpace(f.CurrencyCode) != "" {
switch f.Value.(type) {
case int:
case int8:
case int16:
case int32:
case int64:
case float32:
case float64:
default:
validationErrors = append(validationErrors, "When using currencies, the values have to be numbers")
}
}
return validationErrors
}
type Beacon struct {
Major int `json:"major,omitempty"`
Minor int `json:"minor,omitempty"`
ProximityUUID string `json:"proximityUUID,omitempty"`
RelevantText string `json:"relevantText,omitempty"`
}
func (b *Beacon) IsValid() bool {
return len(b.GetValidationErrors()) == 0
}
func (b *Beacon) GetValidationErrors() []string {
var validationErrors []string
if strings.TrimSpace(b.ProximityUUID) == "" {
validationErrors = append(validationErrors, "Not all required Fields are set: proximityUUID")
}
return validationErrors
}
type Location struct {
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
Altitude float64 `json:"altitude,omitempty"`
RelevantText string `json:"relevantText,omitempty"`
}
func (l *Location) IsValid() bool {
return len(l.GetValidationErrors()) == 0
}
func (l *Location) GetValidationErrors() []string {
return []string{}
}
type Barcode struct {
Format BarcodeFormat `json:"format,omitempty"`
AltText string `json:"altText,omitempty"`
Message string `json:"message,omitempty"`
MessageEncoding string `json:"messageEncoding,omitempty"`
}
func (b *Barcode) IsValid() bool {
return len(b.GetValidationErrors()) == 0
}
func (b *Barcode) GetValidationErrors() []string {
var validationErrors []string
if string(b.Format) == "" || strings.TrimSpace(b.Message) == "" || strings.TrimSpace(b.MessageEncoding) == "" || strings.TrimSpace(b.AltText) == "" {
validationErrors = append(validationErrors, fmt.Sprintf("Not all required Fields are set. Format: %v, Message: %v, MessageEncoding: %v, AltText: %v", b.Format, b.Message, b.MessageEncoding, b.AltText))
}
return validationErrors
}
type PWAssociatedApp struct {
Title string
IdGooglePlay string
IdAmazon string
}
func (a *PWAssociatedApp) IsValid() bool {
return len(a.GetValidationErrors()) == 0
}
func (a *PWAssociatedApp) GetValidationErrors() []string {
return []string{}
}
type NFC struct {
Message string `json:"message,omitempty"`
EncryptionPublicKey string `json:"encryptionPublicKey,omitempty"`
RequiresAuthentication bool `json:"requiresAuthentication,omitempty"`
}
type Personalization struct {
RequiredPersonalizationFields []PassPersonalizationField `json:"requiredPersonalizationFields"`
Description string `json:"description"`
TermsAndConditions string `json:"termsAndConditions"`
}
func (pz *Personalization) toJSON() ([]byte, error) {
return json.Marshal(pz)
}
func (pz *Personalization) IsValid() bool {
return len(pz.GetValidationErrors()) == 0
}
func (pz *Personalization) GetValidationErrors() []string {
var validationErrors []string
if len(pz.RequiredPersonalizationFields) == 0 {
validationErrors = append(validationErrors, "You need to provide at least one requiredPersonalizationField")
}
if strings.TrimSpace(pz.Description) == "" {
validationErrors = append(validationErrors, "You need to provide a description")
}
return validationErrors
}