/
detail.go
241 lines (186 loc) · 5.5 KB
/
detail.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
package client
import (
"errors"
"github.com/secr3t/otcommerce-client/model"
"github.com/tidwall/gjson"
"io/ioutil"
"math"
"net/http"
"net/url"
"regexp"
)
const (
getItemDescription = `GetItemOriginalDescription`
InstanceKeyParam = `instanceKey`
ItemIdParam = `itemId`
DescEncodedString = `\"`
DescDecodedString = `"`
DescriptionPath = `OtapiItemDescription.ItemDescription`
getItemFullInfoWithPromotions = `GetItemFullInfoWithPromotions`
ItemParam = `itemParameters`
ItemParamValue = `<Parameters AllowIncomplete="false" AllowDeleted="false" WaitingTime="500"/>`
FullInfoPath = `OtapiItemFullInfo`
AttributesPath = `Attributes.#(IsConfigurator==true)#`
CombinationPath = `ConfiguredItems.#(Quantity!=0)#`
PromotionsPath = `Promotions.#.ConfiguredItems`
OptionName = `OriginalPropertyName`
OptionValue = `OriginalValue`
OptionImage = `ImageUrl`
Configurators = `Configurators`
)
var (
DescFail = errors.New("get desc failed")
DetailFail = errors.New("get detail failed")
DescRegex = regexp.MustCompile(`img\.alicdn\.com/imgextra/\w{2}/\w+/[\w_!]+\.jpg`)
)
type DetailClient struct {
ApiKey string
}
func NewDetailClient(apiKey string) *DetailClient {
return &DetailClient{
ApiKey: apiKey,
}
}
func (c *DetailClient) GetDescImgs(id string) ([]string, error) {
imgs, err := c.getDescImgs(id)
if err == nil && len(imgs) == 0 {
imgs, err = c.getDescImgs(id)
}
return imgs, err
}
func (c *DetailClient) getDescImgs(id string) ([]string, error) {
q := url.Values{}
q.Add(ItemIdParam, id)
q.Add(InstanceKeyParam, c.ApiKey)
uri := GetUri(host, getItemDescription, q.Encode())
req, _ := http.NewRequest("GET", uri, nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return descResultToImgs(body)
}
func (c *DetailClient) GetDetail(item model.Item) (*model.DetailItem, error) {
id := item.Id
descImgs, err := c.GetDescImgs(id)
if err != nil {
return nil, err
} else if len(descImgs) == 0 {
return nil, errors.New("desc is empty")
}
q := url.Values{}
q.Add(ItemIdParam, id)
q.Add(InstanceKeyParam, c.ApiKey)
q.Add(ItemParam, ItemParamValue)
uri := GetUri(host, getItemFullInfoWithPromotions, q.Encode())
req, _ := http.NewRequest("GET", uri, nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return resultToDetailItem(item, body, descImgs)
}
func resultToDetailItem(item model.Item, body []byte, descImgs []string) (*model.DetailItem, error) {
r := gjson.ParseBytes(body)
var detailItem model.DetailItem
if r.Get("ErrorCode").String() != "Ok" {
return &detailItem, DetailFail
}
detailItem.Title = item.Title
detailItem.DescImgs = descImgs
detailItem.NumIid = item.Id
detailItem.DetailUrl = item.ProductUrl
detailItem.Options = getOptions(r)
detailItem.Images = getImgs(r)
if detailItem.Options == nil {
return nil, DetailFail
}
return &detailItem, nil
}
func getImgs(r gjson.Result) []string {
return ConvertImgUrls(r.Get("OtapiItemFullInfo." + ImgsPath).Array())
}
func descResultToImgs(json []byte) ([]string, error) {
//jsonStr := strings.Replace(string(json), DescEncodedString, DescDecodedString, -1)
r := gjson.ParseBytes(json)
if r.Get("ErrorCode").String() != "Ok" {
return nil, DescFail
}
desc := r.Get(DescriptionPath).String()
descImgUrls := DescRegex.FindAllString(desc, -1)
imgs := make([]string, 0)
for _, imgUrl := range descImgUrls {
imgTag := `<img src="http://` + imgUrl + `">`
imgs = append(imgs, imgTag)
}
return imgs, nil
}
func getOptions(r gjson.Result) []model.Option {
f := r.Get(FullInfoPath)
optionMap := make(map[string]*model.Option)
combinedMap := make(map[string][]string)
priceMap := make(map[string]float64)
f.Get(AttributesPath).ForEach(func(key, value gjson.Result) bool {
option := &model.Option{
Name: value.Get(OptionName).String(),
Value: value.Get(OptionValue).String(),
Img: value.Get(OptionImage).String(),
}
optionMap[getOptionPath(value)] = option
return true
})
if len(optionMap) == 0 {
return nil
}
f.Get(CombinationPath).ForEach(func(key, value gjson.Result) bool {
combinationId := value.Get(IdPath).String()
optionPaths := make([]string, 0)
value.Get(Configurators).ForEach(func(key, configurator gjson.Result) bool {
optionPaths = append(optionPaths, getOptionPath(configurator))
return true
})
combinedMap[combinationId] = optionPaths
priceMap[combinationId] = value.Get(PricePath).Float()
return true
})
for _, v := range f.Get(PromotionsPath).Array() {
v.ForEach(func(key, value gjson.Result) bool {
combinationId := value.Get(IdPath).String()
price := value.Get(PricePath).Float()
if val, ok := priceMap[combinationId]; ok && val > price {
priceMap[combinationId] = price
}
return true
})
}
for combinationId, price := range priceMap {
props := combinedMap[combinationId]
for _, optionPath := range props {
var bPrice float64
if val, exists := optionMap[optionPath]; exists {
bPrice = val.Price
} else {
continue
}
if bPrice == 0 {
optionMap[optionPath].Price = price
} else {
optionMap[optionPath].Price = math.Min(bPrice, price)
}
}
}
options := make([]model.Option, 0)
for _, v := range optionMap {
if v.Price != 0 {
options = append(options, *v)
}
}
return options
}
func getOptionPath(value gjson.Result) string {
return value.Get("Pid").String() + ":" + value.Get("Vid").String()
}