added tg methods need todo

This commit is contained in:
Pavel 2024-06-30 21:02:23 +03:00
parent c00899f41a
commit 8b00ad820f
6 changed files with 187 additions and 83 deletions

@ -70,7 +70,6 @@ type Options struct {
TrashLogHost string `env:"TRASH_LOG_HOST" default:"localhost:7113"`
ModuleLogger string `env:"MODULE_LOGGER" default:"core-local"`
ClickHouseCred string `env:"CLICK_HOUSE_CRED" default:"tcp://10.8.0.15:9000/default?sslmode=disable"`
ApiHash string `env:"TG_API_HASH" default:""`
}
func New(ctx context.Context, opts interface{}, ver appInit.Version) (appInit.CommonApp, error) {
@ -154,9 +153,9 @@ func New(ctx context.Context, opts interface{}, ver appInit.Version) (appInit.Co
privilegeController := privilege.NewPrivilege(clientData, fiberClient)
go tools.PublishPrivilege(privilegeController, 10, 5*time.Minute)
_, err = telegram.NewTelegramClient(0, options.ApiHash)
tgClient, err := telegram.NewTelegramClient(ctx, pgdal)
if err != nil {
panic(fmt.Sprintf("Error init tg_client: %v", err))
panic(fmt.Sprintf("failed init tg clietns: %v", err))
}
// todo подумать над реализацией всего а то пока мне кажется что немного каша получается такой предикт что через некоторое время
@ -180,11 +179,12 @@ func New(ctx context.Context, opts interface{}, ver appInit.Version) (appInit.Co
app.Get("/readiness", healthchecks.Readiness(&workerErr)) //todo parametrized readiness. should discuss ready reason
svc := service.New(service.Deps{
Dal: pgdal,
AuthClient: authClient,
Producer: producer,
ServiceName: options.ServiceName,
ChDAL: chDal,
Dal: pgdal,
AuthClient: authClient,
Producer: producer,
ServiceName: options.ServiceName,
ChDAL: chDal,
TelegramClient: tgClient,
})
svc.Register(app)

@ -1,58 +1,57 @@
package telegram
import (
"context"
"fmt"
"github.com/zelenin/go-tdlib/client"
"path/filepath"
"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal"
"penahub.gitlab.yandexcloud.net/backend/tdlib/client"
)
type TelegramClient struct {
Client *client.Client
repo *dal.DAL
TgClients []*client.Client
WaitingClients map[string]WaitingClient
}
func NewTelegramClient(apiID int32, apiHash string) (*TelegramClient, error) {
authorizer := client.ClientAuthorizer()
go client.CliInteractor(authorizer)
authorizer.TdlibParameters <- &client.SetTdlibParametersRequest{
UseTestDc: false,
DatabaseDirectory: filepath.Join(".tdlib", "database"),
FilesDirectory: filepath.Join(".tdlib", "files"),
UseFileDatabase: false,
UseChatInfoDatabase: false,
UseMessageDatabase: false,
UseSecretChats: false,
ApiId: apiID,
ApiHash: apiHash,
SystemLanguageCode: "en",
DeviceModel: "Server",
SystemVersion: "1.0.0",
ApplicationVersion: "1.0.0",
}
_, err := client.SetLogVerbosityLevel(&client.SetLogVerbosityLevelRequest{
NewVerbosityLevel: 1,
})
if err != nil {
return nil, err
}
tdlibClient, err := client.NewClient(authorizer)
if err != nil {
return nil, err
}
me, err := tdlibClient.GetMe()
if err != nil {
return nil, err
}
fmt.Printf("Me: %s %s [%v]", me.FirstName, me.LastName, me.Usernames)
type WaitingClient struct {
TdLibClient *client.Client
PreviousReq AuthTgUserReq
Authorizer *client.ClientAuthorizer
}
// todo come back saved tg accs to slice for check this status
func NewTelegramClient(ctx context.Context, repo *dal.DAL) (*TelegramClient, error) {
return &TelegramClient{
Client: tdlibClient,
repo: repo,
TgClients: make([]*client.Client, 0),
WaitingClients: make(map[string]WaitingClient),
}, nil
}
type AuthTgUserReq struct {
ApiID int32 `json:"api_id"`
ApiHash string `json:"api_hash"`
PhoneNumber string `json:"phone_number"`
Password string `json:"password"`
}
func (tg *TelegramClient) AddedToMap(data WaitingClient, id string) {
fmt.Println("AddedToMap")
tg.WaitingClients[id] = data
}
func (tg *TelegramClient) GetFromMap(id string) (WaitingClient, bool) {
fmt.Println("GetFromMap")
if data, ok := tg.WaitingClients[id]; ok {
return data, true
}
return WaitingClient{}, false
}
func (tg *TelegramClient) SaveTgAccount() {
}
func (tg *TelegramClient) CreateChannel(channelName string, botID int64) (string, error) {
return "", nil
}

8
go.mod

@ -1,6 +1,6 @@
module penahub.gitlab.yandexcloud.net/backend/quiz/core
go 1.21.4
go 1.22.4
require (
github.com/gofiber/fiber/v2 v2.52.4
@ -9,18 +9,19 @@ require (
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
github.com/pioz/faker v1.7.3
github.com/rs/xid v1.5.0
github.com/skeris/appInit v1.0.2
github.com/stretchr/testify v1.9.0
github.com/themakers/hlog v0.0.0-20191205140925-235e0e4baddf
github.com/twmb/franz-go v1.16.1
github.com/xuri/excelize/v2 v2.8.1
github.com/zelenin/go-tdlib v0.7.0
go.uber.org/zap v1.27.0
google.golang.org/grpc v1.64.0
google.golang.org/protobuf v1.34.2
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240607202348-efe5f2bf3e8c
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240624105135-6982631f2a4b
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240627194440-f997b952c31f
penahub.gitlab.yandexcloud.net/backend/quiz/worker.git v0.0.0-20240421230341-0e086fcbb990
penahub.gitlab.yandexcloud.net/backend/tdlib v0.0.0-20240630165148-3c27e15d9ac1
penahub.gitlab.yandexcloud.net/external/trashlog.git v0.1.2-0.20240615192328-b2f5dffe92ae
)
@ -50,7 +51,6 @@ require (
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/tealeg/xlsx v1.0.5 // indirect
github.com/twmb/franz-go/pkg/kmsg v1.8.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect

8
go.sum

@ -164,8 +164,6 @@ github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 h1:hPVCafDV85blFTabnqKgNh
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/zelenin/go-tdlib v0.7.0 h1:6rTf+kzDUdowUJy7Nd5/RHZAHtLjDjti3qm77JYvSNw=
github.com/zelenin/go-tdlib v0.7.0/go.mod h1:Xs8fXbk5n7VaPyrSs9DP7QYoBScWYsjX+lUcWmx1DIU=
go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU=
go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
@ -287,9 +285,11 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240607202348-efe5f2bf3e8c h1:CWb4UcuNXhd1KTNOmy2U0TJO4+Qxgxrj5cwkyFqbgrk=
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240607202348-efe5f2bf3e8c/go.mod h1:+bPxq2wfW5S1gd+83vZYmHm33AE7nEBfznWS8AM1TKE=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240624105135-6982631f2a4b h1:dNBWrclJAXP/JFRYQPXWAqmF/UihGxH4oZ9Vs0lfm40=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240624105135-6982631f2a4b/go.mod h1:uOuosXduBzd2WbLH6TDZO7ME7ZextulA662oZ6OsoB0=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240627194440-f997b952c31f h1:cvXLN5J6Np+lRbL1l4Kumu1uRB/D1OR2cbXc3qATzWc=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240627194440-f997b952c31f/go.mod h1:uOuosXduBzd2WbLH6TDZO7ME7ZextulA662oZ6OsoB0=
penahub.gitlab.yandexcloud.net/backend/quiz/worker.git v0.0.0-20240421230341-0e086fcbb990 h1:jiO8GWO+3sCnDAV8/NAV8tQIUwae/I6/xiDilW7zf0o=
penahub.gitlab.yandexcloud.net/backend/quiz/worker.git v0.0.0-20240421230341-0e086fcbb990/go.mod h1:zswBuTwmEsFHBVRu1nkG3/Fwylk5Vcm8OUm9iWxccSE=
penahub.gitlab.yandexcloud.net/backend/tdlib v0.0.0-20240630165148-3c27e15d9ac1 h1:fGhu5JuLODJ4pLb4YiyrioFXSQS+UP+KUQhcLwzIeWs=
penahub.gitlab.yandexcloud.net/backend/tdlib v0.0.0-20240630165148-3c27e15d9ac1/go.mod h1:AkE19hcbDwB7hoEASwImm7rUI+cK/8jMVJaTvMK4F+c=
penahub.gitlab.yandexcloud.net/external/trashlog.git v0.1.2-0.20240615192328-b2f5dffe92ae h1:vlGInCsQSDA464q7OMv3EWGUviQWQdEcpLc8HIRo+rE=
penahub.gitlab.yandexcloud.net/external/trashlog.git v0.1.2-0.20240615192328-b2f5dffe92ae/go.mod h1:3ml0dAGT8U8RhpevKBfRgG6yKZum8EI2uJxAb2WCIy4=

@ -5,32 +5,36 @@ import (
"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal"
"penahub.gitlab.yandexcloud.net/backend/quiz/core/brokers"
"penahub.gitlab.yandexcloud.net/backend/quiz/core/clients/auth"
"penahub.gitlab.yandexcloud.net/backend/quiz/core/clients/telegram"
)
// Service is an entity for http requests handling
type Service struct {
dal *dal.DAL
authClient *auth.AuthClient
producer *brokers.Producer
serviceName string
chDAL *dal.ClickHouseDAL
dal *dal.DAL
authClient *auth.AuthClient
producer *brokers.Producer
serviceName string
chDAL *dal.ClickHouseDAL
telegramClient *telegram.TelegramClient
}
type Deps struct {
Dal *dal.DAL
AuthClient *auth.AuthClient
Producer *brokers.Producer
ServiceName string
ChDAL *dal.ClickHouseDAL
Dal *dal.DAL
AuthClient *auth.AuthClient
Producer *brokers.Producer
ServiceName string
ChDAL *dal.ClickHouseDAL
TelegramClient *telegram.TelegramClient
}
func New(deps Deps) *Service {
return &Service{
dal: deps.Dal,
authClient: deps.AuthClient,
producer: deps.Producer,
serviceName: deps.ServiceName,
chDAL: deps.ChDAL,
dal: deps.Dal,
authClient: deps.AuthClient,
producer: deps.Producer,
serviceName: deps.ServiceName,
chDAL: deps.ChDAL,
telegramClient: deps.TelegramClient,
}
}
@ -83,8 +87,8 @@ func (s *Service) Register(app *fiber.App) {
app.Get("/statistics/:quizID/pipelines", s.GetPipelinesStatistics)
//telegram handlers
app.Get("/telegram/pool", s.GetPoolTgBots)
app.Post("/telegram/create", s.AddingTgBot)
app.Delete("/telegram/:id", s.DeleteTgBotByID)
app.Post("/telegram/auth", s.SendAuthTgCode)
app.Get("/telegram/pool", s.GetPoolTgAccounts)
app.Post("/telegram/create", s.AddingTgAccount)
app.Delete("/telegram/:id", s.DeleteTgAccountByID)
app.Post("/telegram/setCode", s.SettingTgCode)
}

@ -1,19 +1,120 @@
package service
import "github.com/gofiber/fiber/v2"
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/rs/xid"
"path/filepath"
"penahub.gitlab.yandexcloud.net/backend/quiz/core/clients/telegram"
"penahub.gitlab.yandexcloud.net/backend/tdlib/client"
)
func (s *Service) GetPoolTgBots(ctx *fiber.Ctx) error {
type Message struct {
Type string `json:"type"`
Data string `json:"data"`
}
func (s *Service) GetPoolTgAccounts(ctx *fiber.Ctx) error {
return nil
}
func (s *Service) AddingTgBot(ctx *fiber.Ctx) error {
return nil
// todo save to slice and save to db for rewoke
func (s *Service) AddingTgAccount(ctx *fiber.Ctx) error {
var req telegram.AuthTgUserReq
if err := ctx.BodyParser(&req); err != nil {
return ctx.Status(fiber.StatusBadRequest).SendString("Invalid request data")
}
authorizer := client.ClientAuthorizerr()
authorizer.TdlibParameters <- &client.SetTdlibParametersRequest{
UseTestDc: false,
DatabaseDirectory: filepath.Join(".tdlib", "database"),
FilesDirectory: filepath.Join(".tdlib", "files"),
UseFileDatabase: false,
UseChatInfoDatabase: false,
UseMessageDatabase: false,
UseSecretChats: false,
ApiId: req.ApiID,
ApiHash: req.ApiHash,
SystemLanguageCode: "en",
DeviceModel: "Server",
SystemVersion: "1.0.0",
ApplicationVersion: "1.0.0",
}
_, err := client.SetLogVerbosityLevel(&client.SetLogVerbosityLevelRequest{
NewVerbosityLevel: 1,
})
if err != nil {
return ctx.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
var tdlibClient *client.Client
// todo проверить как завершается
go func() {
tdlibClient, err = client.NewClient(authorizer)
if err != nil {
fmt.Println("new client failed", err)
return
}
}()
for {
state, ok := <-authorizer.State
if !ok {
return ctx.SendStatus(fiber.StatusOK)
}
fmt.Println("currnet state:", state)
switch state.AuthorizationStateType() {
case client.TypeAuthorizationStateWaitPhoneNumber:
authorizer.PhoneNumber <- req.PhoneNumber
case client.TypeAuthorizationStateWaitCode:
id := xid.New()
s.telegramClient.AddedToMap(telegram.WaitingClient{
TdLibClient: tdlibClient,
PreviousReq: req,
Authorizer: authorizer,
}, id.String())
return ctx.Status(fiber.StatusOK).JSON(id.String())
case client.TypeAuthorizationStateLoggingOut, client.TypeAuthorizationStateClosing, client.TypeAuthorizationStateClosed:
return ctx.Status(fiber.StatusForbidden).SendString("auth failed")
}
}
}
func (s *Service) DeleteTgBotByID(ctx *fiber.Ctx) error {
return nil
func (s *Service) SettingTgCode(ctx *fiber.Ctx) error {
var req struct {
Code string `json:"code"`
ID string `json:"id"`
}
if err := ctx.BodyParser(&req); err != nil {
return ctx.Status(fiber.StatusBadRequest).SendString("Invalid request data")
}
data, ok := s.telegramClient.GetFromMap(req.ID)
if !ok {
return ctx.Status(fiber.StatusBadRequest).SendString("Invalid id, don't have data")
}
data.Authorizer.Code <- req.Code
for {
state, ok := <-data.Authorizer.State
if !ok {
return ctx.SendStatus(fiber.StatusOK)
}
fmt.Println("currnet state:", state)
switch state.AuthorizationStateType() {
case client.TypeAuthorizationStateReady:
return ctx.SendStatus(fiber.StatusOK)
case client.TypeAuthorizationStateWaitPassword:
data.Authorizer.Password <- data.PreviousReq.Password
case client.TypeAuthorizationStateLoggingOut, client.TypeAuthorizationStateClosing, client.TypeAuthorizationStateClosed:
return ctx.Status(fiber.StatusForbidden).SendString("auth failed")
}
}
}
func (s *Service) SendAuthTgCode(ctx *fiber.Ctx) error {
func (s *Service) DeleteTgAccountByID(ctx *fiber.Ctx) error {
return nil
}