mtgbot/modules/background/tcgplayer.go
Jay 273278d322 update
1. add cron module
2. add pool module
3. add tcgplayer background job
4. add card price model
2019-01-16 16:53:08 +08:00

109 lines
1.8 KiB
Go

package background
import (
"git.trj.tw/golang/mtgbot/models"
"git.trj.tw/golang/mtgbot/modules/apiact"
"git.trj.tw/golang/mtgbot/modules/pool"
"git.trj.tw/golang/utils"
)
func runMTGPriceJob() {
api, err := apiact.NewTCGApi("v1.19.0")
if err != nil {
return
}
err = api.GetToken()
if err != nil {
return
}
numSets, err := models.CountSets(models.ListSetsOpts{})
if err != nil {
return
}
sets, err := models.ListSets(models.ListSetsOpts{
Limit: numSets,
})
if err != nil {
return
}
_ = sets
pool := pool.NewPool(5)
for _, set := range sets {
pool.Add()
go getPriceFromAPI(pool, api, set.TCGPlayerID)
}
pool.Wait()
}
func getPriceFromAPI(pool *pool.Pool, api *apiact.TCGPlayer, groupid int) {
defer pool.Done()
prices, err := api.ListGroupProductPrice(groupid)
if err != nil {
return
}
ids := make([]int, 0, len(prices))
type cPrice struct {
CardID string
PriceN float32
PriceF float32
}
cardMap := make(map[int]cPrice)
for _, v := range prices {
if utils.SliceIndex(len(ids), func(idx int) bool { return ids[idx] == v.ProductID }) == -1 {
ids = append(ids, v.ProductID)
}
s, ok := cardMap[v.ProductID]
if !ok {
s = cPrice{}
}
if v.SubTypeName == "Normal" {
s.PriceN = v.MidPrice
} else {
s.PriceF = v.MidPrice
}
cardMap[v.ProductID] = s
}
cards, err := models.GetCardByTCGPlayerIDs(ids)
if err != nil {
return
}
for _, v := range cards {
if s, ok := cardMap[v.TCGPlayerID]; ok {
s.CardID = v.ID
cardMap[v.TCGPlayerID] = s
}
}
insOpts := models.InsertCardPriceOpts{}
insOpts.Data = make([]models.CardPrice, 0, len(cardMap))
for _, v := range cardMap {
if len(v.CardID) > 0 {
insOpts.Data = append(insOpts.Data, models.CardPrice{
Card: v.CardID,
PriceN: v.PriceN,
PriceF: v.PriceF,
})
}
}
models.InsertCardPrice(insOpts)
return
}