forked from iyear/tdl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peers.go
91 lines (74 loc) · 2 KB
/
peers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package storage
import (
"context"
"encoding/json"
"github.com/gotd/td/telegram/peers"
"github.com/Mistolotus/tdl/pkg/key"
"github.com/Mistolotus/tdl/pkg/kv"
"strconv"
)
type Peers struct {
kv kv.KV
}
func NewPeers(kv kv.KV) peers.Storage {
return &Peers{kv: kv}
}
func (p *Peers) Save(_ context.Context, _key peers.Key, value peers.Value) error {
bytes, err := json.Marshal(value)
if err != nil {
return err
}
return p.kv.Set(key.PeersKey(_key), bytes)
}
func (p *Peers) Find(_ context.Context, _key peers.Key) (peers.Value, bool, error) {
data, err := p.kv.Get(key.PeersKey(_key))
if err != nil {
if err == kv.ErrNotFound {
return peers.Value{}, false, nil
}
return peers.Value{}, false, err
}
var value peers.Value
if err = json.Unmarshal(data, &value); err != nil {
return peers.Value{}, false, err
}
return value, true, nil
}
func (p *Peers) SavePhone(_ context.Context, phone string, _key peers.Key) error {
bytes, err := json.Marshal(_key)
if err != nil {
return err
}
return p.kv.Set(key.PeersPhone(phone), bytes)
}
func (p *Peers) FindPhone(ctx context.Context, phone string) (peers.Key, peers.Value, bool, error) {
data, err := p.kv.Get(key.PeersPhone(phone))
if err != nil {
if err == kv.ErrNotFound {
return peers.Key{}, peers.Value{}, false, nil
}
return peers.Key{}, peers.Value{}, false, err
}
var _key peers.Key
if err = json.Unmarshal(data, &_key); err != nil {
return peers.Key{}, peers.Value{}, false, err
}
value, found, err := p.Find(ctx, _key)
if err != nil {
return peers.Key{}, peers.Value{}, false, err
}
return _key, value, found, nil
}
func (p *Peers) GetContactsHash(_ context.Context) (int64, error) {
data, err := p.kv.Get(key.PeersContactsHash())
if err != nil {
if err == kv.ErrNotFound {
return 0, nil
}
return 0, err
}
return strconv.ParseInt(string(data), 10, 64)
}
func (p *Peers) SaveContactsHash(_ context.Context, hash int64) error {
return p.kv.Set(key.PeersContactsHash(), []byte(strconv.FormatInt(hash, 10)))
}