-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
318 lines (257 loc) · 9.28 KB
/
client.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
package go_stockx_client
import (
"encoding/json"
"fmt"
"github.com/bogdanfinn/tls-client/profiles"
"io/ioutil"
"sort"
"strconv"
"strings"
"sync"
http "github.com/bogdanfinn/fhttp"
"github.com/bogdanfinn/fhttp/cookiejar"
tls_client "github.com/bogdanfinn/tls-client"
)
const stockxBaseUrl = "https://stockx.com/"
const stockxSearchEndpointTemplate = "https://stockx.com/api/browse?_search=%s&page=1&resultsPerPage=%d&dataType=product&facetsToRetrieve[]=browseVerticals&propsToRetrieve[][]=brand&propsToRetrieve[][]=colorway&propsToRetrieve[][]=media.thumbUrl&propsToRetrieve[][]=title&propsToRetrieve[][]=productCategory&propsToRetrieve[][]=shortDescription&propsToRetrieve[][]=urlKey"
const stockxProductDetailsEndpointTemplate = "https://stockx.com/api/products/%s?includes=market¤cy=%s&country=%s&market=%s"
var stockxHeader = http.Header{
"accept": {"application/json"},
"accept-language": {"de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7"},
"app-platform": {"Iron"},
"app-version": {"2022.07.17.01"},
"cache-control": {"no-cache"},
"pragma": {"no-cache"},
"referer": {"https://stockx.com/de-de"},
"sec-ch-ua": {`".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"`},
"sec-ch-ua-mobile": {"?0"},
"sec-ch-ua-platform": {`"macOS"`},
"sec-fetch-dest": {"empty"},
"sec-fetch-mode": {"cors"},
"sec-fetch-site": {"same-origin"},
"user-agent": {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"},
"x-requested-with": {"XMLHttpRequest"},
http.HeaderOrderKey: {
"accept",
"accept-language",
"app-platform",
"app-version",
"cache-control",
"pragma",
"referer",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"sec-fetch-dest",
"sec-fetch-mode",
"sec-fetch-site",
"user-agent",
"x-requested-with",
},
}
type Client interface {
SearchProducts(query string, limit int) ([]SearchResultProduct, error)
GetProduct(productIdentifier string) (*ProductDetails, error)
SetProxy(proxyUrl string) error
GetProxy() string
}
type client struct {
initialized bool
logger Logger
currency string
locale string
httpClient tls_client.HttpClient
vatAccount bool
}
var clientContainer = struct {
sync.Mutex
instance Client
}{}
func ProvideClient(currency string, locale string, logger Logger, vatAccount bool) (Client, error) {
clientContainer.Lock()
defer clientContainer.Unlock()
if clientContainer.instance != nil {
return clientContainer.instance, nil
}
instance, err := NewClient(currency, locale, logger, vatAccount)
if err != nil {
return nil, err
}
clientContainer.instance = instance
return clientContainer.instance, nil
}
func NewClient(currency string, locale string, logger Logger, vatAccount bool) (Client, error) {
jar, _ := cookiejar.New(nil)
options := []tls_client.HttpClientOption{
tls_client.WithTimeoutSeconds(30),
tls_client.WithClientProfile(profiles.Chrome_117),
tls_client.WithCookieJar(jar),
// tls_client.WithNotFollowRedirects(),
}
httpClient, err := tls_client.NewHttpClient(logger, options...)
if err != nil {
return nil, fmt.Errorf("failed to construct http client: %w", err)
}
return &client{
initialized: false,
logger: logger,
currency: strings.ToUpper(currency),
locale: strings.ToUpper(locale),
httpClient: httpClient,
vatAccount: vatAccount,
}, nil
}
func (c *client) initialize() error {
if c.initialized {
return nil
}
statusCode, _, err := c.doRequest(stockxBaseUrl, stockxHeader)
if err != nil {
return fmt.Errorf("failed to initialize client: %w", err)
}
if statusCode == http.StatusOK {
c.initialized = true
return nil
}
return fmt.Errorf("received wrong status code during client initialization: %d", statusCode)
}
func (c *client) SetProxy(proxyUrl string) error {
return c.httpClient.SetProxy(proxyUrl)
}
func (c *client) GetProxy() string {
return c.httpClient.GetProxy()
}
func (c *client) SearchProducts(query string, limit int) ([]SearchResultProduct, error) {
err := c.initialize()
if err != nil {
return nil, fmt.Errorf("failed to initialize client: %w", err)
}
preparedQuery := query
if !strings.Contains(query, "+") && strings.Contains(query, " ") {
queryParts := strings.Split(query, " ")
preparedQuery = strings.Join(queryParts, "+")
}
searchUrl := fmt.Sprintf(stockxSearchEndpointTemplate, preparedQuery, limit)
_, respBodyBytes, err := c.doRequest(searchUrl, stockxHeader)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
response := ProductSearchResultResponse{}
err = json.Unmarshal(respBodyBytes, &response)
if err != nil {
return nil, fmt.Errorf("failed to convert response json into response struct: %w", err)
}
searchResultProducts := parseSearchResults(response)
return searchResultProducts, nil
}
func (c *client) GetProduct(productIdentifier string) (*ProductDetails, error) {
err := c.initialize()
if err != nil {
return nil, fmt.Errorf("failed to initialize client: %w", err)
}
productUrl := fmt.Sprintf(stockxProductDetailsEndpointTemplate, productIdentifier, c.currency, c.locale, c.locale)
if c.vatAccount {
productUrl = fmt.Sprintf(stockxProductDetailsEndpointTemplate, productIdentifier, c.currency, c.locale, fmt.Sprintf("%s.vat-registered", c.locale))
}
statusCode, respBodyBytes, err := c.doRequest(productUrl, stockxHeader)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if statusCode != http.StatusOK {
return nil, fmt.Errorf("received wrong status code during product details request: %d", statusCode)
}
response := ProductResponse{}
err = json.Unmarshal(respBodyBytes, &response)
if err != nil {
return nil, fmt.Errorf("failed to convert response json into response struct: %w", err)
}
product := parseProduct(response)
return product, nil
}
func (c *client) doRequest(url string, header http.Header) (int, []byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return 0, nil, fmt.Errorf("failed to create stockx search request: %w", err)
}
req.Header = header
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, nil, fmt.Errorf("failed to search for stockx products: %w", err)
}
c.logger.Info("stockx api (%s) response status code: %d", url, resp.StatusCode)
defer resp.Body.Close()
respBodyBytes, err := ioutil.ReadAll(resp.Body)
c.logger.Debug("stockx api (%s) response body: %s", url, string(respBodyBytes))
return resp.StatusCode, respBodyBytes, err
}
func parseSearchResults(response ProductSearchResultResponse) []SearchResultProduct {
var searchResultProducts []SearchResultProduct
for _, responseProduct := range response.Products {
searchResultProducts = append(searchResultProducts, SearchResultProduct{
Brand: responseProduct.Brand,
Colorway: responseProduct.Colorway,
ImageUrl: responseProduct.Media.Thumburl,
Category: responseProduct.Productcategory,
Description: responseProduct.Shortdescription,
Title: responseProduct.Title,
ProductIdentifier: responseProduct.Urlkey,
})
}
return searchResultProducts
}
func parseProduct(response ProductResponse) *ProductDetails {
var variants []ProductDetailsVariant
product := response.Product
for key, responseVariant := range product.Children {
if responseVariant.Market.Lastsalesize == "" {
continue
}
variants = append(variants, ProductDetailsVariant{
UUID: key,
Size: responseVariant.Market.Lastsalesize,
Lowestask: responseVariant.Market.Lowestask,
Highestbid: responseVariant.Market.Highestbid,
Annualhigh: responseVariant.Market.Annualhigh,
Annuallow: responseVariant.Market.Annuallow,
Lastsale: responseVariant.Market.Lastsale,
Saleslast72Hours: responseVariant.Market.Saleslast72Hours,
Lastsaledate: responseVariant.Market.Lastsaledate,
Lowestaskfloat: responseVariant.Market.Lowestaskfloat,
Highestbidfloat: responseVariant.Market.Highestbidfloat,
})
}
sort.Slice(variants, func(i, j int) bool {
sizeA, errA := strconv.ParseFloat(variants[i].Size, 32)
sizeB, errB := strconv.ParseFloat(variants[j].Size, 32)
if errA != nil || errB != nil {
return false
}
return sizeA < sizeB
})
return &ProductDetails{
ID: product.ID,
UUID: product.UUID,
Brand: product.Brand,
Colorway: product.Colorway,
Minimumbid: product.Minimumbid,
Name: product.Name,
Releasedate: product.Releasedate,
Retailprice: product.Retailprice,
Shoe: product.Shoe,
Shortdescription: product.Shortdescription,
Styleid: product.Styleid,
Title: product.Title,
SizeLocale: product.Sizelocale,
SizeTitle: product.Sizetitle,
ProductIdentifier: product.Urlkey,
Description: product.Description,
Imageurl: product.Media.Imageurl,
Smallimageurl: product.Media.Smallimageurl,
Thumburl: product.Media.Thumburl,
Lowestaskfloat: product.Market.Lowestaskfloat,
Lowestask: product.Market.Lowestask,
Highestbid: product.Market.Highestbid,
Highestbidfloat: product.Market.Highestbidfloat,
Variants: variants,
}
}