-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
resolver.go
62 lines (50 loc) · 1.48 KB
/
resolver.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
package peer
import (
"context"
"golang.org/x/xerrors"
"github.com/gotd/td/tg"
)
// Resolver is a abstraction to resolve domains and Telegram deeplinks.
type Resolver interface {
ResolveDomain(ctx context.Context, domain string) (tg.InputPeerClass, error)
ResolvePhone(ctx context.Context, phone string) (tg.InputPeerClass, error)
}
// DefaultResolver creates and returns default resolver.
func DefaultResolver(raw *tg.Client) Resolver {
return NewLRUResolver(SingleflightResolver(Plain(raw)), 10)
}
// Plain creates plain resolver.
func Plain(raw *tg.Client) Resolver {
return plainResolver{raw: raw}
}
type plainResolver struct {
raw *tg.Client
}
func (p plainResolver) ResolveDomain(ctx context.Context, domain string) (tg.InputPeerClass, error) {
peer, err := p.raw.ContactsResolveUsername(ctx, domain)
if err != nil {
return nil, xerrors.Errorf("resolve: %w", err)
}
return EntitiesFromResult(peer).ExtractPeer(peer.Peer)
}
func (p plainResolver) ResolvePhone(ctx context.Context, phone string) (tg.InputPeerClass, error) {
r, err := p.raw.ContactsGetContacts(ctx, 0)
if err != nil {
return nil, xerrors.Errorf("get contacts: %w", err)
}
switch c := r.(type) {
case *tg.ContactsContacts:
for _, u := range c.Users {
user, ok := u.AsNotEmpty()
if !ok {
continue
}
if user.Phone == phone {
return user.AsInputPeer(), nil
}
}
return nil, xerrors.Errorf("can't resolve phone %q", phone)
default:
return nil, xerrors.Errorf("unexpected type %T", r)
}
}