common/pkg/coach-client/us.go

273 lines
7.4 KiB
Go
Raw Permalink Normal View History

2024-06-14 15:26:27 +08:00
package coach_client
import (
"context"
"fmt"
2024-07-26 14:59:32 +08:00
"log/slog"
"net/url"
"os"
2024-07-26 14:59:32 +08:00
"time"
2024-06-14 15:26:27 +08:00
"gitea.timerzz.com/kedaya_haitao/common/pkg/proxy"
restry_pool "gitea.timerzz.com/kedaya_haitao/common/pkg/restry-pool"
2024-12-11 13:29:43 +08:00
healthcheck "gitea.timerzz.com/timerzz/proxy-detector/pkg/health-check"
"gitea.timerzz.com/timerzz/proxy-detector/pkg/proxy/structs"
2024-06-14 15:26:27 +08:00
"github.com/go-resty/resty/v2"
"github.com/golang/glog"
2024-06-14 15:26:27 +08:00
"github.com/pkg/errors"
)
2024-12-06 17:07:14 +08:00
const (
BaseUrl_Coach = "https://www.coach.com"
BaseUrl_CoachOutlet = "https://www.coachoutlet.com"
)
const (
USClient_Type_Coach = "coach"
USClient_Type_Coach_Outlet = "coach_outlet"
)
const (
USClient_Type_Env_Key = "COACH_CLIENT_TYPE"
)
func LoadUSClientType() string {
clientType := os.Getenv(USClient_Type_Env_Key)
if clientType == "" {
glog.Fatal("加载coach客户端类型失败")
}
if clientType != USClient_Type_Coach && clientType != USClient_Type_Coach_Outlet {
glog.Fatal("加载coach客户端类型不正确")
}
return clientType
}
2024-12-06 17:07:14 +08:00
type USClientBuilder struct {
2024-12-11 13:29:43 +08:00
pool *proxy.Pool
2024-06-14 15:26:27 +08:00
}
2024-12-11 13:29:43 +08:00
func US(pool *proxy.Pool) *USClientBuilder {
2024-12-06 17:07:14 +08:00
return &USClientBuilder{
pool: pool,
}
}
func (u *USClientBuilder) Coach() USClient {
return &us{
pool: u.pool,
2024-06-14 15:26:27 +08:00
defaultTimeOut: 10 * time.Minute,
2024-12-06 17:07:14 +08:00
baseUrl: BaseUrl_Coach,
2024-06-14 15:26:27 +08:00
}
}
2024-12-06 17:07:14 +08:00
func (u *USClientBuilder) CoachOutlet() USClient {
return &us{
pool: u.pool,
defaultTimeOut: 10 * time.Minute,
baseUrl: BaseUrl_CoachOutlet,
}
}
func (u *USClientBuilder) CreateByType(clientType string) USClient {
if clientType == USClient_Type_Coach {
return u.Coach()
} else if clientType == USClient_Type_Coach_Outlet {
return u.CoachOutlet()
}
return nil
}
2024-12-06 17:07:14 +08:00
type USClient interface {
RequestInventory(ctx context.Context, pid string) (inv Inventory, err error)
RequestProductDetail(ctx context.Context, pid string) (data ProductData, err error)
ViewAllBags(ctx context.Context, page int) (resp PageDataResponse, err error)
BaseUrl() string
2024-12-06 17:07:14 +08:00
}
type us struct {
2024-12-11 13:29:43 +08:00
pool *proxy.Pool
2024-12-06 17:07:14 +08:00
defaultTimeOut time.Duration
baseUrl string
}
2024-12-11 13:29:43 +08:00
func tryRequest(ctx context.Context, base, urlPath string, respData any, proxyGetter func() *structs.Proxy) error {
2024-06-14 15:26:27 +08:00
for p := proxyGetter(); p != nil; p = proxyGetter() {
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Errorf("超时未获取到结果,链接:%s", urlPath)
}
return nil
default:
}
2024-12-06 17:07:14 +08:00
resp, err := callByProxy(ctx, p, base, urlPath, respData)
2024-06-14 15:26:27 +08:00
if err != nil {
slog.Debug(err.Error())
continue
}
2024-07-26 15:22:16 +08:00
if resp.StatusCode() != 200 {
slog.Debug(fmt.Errorf("请求错误:%d, %s", resp.StatusCode(), resp.Body()).Error())
continue
}
2024-06-14 15:26:27 +08:00
return nil
}
return errors.New("未获取到可用的代理")
}
2024-12-11 13:29:43 +08:00
func callByProxy(ctx context.Context, p *structs.Proxy, base, urlPath string, result any) (*resty.Response, error) {
full, _ := url.JoinPath(base, urlPath)
2024-12-11 13:29:43 +08:00
addr, err := healthcheck.UrlToMetadata(full)
2024-06-14 15:26:27 +08:00
if err != nil {
return nil, err
}
subCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
2024-12-11 13:29:43 +08:00
conn, err := p.ClashProxy().DialContext(subCtx, &addr)
2024-06-14 15:26:27 +08:00
if err != nil {
return nil, errors.Wrap(err, "创建conn失败")
}
defer conn.Close()
var cli = restry_pool.GetRestyClient(conn)
defer restry_pool.PutRestyClient(cli)
2024-12-06 17:07:14 +08:00
return cli.SetBaseURL(base).R().SetResult(result).Get(urlPath)
2024-06-14 15:26:27 +08:00
}
type Inventory struct {
Id string `json:"id"`
Ats int `json:"ats"`
PreOrderable bool `json:"preorderable"`
BackOrderable bool `json:"backorderable"`
Orderable bool `json:"orderable"`
AllocationResetDate time.Time `json:"allocationResetDate,omitempty"`
Perpetual bool `json:"perpetual"`
StockLevel int `json:"stockLevel"`
}
type InventoryResponse struct {
Inventory struct {
Status string `json:"status"`
InventoryListID string `json:"inventoryListID"`
InventoryInfo Inventory `json:"inventoryInfo"`
} `json:"inventory"`
}
func (c *us) BaseUrl() string {
return c.baseUrl
}
2024-12-06 17:07:14 +08:00
func (c *us) RequestInventory(ctx context.Context, pid string) (inv Inventory, err error) {
2024-06-14 15:26:27 +08:00
sctx, cancel := context.WithTimeout(ctx, c.defaultTimeOut)
defer cancel()
var resp InventoryResponse
2024-12-06 17:07:14 +08:00
urlPath := fmt.Sprintf("/api/inventory?vgId=%s&includeVariantData=false", url.QueryEscape(pid))
err = tryRequest(sctx, c.baseUrl, urlPath, &resp, c.pool.RandomIterator())
2024-06-14 15:26:27 +08:00
inv = resp.Inventory.InventoryInfo
return
}
type ProductData struct {
2024-11-20 21:14:15 +08:00
Id string `json:"id"`
Name string `json:"name"`
Brand string `json:"brand"`
Inventory Inventory `json:"inventory"`
Url string `json:"url"`
MasterId string `json:"masterId"`
ImageGroups []ImageGroup `json:"imageGroups"`
Prices struct {
2024-06-14 15:26:27 +08:00
CurrentPrice float64 `json:"currentPrice"`
} `json:"prices"`
Remark string `json:"-"`
}
2024-11-20 21:11:19 +08:00
type ImageGroup struct {
Images []struct {
Src string `json:"src"`
Title string `json:"title"`
Alt string `json:"alt"`
} `json:"images"`
ViewType string `json:"viewType"`
}
2024-06-14 15:26:27 +08:00
type ProductDataResponse struct {
ProductData []*ProductData `json:"productsData"`
}
2024-12-06 17:07:14 +08:00
func (c *us) RequestProductDetail(ctx context.Context, pid string) (data ProductData, err error) {
2024-06-14 15:26:27 +08:00
sctx, cancel := context.WithTimeout(ctx, c.defaultTimeOut)
defer cancel()
var resp ProductDataResponse
2024-12-06 17:07:14 +08:00
urlPath := fmt.Sprintf("/api/get-products?ids=%s&includeInventory=false", url.QueryEscape(pid))
err = tryRequest(sctx, c.baseUrl, urlPath, &resp, c.pool.RandomIterator())
2024-06-14 15:26:27 +08:00
if len(resp.ProductData) == 0 && err != nil {
err = fmt.Errorf("获取详情信息为空")
return
}
if len(resp.ProductData) > 0 {
data = *resp.ProductData[0]
}
return
}
type PageDataResponse struct {
PageData struct {
Total int `json:"total"`
Page int `json:"page"`
TotalPages int `json:"totalPages"`
PageSize int `json:"pageSize"`
Products []Product `json:"products"`
} `json:"pageData"`
}
2024-11-20 21:14:15 +08:00
2024-06-14 15:26:27 +08:00
type Product struct {
Name string `json:"name"`
Colors []Color `json:"colors"`
VariantsOnSale []Variant `json:"variantsOnSale"`
}
type Color struct {
Id string `json:"id"` //"id": "IMDQC",
Text string `json:"text"` //颜色的描述
Orderable bool `json:"orderable"`
Media Media `json:"media"`
Url string `json:"url"` //"/products/eliza-flap-crossbody-bag-in-signature-canvas/CP009-IMDQC.html",
VgId string `json:"vgId"` // "vgId": "CP009-IMDQC",
MasterId string `json:"masterId"` //"masterId": "CP009"
}
type Media struct {
Thumbnail Thumbnail `json:"thumbnail"`
}
type Thumbnail struct {
Src string `json:"src"`
}
type Variant struct {
Id string `json:"id"`
OnSale bool `json:"onSale"`
Price Price `json:"price"`
}
type Price struct {
Sales Sales `json:"sales"`
MarkdownDiscPercent int `json:"markdownDiscPercent"`
}
type Sales struct {
Value float64 `json:"value"`
Currency string `json:"currency"`
Formatted string `json:"formatted"`
DecimalPrice string `json:"decimalPrice"`
}
2024-12-06 17:07:14 +08:00
func (c *us) ViewAllBags(ctx context.Context, page int) (resp PageDataResponse, err error) {
2024-06-14 15:26:27 +08:00
if page < 1 {
page = 1
}
sctx, cancel := context.WithTimeout(ctx, c.defaultTimeOut)
defer cancel()
2024-12-06 17:07:14 +08:00
urlPath := fmt.Sprintf("/api/get-shop/bags/view-all?page=%d", page)
err = tryRequest(sctx, c.baseUrl, urlPath, &resp, c.pool.RandomIterator())
2024-06-14 15:26:27 +08:00
return
}