/** * @Author: jager * @Email: lhj168os@gmail.com * @File: user * @Date: 2021/12/20 4:54 下午 * @package: user * @Version: v1.0.0 * * @Description: * */ package user import ( "github.com/jageros/hawox/attribute" "sync" "time" ) type User struct { attr *attribute.AttrMgr mx sync.RWMutex } func newUser(openId string) (*User, error) { u := &User{ attr: attribute.NewAttrMgr("user", openId), } err := u.attr.Load(true) if err == attribute.NotExistsErr { u.attr.SetInt64("create_time", time.Now().Unix()) err = u.attr.Save(false) } return u, err } func (u *User) OpenID() string { return u.attr.GetAttrID().(string) } func (u *User) Stop() { u.mx.Lock() u.attr.SetBool("stop", true) u.mx.Unlock() } func (u *User) Start() { u.mx.Lock() u.attr.SetBool("stop", false) u.mx.Unlock() } func (u *User) IsStop() bool { u.mx.RLock() stop := u.attr.GetBool("stop") u.mx.RUnlock() return stop } func (u *User) Codes(isFund bool) []string { u.mx.RLock() defer u.mx.RUnlock() key := "stock" if isFund { key = "fund" } attr := u.attr.GetMapAttr(key) if attr == nil { return nil } var codes []string attr.ForEachKey(func(key string) bool { sAttr := attr.GetMapAttr(key) if sAttr.GetBool("notify") { codes = append(codes, key) } return true }) return codes } // HasSubscribed 查询用户是否订阅此票 func (u *User) HasSubscribed(isFund bool, code string) bool { u.mx.RLock() defer u.mx.RUnlock() key := "stock" if isFund { key = "fund" } attr := u.attr.GetMapAttr(key) if attr == nil { return false } sAttr := attr.GetMapAttr(code) if sAttr == nil { return false } return sAttr.GetBool("notify") } // Subscribe 订阅股票或基金 func (u *User) Subscribe(isFund bool, codes ...string) { u.mx.Lock() defer u.mx.Unlock() key := "stock" if isFund { key = "fund" } attr := u.attr.GetMapAttr(key) if attr == nil { attr = attribute.NewMapAttr() u.attr.SetMapAttr(key, attr) } for _, code := range codes { sAttr := attr.GetMapAttr(code) if sAttr == nil { sAttr = attribute.NewMapAttr() attr.SetMapAttr(code, sAttr) } sAttr.SetBool("notify", true) } } // UnSubscribe 取消订阅股票或基金 func (u *User) UnSubscribe(isFund bool, codes ...string) { u.mx.Lock() defer u.mx.Unlock() key := "stock" if isFund { key = "fund" } attr := u.attr.GetMapAttr(key) if attr == nil { return } for _, code := range codes { sAttr := attr.GetMapAttr(code) if sAttr == nil { return } sAttr.SetBool("notify", false) } }