us-coach-spider/watcher/watchers.go

100 lines
1.9 KiB
Go
Raw Normal View History

2024-11-30 20:26:37 +08:00
package watcher
import (
"slices"
"sync"
"gitea.timerzz.com/kedaya_haitao/common/structs/storage"
v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2"
"github.com/golang/glog"
)
type Watcher struct {
pArticle *v2.ProviderArticle
watching bool //是不是正在抓
}
type Watchers struct {
m sync.RWMutex
list []*Watcher
providerId v2.ProviderId
storage *storage.Storage
ready bool
}
func NewWatchers(storage *storage.Storage, providerId v2.ProviderId) *Watchers {
return &Watchers{
storage: storage,
providerId: providerId,
list: make([]*Watcher, 0),
}
}
func (w *Watchers) Add(article *v2.ProviderArticle) {
w.m.Lock()
defer w.m.Unlock()
if !slices.ContainsFunc(w.list, func(item *Watcher) bool {
return item.pArticle.SkuID == article.SkuID
}) {
w.list = append(w.list, &Watcher{pArticle: article})
}
}
func (w *Watchers) Remove(skuID string) {
for i, item := range w.list {
if item.pArticle.SkuID == skuID {
w.m.Lock()
w.list = append(w.list[:i], w.list[i+1:]...)
w.m.Unlock()
return
}
}
}
func (w *Watchers) Range(filter func(watcher *Watcher) bool, do func(watcher *Watcher)) {
w.m.RLock()
defer w.m.RUnlock()
for _, item := range w.list {
if filter(item) {
do(item)
}
}
}
func (w *Watchers) Exist(skuID string) bool {
w.m.RLock()
defer w.m.RUnlock()
for _, item := range w.list {
if item.pArticle.SkuID == skuID {
return true
}
}
return false
}
func (w *Watchers) Load() (err error) {
var articles []*v2.ProviderArticle
articles, err = w.storage.ProviderArticle().Find(
storage.NewGetProviderArticleQuery().
SetProviderId(w.providerId).
SetWatch(true),
)
if err != nil {
return err
}
w.m.Lock()
defer w.m.Unlock()
for _, article := range articles {
w.list = append(w.list, &Watcher{pArticle: article})
}
glog.Infof("共加载%d个需要蹲货的商品\n", len(w.list))
w.ready = true
return
}
// 返回ready
func (w *Watchers) Ready() bool {
return w.ready
}