Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
config.yml
.vscode
6 changes: 6 additions & 0 deletions common/commonconst/consts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package commonconst

const ERR_LOG = "error"
const ACCOUNTID_LOG = "accountId"
const QUERY_LOG = "query"
const DATA_LOG = "data"
8 changes: 8 additions & 0 deletions telegram-service/src/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package main

import (
"log/slog"
"os"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"go.uber.org/fx"
"mine.local/ocr-gallery/common/commonconfig"
Expand All @@ -13,6 +16,11 @@ func Statup(serv service.TelegramBotService) {
}

func main() {
handler := slog.NewTextHandler(os.Stdout, nil)
logger := slog.New(handler)
slog.SetLogLoggerLevel(slog.LevelDebug)
slog.SetDefault(logger)

commonconfig.InitConfig()

fx.New(
Expand Down
45 changes: 25 additions & 20 deletions telegram-service/src/service/InlineHandlerService.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package service

import (
"context"
"log"
"log/slog"
"strconv"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/labstack/gommon/log"
"mine.local/ocr-gallery/telegram-service/conf"
)

Expand All @@ -30,8 +31,11 @@ func (i *InineHandlerServiceImpl) ProcessQuery(
userId := request.From.ID
query := request.Query

log.Printf("Inline query: userid: '%d' id: '%s' text: '%s' offset: '%s'",
userId, request.ID, request.Query, request.Offset)
slog.Info("Inline query:",
"userId", userId,
"requestId", request.ID,
"query", request.Query,
"offset", request.Offset)

accountId, err := i.userAccount.MapUserToAccount(ctx, userId)
if err != nil {
Expand All @@ -58,6 +62,11 @@ func (i *InineHandlerServiceImpl) ProcessQuery(
return nil, err
}

slog.Info("Search query result",
"userId", userId,
"requestId", request.ID,
"resultListSize", len(results))

if results == nil {
retval := tgbotapi.InlineConfig{
InlineQueryID: request.ID,
Expand All @@ -69,6 +78,14 @@ func (i *InineHandlerServiceImpl) ProcessQuery(

photos := make([]interface{}, len(results))
for index, item := range results {
log.Info("SearchResultItem ",
"userId", userId,
"requestId", request.ID,
"index", index,
"id", item.Id,
"sortId", item.SortId,
"url", item.ImageUrl,
)
inlineChoice := tgbotapi.NewInlineQueryResultPhotoWithThumb(
item.Id.String(),
item.ImageUrl,
Expand All @@ -81,14 +98,16 @@ func (i *InineHandlerServiceImpl) ProcessQuery(
photos[index] = inlineChoice
}

log.Printf("Result count is %d", len(results))

nextOffset := ""
if len(results) == i.config.PageSize && i.config.PageSize > 0 {
nextOffset = strconv.FormatInt(results[i.config.PageSize-1].SortId, 10)
log.Printf("Next offset is %s", nextOffset)
}

log.Info("Search next offset ",
"userId", userId,
"requestId", request.ID,
"nextOffset", nextOffset)

retval := tgbotapi.InlineConfig{
InlineQueryID: request.ID,
CacheTime: 5,
Expand All @@ -100,20 +119,6 @@ func (i *InineHandlerServiceImpl) ProcessQuery(
return &retval, nil
}

func substr(s string, start, end int) string {
counter, startIdx := 0, 0
for i := range s {
if counter == start {
startIdx = i
}
if counter == end {
return s[startIdx:i]
}
counter++
}
return s[startIdx:]
}

func NewInlineService(
userAccount UserAccountService,
storage StorageConnector,
Expand Down
15 changes: 11 additions & 4 deletions telegram-service/src/service/MessageHandlerService.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"context"
"errors"
"fmt"
"log/slog"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"mine.local/ocr-gallery/common/commonconst"
)

type MessageHandlerService interface {
Expand All @@ -31,25 +33,30 @@ func (m MessageHandlerServiceImpl) ProcessMessage(message *tgbotapi.Message) (*M
}

if fileId == "" {
return nil, errors.New("message dont contain image")
return nil, errors.New("messageHandlerService: message dont contain image")
}

file, err := m.fileResolver.GetFile(fileId)

if err != nil {
return nil, err
return nil, fmt.Errorf("messageHandlerService: GetFile failed, fileId: %s : %w", fileId, err)
}

accountId, err := m.userAccountService.MapUserToAccount(context.TODO(), message.Chat.ID)
if err != nil {
return nil, err
return nil, fmt.Errorf("messageHandlerService: MapUserToAccount failed : %w", err)
}

result, err := m.storage.CreateMeme(file, "image/jpeg", accountId)
if err != nil {
return nil, err
return nil, fmt.Errorf("messageHandlerService: CreateMeme failed : %w", err)
}

slog.Info("messageHandlerService: meme created",
commonconst.ACCOUNTID_LOG, accountId,
"imageId", result.Id,
"duplicate", result.DuplicateStatus)

return &MessageHandlerResponse{
Message: fmt.Sprintf("\n```Text\n%s\n```\n ID: `%s` \n Status: `%s`", result.Text, result.Id, result.DuplicateStatus),
ParseMode: "Markdown",
Expand Down
9 changes: 5 additions & 4 deletions telegram-service/src/service/StorageConnector.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"errors"
"fmt"

"github.com/google/uuid"
"mine.local/ocr-gallery/apispec/meme-storage/client"
Expand Down Expand Up @@ -47,11 +48,11 @@ func (s *StorageConnectorImpl) ProcessSearchQuery(
})

if err != nil {
return nil, err
return nil, fmt.Errorf("storageService: search meme query failed query: %s : %w", query, err)
}

if response.HTTPResponse.StatusCode >= 400 {
return nil, errors.New("failed to request storage service")
return nil, fmt.Errorf("storageService: failed to request storage service: %s", string(response.Body))
}

entityResult := make([]*entity.MemeSearchResult, len(*response.JSON200))
Expand Down Expand Up @@ -87,11 +88,11 @@ func (u *StorageConnectorImpl) CreateMeme(file []byte, mime string, accountId uu
)

if err != nil {
return nil, err
return nil, fmt.Errorf("storageService: create meme failed : %w", err)
}

if resp.StatusCode() != 200 {
return nil, errors.New("UploadFile() - failed - storage service status code non 2xx ")
return nil, errors.New("storageService: create meme failed : storage service status code non 2xx ")
}

creationResult := &entity.MemeCreateResult{
Expand Down
24 changes: 13 additions & 11 deletions telegram-service/src/service/Telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package service

import (
"context"
"log"
"log/slog"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"mine.local/ocr-gallery/common/commonconst"
"mine.local/ocr-gallery/telegram-service/conf"
)

Expand All @@ -19,7 +20,7 @@ type TelegramBotServiceImpl struct {
}

func (srv *TelegramBotServiceImpl) StartBot() {
log.Printf("Authorized on account %s", srv.bot.Self.UserName)
slog.Info("Authorized", "account", srv.bot.Self.UserName)

u := tgbotapi.NewUpdate(0)
u.Timeout = 60
Expand All @@ -37,13 +38,13 @@ func (srv *TelegramBotServiceImpl) StartBot() {
}

func (srv *TelegramBotServiceImpl) HandleMessage(update *tgbotapi.Update) {
log.Printf("Bot message request: %+v", update.Message)
slog.Info("Bot message request", "request", update.Message)
answer, err := srv.message.ProcessMessage(update.Message)
if err != nil {
log.Println(err)
slog.Error("Failed to process message", commonconst.ERR_LOG, err)
message := tgbotapi.NewMessage(update.Message.Chat.ID, err.Error())
message.ReplyToMessageID = update.Message.MessageID
_, err = srv.bot.Send(message)
srv.bot.Send(message)
return
}

Expand All @@ -52,30 +53,31 @@ func (srv *TelegramBotServiceImpl) HandleMessage(update *tgbotapi.Update) {
message.ParseMode = answer.ParseMode
_, err = srv.bot.Send(message)
if err != nil {
log.Println(err)
slog.Error("Failed to send message to bot", commonconst.ERR_LOG, err)
return
}
}
func (srv *TelegramBotServiceImpl) HandleInlineRequest(update *tgbotapi.Update) {
log.Printf("Bot inline request: %+v", update.InlineQuery)
slog.Debug("Bot inline request:", commonconst.DATA_LOG, update.InlineQuery)
inlineResponse, err := srv.inline.ProcessQuery(context.Background(), update.InlineQuery)
if err != nil {
log.Println(err)
slog.Error("failed to process inline query:", commonconst.ERR_LOG, err)
return
}
log.Printf("Bot inline response: %+v", inlineResponse)
slog.Debug("Bot inline response:", commonconst.DATA_LOG, inlineResponse)

_, err = srv.bot.Request(inlineResponse)
if err != nil {
log.Println(err)
slog.Error("Failed to send message to bot", commonconst.ERR_LOG, err)
return
}
}

func NewTelegramBot(config *conf.TelegramConfig) *tgbotapi.BotAPI {
bot, err := tgbotapi.NewBotAPI(config.Token)
if err != nil {
log.Panic(err)
slog.Error("Bot api creation failed", commonconst.ERR_LOG, err)
panic("bot api creation failed")
}
bot.Debug = config.Debug
return bot
Expand Down
7 changes: 4 additions & 3 deletions telegram-service/src/service/TelegramFileResolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package service

import (
"errors"
"fmt"
"io"
"net/http"
)
Expand All @@ -22,15 +23,15 @@ type TelegramFileResolverServiceImpl struct {
func (t *TelegramFileResolverServiceImpl) GetFile(fileID string) ([]byte, error) {
url, err := t.fileGetter.GetFileDirectURL(fileID)
if err != nil {
return nil, err
return nil, fmt.Errorf("TelegramFileResolverService: GetFileDirectURL failed, fileId: %s : %w", fileID, err)
}
resp, err := http.Get(url)
if err != nil {
return nil, err
return nil, fmt.Errorf("TelegramFileResolverService: download file by got url failed, url: %s : %w", url, err)
}

if resp.StatusCode >= 400 {
return nil, errors.New("GetFile() failed - non 2xx status code")
return nil, errors.New("TelegramFileResolverService: download file by got url failed url: %s : non 2xx status code")
}

return io.ReadAll(resp.Body)
Expand Down
Loading