This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
/
listing.go
1844 lines (1662 loc) · 54.4 KB
/
listing.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package repo
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"math/big"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
cid "gx/ipfs/QmTbxNB1NwDesLmKTscr4udL2tVP7MaxvXnD1D9yX7g3PN/go-cid"
mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
"github.com/OpenBazaar/jsonpb"
"github.com/OpenBazaar/openbazaar-go/ipfs"
"github.com/OpenBazaar/openbazaar-go/pb"
"github.com/OpenBazaar/openbazaar-go/util"
"github.com/golang/protobuf/proto"
"github.com/gosimple/slug"
"github.com/microcosm-cc/bluemonday"
)
const (
// ListingVersion - current listing version
ListingVersion = 5
// TitleMaxCharacters - max size for title
TitleMaxCharacters = 140
// ShortDescriptionLength - min length for description
ShortDescriptionLength = 160
// DescriptionMaxCharacters - max length for description
DescriptionMaxCharacters = 50000
// MaxTags - max permitted tags
MaxTags = 10
// MaxCategories - max permitted categories
MaxCategories = 10
// MaxListItems - max items in a listing
MaxListItems = 30
// FilenameMaxCharacters - max filename size
FilenameMaxCharacters = 255
// CodeMaxCharacters - max chars for a code
CodeMaxCharacters = 20
// WordMaxCharacters - max chars for word
WordMaxCharacters = 40
// SentenceMaxCharacters - max chars for sentence
SentenceMaxCharacters = 70
// CouponTitleMaxCharacters - max length of a coupon title
CouponTitleMaxCharacters = 70
// PolicyMaxCharacters - max length for policy
PolicyMaxCharacters = 10000
// AboutMaxCharacters - max length for about
AboutMaxCharacters = 10000
// URLMaxCharacters - max length for URL
URLMaxCharacters = 2000
// MaxCountryCodes - max country codes
MaxCountryCodes = 255
// DefaultEscrowTimeout - escrow timeout in hours
DefaultEscrowTimeout = 1080
// SlugBuffer - buffer size for slug
SlugBuffer = 5
// PriceModifierMin - min price modifier
PriceModifierMin = -99.99
// PriceModifierMax = max price modifier
PriceModifierMax = 1000.00
)
type option struct {
Name string `json:"name"`
Value string `json:"value"`
}
type options []option
func (os options) ToOrderOptionSetProtobuf() []*pb.Order_Item_Option {
var optionProtos = make([]*pb.Order_Item_Option, len(os))
for i, o := range os {
optionProtos[i] = &pb.Order_Item_Option{
Name: o.Name,
Value: o.Value,
}
}
return optionProtos
}
type shippingOption struct {
Name string `json:"name"`
Service string `json:"service"`
}
// Item represents a purchased item
type Item struct {
ListingHash string `json:"listingHash"`
Quantity string `json:"bigQuantity"`
Options options `json:"options"`
Shipping shippingOption `json:"shipping"`
Memo string `json:"memo"`
Coupons []string `json:"coupons"`
PaymentAddress string `json:"paymentAddress"`
}
// PurchaseData represents purchase request metadata
type PurchaseData struct {
ShipTo string `json:"shipTo"`
Address string `json:"address"`
City string `json:"city"`
State string `json:"state"`
PostalCode string `json:"postalCode"`
CountryCode string `json:"countryCode"`
AddressNotes string `json:"addressNotes"`
Moderator string `json:"moderator"`
Items []Item `json:"items"`
AlternateContactInfo string `json:"alternateContactInfo"`
RefundAddress *string `json:"refundAddress"` //optional, can be left out of json
PaymentCoin string `json:"paymentCoin"`
}
// IndividualListingContainer is a wrapper for a single listing
type IndividualListingContainer struct {
Listing `json:"listing"`
}
// Listing represents a trade offer which can be accepted by another
// party on the OpenBazaar network
type Listing struct {
listingProto *pb.Listing
proto.Message
}
func (l *Listing) Reset() { *l = Listing{} }
func (l *Listing) String() string { return proto.CompactTextString(l) }
func (*Listing) ProtoMessage() {}
// NewListingFromProtobuf - return Listing from pb.Listing
func NewListingFromProtobuf(l *pb.Listing) (*Listing, error) {
clonedListing := proto.Clone(l).(*pb.Listing)
if clonedListing.Metadata.Version == 0 {
clonedListing.Metadata.Version = ListingVersion
}
if clonedListing.Metadata.EscrowTimeoutHours == 0 {
clonedListing.Metadata.EscrowTimeoutHours = DefaultEscrowTimeout
}
return &Listing{
listingProto: clonedListing,
}, nil
}
// CreateListing will create a pb Listing
func CreateListing(r []byte, isTestnet bool, dstore *Datastore, repoPath string) (Listing, error) {
ld := new(pb.Listing)
err := jsonpb.UnmarshalString(string(r), ld)
if err != nil {
return Listing{}, err
}
slug := ld.Slug
exists, err := listingExists(slug, repoPath, isTestnet)
if err != nil {
return Listing{}, err
}
if exists {
return Listing{}, ErrListingAlreadyExists
}
if slug == "" {
slug, err = GenerateSlug(ld.Item.Title, repoPath, isTestnet, dstore)
if err != nil {
return Listing{}, err
}
ld.Slug = slug
}
retListing, err := NewListingFromProtobuf(ld)
return *retListing, err
}
// UpdateListing will update a pb Listing
func UpdateListing(r []byte, isTestnet bool, dstore *Datastore, repoPath string) (Listing, error) {
ld := new(pb.Listing)
err := jsonpb.UnmarshalString(string(r), ld)
if err != nil {
return Listing{}, err
}
skus := ld.Item.Skus
for _, sku := range skus {
if sku.BigSurcharge == "" {
sku.BigSurcharge = "0"
}
if sku.BigQuantity == "" {
sku.BigQuantity = "0"
}
}
ld.Item.Skus = skus
slug := ld.Slug
exists, err := listingExists(slug, repoPath, isTestnet)
if err != nil {
return Listing{}, err
}
if !exists {
return Listing{}, ErrListingDoesNotExist
}
retListing, err := NewListingFromProtobuf(ld)
return *retListing, err
}
func listingExists(slug, repoPath string, isTestnet bool) (bool, error) {
if slug == "" {
return false, nil
}
fPath, err := GetPathForListingSlug(slug, repoPath, isTestnet)
if err != nil {
return false, err
}
_, ferr := os.Stat(fPath)
if slug == "" {
return false, nil
}
if os.IsNotExist(ferr) {
return false, nil
}
if ferr != nil {
return false, ferr
}
return true, nil
}
// GenerateSlug - slugify the title of the listing
func GenerateSlug(title, repoPath string, isTestnet bool, dStore *Datastore) (string, error) {
title = strings.Replace(title, "/", "", -1)
counter := 1
slugBase := CreateSlugFor(title)
slugToTry := slugBase
for {
_, err := GetListingFromSlug(slugToTry, repoPath, isTestnet, dStore)
if os.IsNotExist(err) {
return slugToTry, nil
} else if err != nil {
return "", err
}
slugToTry = slugBase + strconv.Itoa(counter)
counter++
}
}
// GetListingFromSlug - fetch listing for the specified slug
func GetListingFromSlug(slug, repoPath string, isTestnet bool, dStore *Datastore) (*pb.SignedListing, error) {
repoPath, err := GetRepoPath(isTestnet, repoPath)
if err != nil {
return nil, err
}
// Read listing file
listingPath := path.Join(repoPath, "root", "listings", slug+".json")
file, err := ioutil.ReadFile(listingPath)
if err != nil {
return nil, err
}
// Unmarshal listing
sl := new(pb.SignedListing)
err = jsonpb.UnmarshalString(string(file), sl)
if err != nil {
return nil, err
}
// Get the listing inventory
inventory, err := (*dStore).Inventory().Get(slug)
if err != nil {
return nil, err
}
// Build the inventory list
for variant, count := range inventory {
for i, s := range sl.Listing.Item.Skus {
if variant == i {
s.BigQuantity = count.String()
break
}
}
}
for _, s := range sl.Listing.Item.Skus {
if s.BigSurcharge == "" {
s.BigSurcharge = "0"
}
}
return sl, nil
}
func GetPathForListingSlug(slug, repoPath string, isTestnet bool) (string, error) {
repoPath, err := GetRepoPath(isTestnet, repoPath)
if err != nil {
return "", err
}
return path.Join(repoPath, "root", "listings", slug+".json"), nil
}
func ToHtmlEntities(str string) string {
var rx = regexp.MustCompile(util.EmojiPattern)
return rx.ReplaceAllStringFunc(str, func(s string) string {
r, _ := utf8.DecodeRuneInString(s)
html := fmt.Sprintf(`&#x%X;`, r)
return html
})
}
// CreateSlugFor Create a slug from a multi-lang string
func CreateSlugFor(slugName string) string {
l := SentenceMaxCharacters - SlugBuffer
slugName = ToHtmlEntities(slugName)
slug := slug.Make(slugName)
if len(slug) < SentenceMaxCharacters-SlugBuffer {
l = len(slug)
}
return slug[:l]
}
// ListingMetadata -
type ListingMetadata struct {
Version uint `json:"version"`
}
// UnmarshalJSONListing - unmarshal listing
func UnmarshalJSONListing(data []byte) (*Listing, error) {
l, err := UnmarshalJSONSignedListing(data)
if err != nil {
return nil, err
}
return l.GetListing(), nil
}
// ExtractVersion returns the version of the listing
func ExtractVersionFromSignedListing(data []byte) (uint, error) {
type sl struct {
Listing interface{} `json:"listing"`
}
var s sl
err := json.Unmarshal(data, &s)
if err != nil {
return 0, err
}
lmap, ok := s.Listing.(map[string]interface{})
if !ok {
return 0, errors.New("malformed listing")
}
lampMeta0, ok := lmap["metadata"]
if !ok {
return 0, errors.New("malformed listing")
}
lampMeta, ok := lampMeta0.(map[string]interface{})
if !ok {
return 0, errors.New("malformed listing")
}
ver0, ok := lampMeta["version"]
if !ok {
return 0, errors.New("malformed listing")
}
ver, ok := ver0.(float64)
if !ok {
return 0, errors.New("malformed listing")
}
return uint(ver), nil
}
// ExtractIDFromListing returns pb.ID of the listing
func ExtractIDFromListing(data []byte) (*pb.ID, error) {
var lmap map[string]*json.RawMessage
vendorPlay := new(pb.ID)
err := json.Unmarshal(data, &lmap)
if err != nil {
log.Error(err)
return vendorPlay, err
}
err = json.Unmarshal(*lmap["vendorID"], &vendorPlay)
if err != nil {
log.Error(err)
return vendorPlay, err
}
return vendorPlay, nil
}
// Normalize converts legacy schema listing data from other users on the network
// to fit the latest schema for consumption via the API for local use. NOTE: Legacy
// nodes do not understand the latest schema. As such, normalized listings must not
// be used as part of the RicardianContract and must be serialized and used as they
// were provided by the originating node.
func (l *Listing) Normalize() (*Listing, error) {
if l == nil {
return nil, errors.New("nil listing cannot be normalized")
}
if l.GetVersion() == ListingVersion {
return l, nil
}
nl, err := NewListingFromProtobuf(l.listingProto)
if err != nil {
return nil, fmt.Errorf("creating listing clone: %s", err.Error())
}
nlp := nl.GetProtobuf()
nlp.Metadata.Version = ListingVersion
if p, err := l.GetPrice(); err != nil {
return nil, fmt.Errorf("get price: %s", err.Error())
} else {
nlp.Item.BigPrice = p.Amount.String()
nlp.Item.PriceCurrency = &pb.CurrencyDefinition{
Code: p.Currency.Code.String(),
Divisibility: uint32(p.Currency.Divisibility),
}
}
if ss, err := l.GetSkus(); err != nil {
return nil, fmt.Errorf("get skus: %s", err.Error())
} else {
nlp.Item.Skus = ss
}
if sos, err := l.GetShippingOptions(); err != nil {
return nil, fmt.Errorf("get shipping options: %s", err.Error())
} else {
nlp.ShippingOptions = sos
}
if cs, err := l.GetCoupons(); err != nil {
return nil, fmt.Errorf("get coupons: %s", err.Error())
} else {
nlp.Coupons = cs.GetProtobuf()
}
return nl, nil
}
// GetProtobuf returns the current state of pb.Listing managed by Listing
func (l *Listing) GetProtobuf() *pb.Listing {
return l.listingProto
}
// GetVersion returns the schema version of the Listing
func (l *Listing) GetVersion() uint32 {
return l.listingProto.Metadata.Version
}
// GetCryptoDivisibility returns the listing crypto divisibility
func (l *Listing) GetCryptoDivisibility() uint32 {
if l.GetContractType() != pb.Listing_Metadata_CRYPTOCURRENCY.String() {
return 0
}
switch l.GetVersion() {
case 5:
return l.listingProto.Metadata.CryptoDivisibility
default: // version < 4
div := l.listingProto.Metadata.CryptoDivisibility
if div != 0 {
div = uint32(math.Log10(float64(div)))
}
return div
}
}
// GetCryptoCurrencyCode returns the listing crypto currency code
func (l *Listing) GetCryptoCurrencyCode() string {
if l.GetContractType() != pb.Listing_Metadata_CRYPTOCURRENCY.String() {
return ""
}
return l.listingProto.Metadata.CryptoCurrencyCode
}
// GetTitle returns the listing item title
func (l *Listing) GetTitle() string {
return l.listingProto.Item.Title
}
// GetSlug returns the listing slug
func (l *Listing) GetSlug() string {
return l.listingProto.Slug
}
// GetAcceptedCurrencies returns the listing's list of accepted currency codes
func (l *Listing) GetAcceptedCurrencies() []string {
return l.listingProto.Metadata.AcceptedCurrencies
}
// SetAcceptedCurrencies the listing's accepted currency codes. Assumes the node
// serving the listing has already validated the wallet supports the currencies.
func (l *Listing) SetAcceptedCurrencies(codes ...string) error {
if len(codes) < 1 {
return errors.New("no accepted currencies provided")
}
var accCurrencies = make([]string, 0)
for _, c := range codes {
def, err := AllCurrencies().Lookup(c)
if err != nil {
return fmt.Errorf("unknown accepted currency (%s)", c)
}
accCurrencies = append(accCurrencies, def.CurrencyCode().String())
}
l.listingProto.Metadata.AcceptedCurrencies = accCurrencies
return nil
}
// GetContractType returns listing's contract type
func (l *Listing) GetContractType() string {
return l.listingProto.Metadata.ContractType.String()
}
// GetFormat returns the listing's pricing format
func (l *Listing) GetFormat() string {
return l.listingProto.Metadata.Format.String()
}
// GetPrice returns the listing price. For CRYPTOCURRENCY listings, this
// value would be zero in the denomination of the cryptocurrency being
// traded and the item value in all other cases. In the event that the
// shema version or contract type are unrecognizable, an error is returned.
func (l *Listing) GetPrice() (*CurrencyValue, error) {
switch l.GetContractType() {
case pb.Listing_Metadata_CRYPTOCURRENCY.String():
return &CurrencyValue{
Amount: big.NewInt(0),
Currency: NewUnknownCryptoDefinition(l.GetCryptoCurrencyCode(), 0),
}, nil
case pb.Listing_Metadata_DIGITAL_GOOD.String(), pb.Listing_Metadata_PHYSICAL_GOOD.String(), pb.Listing_Metadata_SERVICE.String():
switch l.GetVersion() {
case 5:
return NewCurrencyValueFromProtobuf(l.listingProto.Item.BigPrice, l.listingProto.Item.PriceCurrency)
case 4, 3, 2:
priceCurrency, err := AllCurrencies().Lookup(l.listingProto.Metadata.PricingCurrency)
if err != nil {
return nil, fmt.Errorf("lookup metadata pricing currency: %s", err)
}
return NewCurrencyValueFromUint(l.listingProto.Item.Price, priceCurrency)
default:
return nil, fmt.Errorf("unknown schema version")
}
}
return nil, fmt.Errorf("unknown contract type")
}
// GetModerators returns accepted moderators for the listing
func (l *Listing) GetModerators() []string {
return l.listingProto.Moderators
}
// SetModerators updates the listing's accepted moderators
func (l *Listing) SetModerators(mods []string) error {
l.listingProto.Moderators = mods
// mutations should return an error, even if no error is possible today
return nil
}
// GetTermsAndConditions return the terms for the listings purchase contract
func (l *Listing) GetTermsAndConditions() string {
return l.listingProto.TermsAndConditions
}
// GetRefundPolicy return the refund policy for the listing
func (l *Listing) GetRefundPolicy() string {
return l.listingProto.RefundPolicy
}
// GetVendorID returns the vendor peer ID
func (l *Listing) GetVendorID() *PeerInfo {
return NewPeerInfoFromProtobuf(l.listingProto.VendorID)
}
// GetShortDescription returns the item description truncated down to the
// ShortDescriptionLength maximum
func (l *Listing) GetShortDescription() string {
dl := len(l.GetDescription())
if dl > ShortDescriptionLength {
return l.GetDescription()[:ShortDescriptionLength]
}
return l.GetDescription()
}
// GetDescription returns item description
func (l *Listing) GetDescription() string {
return l.listingProto.Item.Description
}
// GetProcessingTime returns the expected time for vendor to process listing fulfillment
func (l *Listing) GetProcessingTime() string {
return l.listingProto.Item.ProcessingTime
}
// GetNSFW returns whether the listing is marked as inappropriate for general viewing
// or otherwise "Not Safe For Work"
func (l *Listing) GetNsfw() bool {
return l.listingProto.Item.Nsfw
}
// GetTags returns a list of tags for the listing
func (l *Listing) GetTags() []string {
return l.listingProto.Item.Tags
}
// GetCategories returns a list of categories for the listing
func (l *Listing) GetCategories() []string {
return l.listingProto.Item.Categories
}
// GetGrams returns listing item weight in grams
func (l *Listing) GetWeightGrams() float32 {
return l.listingProto.Item.Grams
}
// GetCondition returns listing item condition
func (l *Listing) GetCondition() string {
return l.listingProto.Item.Condition
}
// ListingImage represents the underlying protobuf image
type ListingImage struct {
listing *Listing
protoIndex int
filename string
original string
large string
medium string
small string
tiny string
}
// GetFilename returns the image filename
func (i *ListingImage) GetFilename() string { return i.filename }
// GetOriginal returns the image's original size
func (i *ListingImage) GetOriginal() string { return i.original }
// GetLarge returns the image's large size
func (i *ListingImage) GetLarge() string { return i.large }
// GetMedium returns the image's medium size
func (i *ListingImage) GetMedium() string { return i.medium }
// GetSmall returns the image's small size
func (i *ListingImage) GetSmall() string { return i.small }
// GetTiny returns the image's tiny size
func (i *ListingImage) GetTiny() string { return i.tiny }
// String satisfies Stringer and returns the image filename
func (i *ListingImage) String() string { return i.GetFilename() }
func (i *ListingImage) imageProtobuf() (*pb.Listing_Item_Image, error) {
if i == nil ||
i.listing == nil ||
i.listing.listingProto == nil ||
i.listing.listingProto.Item == nil ||
i.listing.listingProto.Item.Images == nil {
return nil, fmt.Errorf("listing item image incomplete")
}
pbImg := i.listing.listingProto.Item.Images[i.protoIndex]
if i.filename != pbImg.GetFilename() ||
i.original != pbImg.GetOriginal() ||
i.large != pbImg.GetLarge() ||
i.medium != pbImg.GetMedium() ||
i.small != pbImg.GetSmall() ||
i.tiny != pbImg.GetTiny() {
return nil, fmt.Errorf("underlying protobuf has changed from expected state")
}
return pbImg, nil
}
// SetOriginal updates CID for the original image
func (i *ListingImage) SetOriginal(cid string) error {
var pbi, err = i.imageProtobuf()
if err != nil {
return fmt.Errorf("set original image hash: %s", err.Error())
}
pbi.Original = cid
i.original = cid
return nil
}
// SetLarge updates CID for the large image
func (i *ListingImage) SetLarge(cid string) error {
var pbi, err = i.imageProtobuf()
if err != nil {
return fmt.Errorf("set large image hash: %s", err.Error())
}
pbi.Large = cid
i.large = cid
return nil
}
// SetMedium updates CID for the medium image
func (i *ListingImage) SetMedium(cid string) error {
var pbi, err = i.imageProtobuf()
if err != nil {
return fmt.Errorf("set medium image hash: %s", err.Error())
}
pbi.Medium = cid
i.medium = cid
return nil
}
// SetSmall updates CID for the small image
func (i *ListingImage) SetSmall(cid string) error {
var pbi, err = i.imageProtobuf()
if err != nil {
return fmt.Errorf("set small image hash: %s", err.Error())
}
pbi.Small = cid
i.small = cid
return nil
}
// SetTiny updates CID for the tiny image
func (i *ListingImage) SetTiny(cid string) error {
var pbi, err = i.imageProtobuf()
if err != nil {
return fmt.Errorf("set tiny image hash: %s", err.Error())
}
pbi.Tiny = cid
i.tiny = cid
return nil
}
// GetImages return set of listing item images
func (l *Listing) GetImages() []*ListingImage {
if l == nil ||
l.listingProto == nil ||
l.listingProto.Item == nil ||
l.listingProto.Item.Images == nil {
return make([]*ListingImage, 0)
}
var (
protoImgs = l.listingProto.Item.Images
imgs = make([]*ListingImage, len(protoImgs))
)
for i, img := range protoImgs {
imgs[i] = &ListingImage{
listing: l,
protoIndex: i,
filename: img.GetFilename(),
original: img.GetOriginal(),
large: img.GetLarge(),
medium: img.GetMedium(),
small: img.GetSmall(),
tiny: img.GetTiny(),
}
}
return imgs
}
// GetSkus returns the listing SKUs
func (l *Listing) GetSkus() ([]*pb.Listing_Item_Sku, error) {
var ss = make([]*pb.Listing_Item_Sku, len(l.listingProto.Item.Skus))
for i, s := range l.listingProto.Item.Skus {
ss[i] = proto.Clone(s).(*pb.Listing_Item_Sku)
}
switch l.GetVersion() {
case 3, 4:
for _, sku := range ss {
sku.BigSurcharge = big.NewInt(sku.Surcharge).String()
sku.BigQuantity = big.NewInt(sku.Quantity).String()
}
}
return ss, nil
}
//GetLanguage return listing's language
func (l *Listing) GetLanguage() string {
return l.listingProto.Metadata.Language
}
// GetEscrowTimeout return listing's escrow timeout in hours
func (l *Listing) GetEscrowTimeoutHours() uint32 {
return l.listingProto.Metadata.EscrowTimeoutHours
}
// GetPriceModifier return listing's price modifier
func (l *Listing) GetPriceModifier() float32 {
switch l.GetVersion() {
case 5:
return l.listingProto.Item.PriceModifier
case 4, 3, 2:
return l.listingProto.Metadata.PriceModifier
}
log.Errorf("missing price modifier for listing (%s)", l.GetSlug())
return 0
}
// ListingTaxes is a set of taxes
type ListingTaxes []ListingTax
// ListingTax describes how a listing is taxed in each region
type ListingTax struct {
taxType string
regions []string
rate float32
taxableShipping bool
}
// GetType returns the tax type
func (t ListingTax) GetType() string { return t.taxType }
// GetApplicableRegions returns the regions affected by the tax
func (t ListingTax) GetApplicableRegions() []string { return t.regions }
// GetRate returns the tax rate
func (t ListingTax) GetRate() float32 { return t.rate }
// GetTaxableShipping indicates whether the shipping is subject to the tax
func (t ListingTax) GetTaxableShipping() bool { return t.taxableShipping }
// GetTaxes returns listing tax information
func (l *Listing) GetTaxes() ListingTaxes {
var ts = make([]ListingTax, len(l.listingProto.Taxes))
for ti, tax := range l.listingProto.Taxes {
var rs = make([]string, len(tax.TaxRegions))
for ri, region := range tax.TaxRegions {
rs[ri] = region.String()
}
ts[ti] = ListingTax{
taxType: tax.GetTaxType(),
rate: tax.GetPercentage(),
taxableShipping: tax.GetTaxShipping(),
regions: rs,
}
}
return ts
}
type couponGetter interface {
Get(string) ([]Coupon, error)
}
// UpdateCouponsFromDatastore will get all coupons from the datastore and update
// the internal protobuf with the codes that match the coupon's hash, if any.
func (l *Listing) UpdateCouponsFromDatastore(cdb couponGetter) error {
var coupons, err = l.GetCoupons()
if err != nil {
return fmt.Errorf("getting coupons: %s", err.Error())
}
dbCoupons, err := cdb.Get(l.GetSlug())
if err != nil {
return fmt.Errorf("loading datastore coupon: %s", err.Error())
}
for i, c := range coupons {
for _, dbc := range dbCoupons {
if c.redemptionHash == dbc.Hash {
// make sure applying code does not shift already-matched hash
expectedHash, err := ipfs.EncodeMultihash([]byte(dbc.Code))
if err != nil {
return fmt.Errorf("hashing persisted redemption code (%s): %s", dbc.Code, err.Error())
}
if c.redemptionHash != expectedHash.B58String() {
return fmt.Errorf("update coupon code (%s) results in mismatched published hash", dbc.Code)
}
if err := coupons[i].SetRedemptionCode(dbc.Code); err != nil {
return fmt.Errorf("setting redemption code: %s", err.Error())
}
}
}
}
l.listingProto.Coupons = coupons.GetProtobuf()
return nil
}
// GetCoupons returns listing coupons with discount amount normalized as a
// CurrencyValue
func (l *Listing) GetCoupons() (ListingCoupons, error) {
var (
protoCoupons = l.listingProto.GetCoupons()
cs = make([]*ListingCoupon, len(protoCoupons))
listingVersion = l.GetVersion()
discPrice, err = l.GetPrice()
)
if err != nil {
return nil, fmt.Errorf("get listing price for coupon: %s", err.Error())
}
for i, c := range protoCoupons {
var (
discAmt string
discValue *CurrencyValue
)
switch listingVersion {
case 5:
discAmt = c.GetBigPriceDiscount()
default:
//nolint:staticcheck
discAmt = strconv.FormatUint(c.GetPriceDiscount(), 10)
}
if discAmt != "" {
dv, err := NewCurrencyValue(discAmt, discPrice.Currency)
if err != nil {
return nil, fmt.Errorf("unable to create coupon discount value for amount (%s %s): %s", discAmt, discPrice.Currency, err.Error())
}
discValue = dv
} else {
discValue = nil
}
cs[i] = &ListingCoupon{
listing: l,
title: c.GetTitle(),
redemptionCode: c.GetDiscountCode(),
redemptionHash: c.GetHash(),
discountPercent: c.GetPercentDiscount(),
discountAmount: discValue,
}
}
return cs, nil
}
// ListingCoupons is a set of listing coupons
type ListingCoupons []*ListingCoupon
// GetProtobuf converts ListingCoupons into its protobuf representation
func (cs ListingCoupons) GetProtobuf() []*pb.Listing_Coupon {
var cspb = make([]*pb.Listing_Coupon, len(cs))
for i, c := range cs {
cspb[i] = &pb.Listing_Coupon{
Title: c.GetTitle(),
}
if c.GetPercentOff() > 0 {
cspb[i].Discount = &pb.Listing_Coupon_PercentDiscount{
PercentDiscount: c.GetPercentOff(),
}
} else if c.GetAmountOff() != nil {
cspb[i].Discount = &pb.Listing_Coupon_BigPriceDiscount{
BigPriceDiscount: c.GetAmountOff().Amount.String(),
}
}
if hash, err := c.GetRedemptionHash(); err == nil {
cspb[i].Code = &pb.Listing_Coupon_Hash{Hash: hash}
}
if code, err := c.GetRedemptionCode(); err == nil {
cspb[i].Code = &pb.Listing_Coupon_DiscountCode{DiscountCode: code}
}
}
return cspb
}
// ListingCoupon represents an coupon which can be applied to a listing for a discount
type ListingCoupon struct {
listing *Listing
title string
redemptionCode string
redemptionHash string
discountPercent float32
discountAmount *CurrencyValue
}
// GetListingSlug returns the slug for the coupon's listing
func (c *ListingCoupon) GetListingSlug() string { return c.listing.GetSlug() }
// GetTitle returns the coupon's title
func (c *ListingCoupon) GetTitle() string { return c.title }
// GetRedemptionCode returns the coupon redemption code
func (c *ListingCoupon) GetRedemptionCode() (string, error) {
if c.redemptionCode != "" {
return c.redemptionCode, nil
}
return "", errors.New("redemption code not set")
}
// GetRedemptionHash returns the hashed representation of the code
func (c *ListingCoupon) GetRedemptionHash() (string, error) {
_, err := mh.FromB58String(c.redemptionHash)
if err != nil {
// if hash is invalid, let's try to produce a new one
if c.redemptionCode == "" {
return "", errors.New("hash invalid and code missing")
}
if err := c.SetRedemptionCode(c.redemptionCode); err != nil {
return "", err
}
}
return c.redemptionHash, nil