2023-09-20 03:20:44 +08:00
|
|
|
package kv
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2024-06-04 13:36:04 +08:00
|
|
|
"sync"
|
2023-09-20 03:20:44 +08:00
|
|
|
|
|
|
|
"github.com/gotd/td/telegram"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Session struct {
|
|
|
|
kv KV
|
|
|
|
key string
|
2024-06-04 13:36:04 +08:00
|
|
|
mu sync.Mutex
|
2023-09-20 03:20:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewSession(kv KV, key string) telegram.SessionStorage {
|
|
|
|
return &Session{kv: kv, key: key}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) LoadSession(_ context.Context) ([]byte, error) {
|
2024-06-04 13:36:04 +08:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2023-09-20 03:20:44 +08:00
|
|
|
|
|
|
|
b, err := s.kv.Get(s.key)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, ErrNotFound) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-06-06 02:49:30 +08:00
|
|
|
data := make([]byte, len(b))
|
|
|
|
copy(data, b)
|
|
|
|
return data, nil
|
2023-09-20 03:20:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) StoreSession(_ context.Context, data []byte) error {
|
2024-06-04 13:36:04 +08:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2023-09-20 03:20:44 +08:00
|
|
|
return s.kv.Set(s.key, data)
|
|
|
|
}
|