aboutsummaryrefslogtreecommitdiff
path: root/telegram/connect.go
blob: c30f9a0ef731d97fc90229a1fd5515be134dd82e (plain) (blame)
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
package telegram

import (
	"github.com/pkg/errors"

	log "github.com/sirupsen/logrus"
	"github.com/zelenin/go-tdlib/client"
)

// Connect starts TDlib connection
func (c *Client) Connect() error {
	if c.online {
		return nil
	}

	log.Warn("Connecting to Telegram network...")

	authorizer := client.ClientAuthorizer()
	go func() {
		for {
			state, ok := <-authorizer.State
			if !ok {
				return
			}

			ok = authorizationStateHandler(state)
			if !ok {
				return
			}
		}
	}()

	authorizer.TdlibParameters <- c.parameters

	tdlibClient, err := client.NewClient(authorizer, c.logVerbosity)
	if err != nil {
		return errors.Wrap(err, "Coudn't initialize a Telegram client instance")
	}

	c.client = tdlibClient
	c.online = true

	go updateHandler(c.client)

	return nil
}

// Disconnect drops TDlib connection
func (c *Client) Disconnect() {
	if !c.online {
		return
	}

	log.Warn("Disconnecting from Telegram network...")

	// TODO: send unavailable presence to cached chats

	c.client.Stop()
	c.online = false
}

func authorizationStateHandler(state client.AuthorizationState) bool {
	switch state.AuthorizationStateType() {
	// TODO
	}

	return true
}