-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
session.go
125 lines (104 loc) · 2.49 KB
/
session.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package telegram
import (
"context"
"fmt"
"github.com/go-faster/errors"
"go.uber.org/zap"
"github.com/gotd/td/crypto"
"github.com/gotd/td/mtproto"
"github.com/gotd/td/pool"
"github.com/gotd/td/session"
"github.com/gotd/td/tg"
)
func (c *Client) restoreConnection(ctx context.Context) error {
if c.storage == nil {
return nil
}
data, err := c.storage.Load(ctx)
if errors.Is(err, session.ErrNotFound) {
return nil
}
if err != nil {
return errors.Wrap(err, "load")
}
// If file does not contain DC ID, so we use DC from options.
prev := c.session.Load()
if data.DC == 0 {
data.DC = prev.DC
}
// Restoring persisted auth key.
var key crypto.AuthKey
copy(key.Value[:], data.AuthKey)
copy(key.ID[:], data.AuthKeyID)
if key.Value.ID() != key.ID {
return errors.New("corrupted key")
}
// Re-initializing connection from persisted state.
c.log.Info("Connection restored from state",
zap.String("addr", data.Addr),
zap.String("key_id", fmt.Sprintf("%x", data.AuthKeyID)),
)
c.connMux.Lock()
c.session.Store(pool.Session{
DC: data.DC,
AuthKey: key,
Salt: data.Salt,
})
c.conn = c.createPrimaryConn(nil)
c.connMux.Unlock()
return nil
}
func (c *Client) saveSession(cfg tg.Config, s mtproto.Session) error {
if c.storage == nil {
return nil
}
data, err := c.storage.Load(c.ctx)
if errors.Is(err, session.ErrNotFound) {
// Initializing new state.
err = nil
data = &session.Data{}
}
if err != nil {
return errors.Wrap(err, "load")
}
// Updating previous data.
data.Config = session.ConfigFromTG(cfg)
data.AuthKey = s.Key.Value[:]
data.AuthKeyID = s.Key.ID[:]
data.DC = cfg.ThisDC
data.Salt = s.Salt
if err := c.storage.Save(c.ctx, data); err != nil {
return errors.Wrap(err, "save")
}
c.log.Debug("Data saved",
zap.String("key_id", fmt.Sprintf("%x", data.AuthKeyID)),
)
return nil
}
func (c *Client) onSession(cfg tg.Config, s mtproto.Session) error {
c.sessionsMux.Lock()
c.sessions[cfg.ThisDC] = pool.NewSyncSession(pool.Session{
DC: cfg.ThisDC,
Salt: s.Salt,
AuthKey: s.Key,
})
c.sessionsMux.Unlock()
primaryDC := c.session.Load().DC
// Do not save session for non-primary DC.
if cfg.ThisDC != 0 && primaryDC != 0 && primaryDC != cfg.ThisDC {
return nil
}
c.connMux.Lock()
c.session.Store(pool.Session{
DC: cfg.ThisDC,
Salt: s.Salt,
AuthKey: s.Key,
})
c.cfg.Store(cfg)
c.onReady()
c.connMux.Unlock()
if err := c.saveSession(cfg, s); err != nil {
return errors.Wrap(err, "save")
}
return nil
}