You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
1.4 KiB
Go

3 years ago
/**
* @Author: jager
* @Email: lhj168os@gmail.com
* @File: cache
* @Date: 2021/12/20 6:39
* @package: user
* @Version: v1.0.0
*
* @Description:
*
*/
package user
import (
"github.com/jageros/hawox/attribute"
3 years ago
"github.com/jageros/hawox/logx"
3 years ago
"sync"
)
3 years ago
var (
users = map[string]*User{}
mx sync.RWMutex
)
3 years ago
func LoadAllUserIntoCache() error {
attrs, err := attribute.LoadAll("user")
if err != nil {
return err
}
3 years ago
mx.Lock()
3 years ago
for _, attr := range attrs {
u := &User{attr: attr}
3 years ago
users[u.OpenID()] = u
3 years ago
}
3 years ago
mx.Unlock()
3 years ago
return nil
}
3 years ago
func SaveAll() {
mx.Lock()
defer mx.Unlock()
for _, u := range users {
err := u.attr.Save(true)
if err != nil {
logx.Error(err)
}
}
}
3 years ago
func GetUser(openId string) (*User, error) {
3 years ago
mx.RLock()
u, ok := users[openId]
mx.RUnlock()
3 years ago
if ok {
3 years ago
return u, nil
3 years ago
}
us, err := newUser(openId)
if err != nil {
return nil, err
}
3 years ago
mx.Lock()
users[openId] = us
mx.Unlock()
3 years ago
return us, nil
}
3 years ago
3 years ago
func ForEachUser(f func(u *User) bool) {
3 years ago
mx.Lock()
defer mx.Unlock()
for _, u := range users {
if !f(u) {
break
}
}
}
func Codes(isFund bool) []string {
var codes = map[string]struct{}{}
3 years ago
ForEachUser(func(u *User) bool {
if u.IsStop() {
return true
}
3 years ago
cds := u.Codes(isFund)
for _, cd := range cds {
if _, ok := codes[cd]; ok {
continue
}
codes[cd] = struct{}{}
}
return true
})
var cods []string
for code := range codes {
cods = append(cods, code)
}
return cods
}