2022-10-20 23:07:04 -04:00
|
|
|
package iprecoder
|
2022-11-01 22:26:04 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
2023-07-29 07:27:15 -04:00
|
|
|
|
|
|
|
"github.com/InazumaV/V2bX/conf"
|
|
|
|
"github.com/InazumaV/V2bX/limiter"
|
|
|
|
"github.com/go-redis/redis/v8"
|
2022-11-01 22:26:04 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Redis struct {
|
|
|
|
*conf.RedisConfig
|
|
|
|
client *redis.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRedis(c *conf.RedisConfig) *Redis {
|
|
|
|
return &Redis{
|
|
|
|
RedisConfig: c,
|
|
|
|
client: redis.NewClient(&redis.Options{
|
|
|
|
Addr: c.Address,
|
|
|
|
Password: c.Password,
|
|
|
|
DB: c.Db,
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-15 21:15:29 -04:00
|
|
|
func (r *Redis) SyncOnlineIp(Ips []limiter.UserIpList) ([]limiter.UserIpList, error) {
|
2022-11-01 22:26:04 -04:00
|
|
|
ctx := context.Background()
|
|
|
|
for i := range Ips {
|
2022-11-02 02:54:24 -04:00
|
|
|
err := r.client.SAdd(ctx, "UserList", Ips[i].Uid).Err()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("add user failed: %s", err)
|
2022-11-01 22:26:04 -04:00
|
|
|
}
|
2022-11-17 21:18:26 -05:00
|
|
|
r.client.Expire(ctx, "UserList", time.Second*time.Duration(r.Expiry))
|
2022-11-01 22:26:04 -04:00
|
|
|
for _, ip := range Ips[i].IpList {
|
|
|
|
err := r.client.SAdd(ctx, strconv.Itoa(Ips[i].Uid), ip).Err()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("add ip failed: %s", err)
|
|
|
|
}
|
2022-11-17 21:18:26 -05:00
|
|
|
r.client.Expire(ctx, strconv.Itoa(Ips[i].Uid), time.Second*time.Duration(r.Expiry))
|
2022-11-01 22:26:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
c := r.client.SMembers(ctx, "UserList")
|
|
|
|
if c.Err() != nil {
|
|
|
|
return nil, fmt.Errorf("get user list failed: %s", c.Err())
|
|
|
|
}
|
2023-05-15 21:15:29 -04:00
|
|
|
Ips = make([]limiter.UserIpList, 0, len(c.Val()))
|
2022-11-01 22:26:04 -04:00
|
|
|
for _, uid := range c.Val() {
|
|
|
|
uidInt, err := strconv.Atoi(uid)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("convert uid failed: %s", err)
|
|
|
|
}
|
|
|
|
ips := r.client.SMembers(ctx, uid)
|
|
|
|
if ips.Err() != nil {
|
|
|
|
return nil, fmt.Errorf("get ip list failed: %s", ips.Err())
|
|
|
|
}
|
2023-05-15 21:15:29 -04:00
|
|
|
Ips = append(Ips, limiter.UserIpList{
|
2022-11-01 22:26:04 -04:00
|
|
|
Uid: uidInt,
|
|
|
|
IpList: ips.Val(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return Ips, nil
|
|
|
|
}
|