aboutsummaryrefslogtreecommitdiff
path: root/telegram/client.go
blob: 833d883581d22c0a3aafe9d2441b704e113e5342 (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
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
package telegram

import (
	"fmt"
	"github.com/pkg/errors"
	"path/filepath"
	"strconv"

	"dev.narayana.im/narayana/telegabber/config"
	"dev.narayana.im/narayana/telegabber/persistence"

	"github.com/zelenin/go-tdlib/client"
)

var logConstants = map[string]int32{
	":fatal":   0,
	":error":   1,
	":warn":    2,
	":info":    3,
	":debug":   4,
	":verbose": 5,
	":all":     1023,
}

func stringToLogConstant(c string) int32 {
	level, ok := logConstants[c]
	if !ok {
		level = 0
	}

	return level
}

// Client stores the metadata for lazily invoked TDlib instance
type Client struct {
	client       *client.Client
	jid          string
	parameters   *client.TdlibParameters
	Session      *persistence.Session
	online       bool
	logVerbosity client.Option
}

// NewClient instantiates a Telegram App
func NewClient(conf config.TelegramConfig, jid string, session *persistence.Session) (Client, error) {
	logVerbosity := client.WithLogVerbosity(&client.SetLogVerbosityLevelRequest{
		NewVerbosityLevel: stringToLogConstant(conf.Loglevel),
	})

	apiID, err := strconv.Atoi(conf.Tdlib.Client.APIID)
	if err != nil {
		return Client{}, errors.Wrap(err, "Wrong api_id")
	}

	parameters := client.TdlibParameters{
		UseTestDc: false,

		DatabaseDirectory: filepath.Join("./sessions/", jid),
		FilesDirectory:    filepath.Join("./sessions/", jid, "/files/"),

		UseFileDatabase:     true,
		UseChatInfoDatabase: conf.Tdlib.Client.UseChatInfoDatabase,
		UseMessageDatabase:  true,
		UseSecretChats:      conf.Tdlib.Client.UseSecretChats,

		ApiId:   int32(apiID),
		ApiHash: conf.Tdlib.Client.APIHash,

		SystemLanguageCode: "en",
		DeviceModel:        conf.Tdlib.Client.DeviceModel,
		SystemVersion:      "1.0.0",
		ApplicationVersion: conf.Tdlib.Client.ApplicationVersion,

		EnableStorageOptimizer: true,
		IgnoreFileNames:        false,
	}

	return Client{
		parameters:   &parameters,
		jid:          jid,
		Session:      session,
		logVerbosity: logVerbosity,
	}, nil
}

func updateHandler(tdlibClient *client.Client) {
	listener := tdlibClient.GetListener()
	defer listener.Close()

	for update := range listener.Updates {
		if update.GetClass() == client.ClassUpdate {
			fmt.Printf("%#v", update)
		}
	}
}