-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
builder.go
174 lines (148 loc) · 4.17 KB
/
builder.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package telegram
import (
"context"
"io"
"os"
"path/filepath"
"strconv"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/go-faster/errors"
"go.uber.org/zap"
"golang.org/x/net/proxy"
"github.com/gotd/td/clock"
"github.com/gotd/td/internal/crypto"
"github.com/gotd/td/session"
"github.com/gotd/td/telegram/auth"
"github.com/gotd/td/telegram/dcs"
"github.com/gotd/td/tgerr"
)
func sessionDir() (string, error) {
dir, ok := os.LookupEnv("SESSION_DIR")
if ok {
return filepath.Abs(dir)
}
dir, err := os.UserHomeDir()
if err != nil {
dir = "."
}
return filepath.Abs(filepath.Join(dir, ".td"))
}
// OptionsFromEnvironment fills unfilled field in opts parameter
// using environment variables.
//
// Variables:
//
// SESSION_FILE: path to session file
// SESSION_DIR: path to session directory, if SESSION_FILE is not set
// ALL_PROXY, NO_PROXY: see https://pkg.go.dev/golang.org/x/net/proxy#FromEnvironment
func OptionsFromEnvironment(opts Options) (Options, error) {
// Setting up session storage if not provided.
if opts.SessionStorage == nil {
sessionFile, ok := os.LookupEnv("SESSION_FILE")
if !ok {
dir, err := sessionDir()
if err != nil {
return Options{}, errors.Wrap(err, "SESSION_DIR not set or invalid")
}
sessionFile = filepath.Join(dir, "session.json")
}
dir, _ := filepath.Split(sessionFile)
if err := os.MkdirAll(dir, 0700); err != nil {
return Options{}, errors.Wrap(err, "session dir creation")
}
opts.SessionStorage = &session.FileStorage{
Path: sessionFile,
}
}
if opts.Resolver == nil {
opts.Resolver = dcs.Plain(dcs.PlainOptions{
Dial: proxy.Dial,
})
}
return opts, nil
}
// ClientFromEnvironment creates client using OptionsFromEnvironment
// but does not connect to server.
//
// Variables:
//
// APP_ID: app_id of Telegram app.
// APP_HASH: app_hash of Telegram app.
func ClientFromEnvironment(opts Options) (*Client, error) {
appID, err := strconv.Atoi(os.Getenv("APP_ID"))
if err != nil {
return nil, errors.Wrap(err, "APP_ID not set or invalid")
}
appHash := os.Getenv("APP_HASH")
if appHash == "" {
return nil, errors.New("no APP_HASH provided")
}
opts, err = OptionsFromEnvironment(opts)
if err != nil {
return nil, err
}
return NewClient(appID, appHash, opts), nil
}
func retry(ctx context.Context, logger *zap.Logger, cb func(ctx context.Context) error) error {
b := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
// List of known retryable RPC error types.
retryableErrors := []string{
"NEED_MEMBER_INVALID",
"AUTH_KEY_UNREGISTERED",
"API_ID_PUBLISHED_FLOOD",
}
return backoff.Retry(func() error {
if err := cb(ctx); err != nil {
logger.Warn("TestClient run failed", zap.Error(err))
if tgerr.Is(err, retryableErrors...) {
return err
}
if timeout, ok := AsFloodWait(err); ok {
timer := clock.System.Timer(timeout + 1*time.Second)
defer clock.StopTimer(timer)
select {
case <-timer.C():
return err
case <-ctx.Done():
return ctx.Err()
}
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
// Possibly server closed connection.
return err
}
return backoff.Permanent(err)
}
return nil
}, b)
}
// TestClient creates and authenticates user telegram.Client
// using Telegram test server.
func TestClient(ctx context.Context, opts Options, cb func(ctx context.Context, client *Client) error) error {
if opts.DC == 0 {
opts.DC = 2
}
if opts.DCList.Zero() {
opts.DCList = dcs.Test()
}
logger := zap.NewNop()
if opts.Logger != nil {
logger = opts.Logger.Named("test")
}
// Sometimes testing server can return "AUTH_KEY_UNREGISTERED" error.
// It is expected and client implementation is unlikely to cause
// such errors, so just doing retries using backoff.
return retry(ctx, logger, func(retryCtx context.Context) error {
client := NewClient(TestAppID, TestAppHash, opts)
return client.Run(retryCtx, func(runCtx context.Context) error {
if err := client.Auth().IfNecessary(runCtx, auth.NewFlow(
auth.Test(crypto.DefaultRand(), opts.DC),
auth.SendCodeOptions{},
)); err != nil {
return errors.Wrap(err, "auth flow")
}
return cb(runCtx, client)
})
})
}