telegabber/telegram/client.go
2019-12-16 03:02:53 +02:00

119 lines
2.6 KiB
Go

package telegram
import (
"github.com/pkg/errors"
"path/filepath"
"strconv"
"sync"
"time"
"dev.narayana.im/narayana/telegabber/config"
"dev.narayana.im/narayana/telegabber/persistence"
"github.com/zelenin/go-tdlib/client"
"gosrc.io/xmpp"
)
var logConstants = map[string]int32{
":fatal": 0,
":error": 1,
":warn": 2,
":info": 3,
":debug": 4,
":verbose": 5,
":all": 1023,
}
type cache struct {
chats map[int64]*client.Chat
users map[int32]*client.User
}
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
authorizer *clientAuthorizer
parameters *client.TdlibParameters
options []client.Option
me *client.User
listener *client.Listener
xmpp *xmpp.Component
jid string
Session *persistence.Session
content *config.TelegramContentConfig
cache *cache
locks clientLocks
}
type clientLocks struct {
authorizationReady sync.WaitGroup
}
// NewClient instantiates a Telegram App
func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component, session *persistence.Session) (*Client, error) {
var options []client.Option
options = append(options, client.WithLogVerbosity(&client.SetLogVerbosityLevelRequest{
NewVerbosityLevel: stringToLogConstant(conf.Loglevel),
}))
if conf.Tdlib.Client.CatchTimeout != 0 {
options = append(options, client.WithCatchTimeout(
time.Duration(conf.Tdlib.Client.CatchTimeout)*time.Second,
))
}
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,
xmpp: component,
jid: jid,
Session: session,
content: &conf.Content,
cache: &cache{
chats: map[int64]*client.Chat{},
users: map[int32]*client.User{},
},
options: options,
locks: clientLocks{},
}, nil
}