mirror of
https://github.com/elyby/chrly.git
synced 2024-12-24 05:59:54 +05:30
92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package data
|
||
|
||
import (
|
||
"log"
|
||
"encoding/json"
|
||
|
||
"elyby/minecraft-skinsystem/lib/services"
|
||
"elyby/minecraft-skinsystem/lib/tools"
|
||
|
||
"github.com/mediocregopher/radix.v2/redis"
|
||
)
|
||
|
||
type SkinItem struct {
|
||
UserId int `json:"userId"`
|
||
Username string `json:"username"`
|
||
SkinId int `json:"skinId"`
|
||
Url string `json:"url"`
|
||
Is1_8 bool `json:"is1_8"`
|
||
IsSlim bool `json:"isSlim"`
|
||
Hash string `json:"hash"`
|
||
oldUsername string
|
||
}
|
||
|
||
const accountIdToUsernameKey string = "hash:username-to-account-id"
|
||
|
||
func (s *SkinItem) Save() {
|
||
str, _ := json.Marshal(s)
|
||
pool, _ := services.RedisPool.Get()
|
||
pool.Cmd("MULTI")
|
||
|
||
// Если пользователь сменил ник, то мы должны удать его ключ
|
||
if (s.oldUsername != "" && s.oldUsername != s.Username) {
|
||
pool.Cmd("DEL", tools.BuildKey(s.oldUsername))
|
||
}
|
||
|
||
// Если это новая запись или если пользователь сменил ник, то обновляем значение в хэш-таблице
|
||
if (s.oldUsername != "" || s.oldUsername != s.Username) {
|
||
pool.Cmd("HSET", accountIdToUsernameKey, s.UserId, s.Username)
|
||
}
|
||
|
||
pool.Cmd("SET", tools.BuildKey(s.Username), str)
|
||
|
||
pool.Cmd("EXEC")
|
||
|
||
s.oldUsername = s.Username
|
||
}
|
||
|
||
func (s *SkinItem) Delete() {
|
||
if (s.oldUsername == "") {
|
||
return;
|
||
}
|
||
|
||
pool, _ := services.RedisPool.Get()
|
||
pool.Cmd("MULTI")
|
||
|
||
pool.Cmd("DEL", tools.BuildKey(s.oldUsername))
|
||
pool.Cmd("HDEL", accountIdToUsernameKey, s.UserId)
|
||
|
||
pool.Cmd("EXEC")
|
||
}
|
||
|
||
func FindByUsername(username string) (SkinItem, error) {
|
||
var record SkinItem;
|
||
response := services.RedisPool.Cmd("GET", tools.BuildKey(username));
|
||
if (response.IsType(redis.Nil)) {
|
||
return record, DataNotFound{username}
|
||
}
|
||
|
||
result, err := response.Str()
|
||
if (err == nil) {
|
||
decodeErr := json.Unmarshal([]byte(result), &record)
|
||
if (decodeErr != nil) {
|
||
log.Println("Cannot decode record data")
|
||
}
|
||
|
||
record.oldUsername = record.Username
|
||
}
|
||
|
||
return record, err
|
||
}
|
||
|
||
func FindById(id int) (SkinItem, error) {
|
||
response := services.RedisPool.Cmd("HGET", accountIdToUsernameKey, id);
|
||
if (response.IsType(redis.Nil)) {
|
||
return SkinItem{}, DataNotFound{"unknown"}
|
||
}
|
||
|
||
username, _ := response.Str()
|
||
|
||
return FindByUsername(username)
|
||
}
|