refactor
This commit is contained in:
@@ -2,10 +2,10 @@ package screens
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"example.com/m/bot"
|
||||
"example.com/m/ui"
|
||||
"github.com/NicoNex/echotron/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -28,12 +28,11 @@ type CreativeEditorFields struct {
|
||||
MediaFileID string // File ID из Telegram
|
||||
MediaChanged bool
|
||||
|
||||
// Режим ввода
|
||||
InputMode string
|
||||
|
||||
// Состояние для добавления кнопки
|
||||
WaitingForButtonText bool
|
||||
WaitingForButtonURL bool
|
||||
CurrentButtonText *string
|
||||
WaitingForMedia bool
|
||||
PendingButtonType string
|
||||
PendingButtonType string
|
||||
|
||||
// ID сообщения с креативом (которое постоянно обновляется)
|
||||
CreativeMessageID *int
|
||||
@@ -41,115 +40,108 @@ type CreativeEditorFields struct {
|
||||
ControlPanelMessageID *int
|
||||
|
||||
// Предыдущее состояние для определения изменения типа сообщения
|
||||
previousHasMedia bool
|
||||
previousHasMedia bool
|
||||
previousMediaType string
|
||||
previousMediaFileID string
|
||||
}
|
||||
|
||||
const inviteLinkPlaceholder = "{{invite_link}}"
|
||||
const inviteLinkPreviewURL = "https://t.me/+nlOUmIsLGAlmZTMy" //ссылка приглашения для предпросмотра
|
||||
const buttonURLPlaceholder = "https://example.com"
|
||||
|
||||
const (
|
||||
inputModeText = "text"
|
||||
inputModeButtonText = "button_text"
|
||||
inputModeButtonURL = "button_url"
|
||||
inputModeMedia = "media"
|
||||
)
|
||||
const msgCreativeDefault = `
|
||||
<i>💭 Я твой креатив
|
||||
|
||||
У меня пока нет текста, добавь его ниже.
|
||||
|
||||
</i>
|
||||
`
|
||||
const msgCreativeManagement = `
|
||||
<b>👆Превью креатива выше</b> — так он будет выглядеть при отправке.
|
||||
|
||||
Выберите, что изменить:
|
||||
|
||||
`
|
||||
|
||||
func buildCreativeKeyboard(buttons [][]echotron.InlineKeyboardButton) echotron.InlineKeyboardMarkup {
|
||||
keyboard := echotron.InlineKeyboardMarkup{
|
||||
InlineKeyboard: buttons,
|
||||
}
|
||||
if len(buttons) == 0 {
|
||||
keyboard.InlineKeyboard = [][]echotron.InlineKeyboardButton{}
|
||||
}
|
||||
return keyboard
|
||||
}
|
||||
|
||||
// GetCreativeText возвращает текст для превью креатива
|
||||
func (e *CreativeEditorFields) GetCreativeText() string {
|
||||
var result string
|
||||
|
||||
if e.Text != nil && *e.Text != "" {
|
||||
text := strings.TrimSpace(*e.Text)
|
||||
|
||||
// Проверяем что текст не пустой
|
||||
if text == "" {
|
||||
log.Info().Str("text", *e.Text).Msg("GetCreativeText: text is empty, using default")
|
||||
return result + `<i>💭 Я твой креатив
|
||||
|
||||
У меня пока нет текста, добавь его ниже.
|
||||
|
||||
</i>`
|
||||
}
|
||||
|
||||
// Заменяем пригласительные ссылки с классом tg-link на preview-ссылку
|
||||
// Находим все вхождения <a class="tg-link">...</a> и заменяем на кликабельную ссылку
|
||||
replacementCount := 0
|
||||
for strings.Contains(text, `<a class="tg-link">`) {
|
||||
startIdx := strings.Index(text, `<a class="tg-link">`)
|
||||
if startIdx == -1 {
|
||||
break
|
||||
}
|
||||
endIdx := strings.Index(text[startIdx:], "</a>")
|
||||
if endIdx == -1 {
|
||||
log.Warn().Msg("Found <a class=\"tg-link\"> but no closing </a>")
|
||||
break
|
||||
}
|
||||
endIdx += startIdx
|
||||
|
||||
// Извлекаем текст между тегами
|
||||
linkText := text[startIdx+len(`<a class="tg-link">`) : endIdx]
|
||||
log.Info().
|
||||
Int("replacement_num", replacementCount).
|
||||
Str("linkText_before_sanitize", linkText).
|
||||
Msg("Processing tg-link")
|
||||
|
||||
// ВАЖНО: Удаляем все HTML-теги из текста ссылки для предотвращения неправильной вложенности
|
||||
// Это нужно для старых креативов с неправильным HTML
|
||||
tagsRemoved := 0
|
||||
for {
|
||||
openTag := strings.Index(linkText, "<")
|
||||
if openTag == -1 {
|
||||
break
|
||||
}
|
||||
closeTag := strings.Index(linkText[openTag:], ">")
|
||||
if closeTag == -1 {
|
||||
log.Warn().Str("linkText", linkText).Msg("Found < but no closing >")
|
||||
break
|
||||
}
|
||||
// Удаляем тег
|
||||
removedTag := linkText[openTag : openTag+closeTag+1]
|
||||
linkText = linkText[:openTag] + linkText[openTag+closeTag+1:]
|
||||
tagsRemoved++
|
||||
log.Info().
|
||||
Str("removed_tag", removedTag).
|
||||
Str("linkText_after", linkText).
|
||||
Int("tags_removed_total", tagsRemoved).
|
||||
Msg("Removed HTML tag from link text")
|
||||
}
|
||||
|
||||
linkText = strings.TrimSpace(linkText)
|
||||
|
||||
// Если текст ссылки не пустой, добавляем атрибут href с примером ссылки
|
||||
// Если пустой, показываем просто текст примера ссылки (без тега)
|
||||
var replacement string
|
||||
if linkText != "" {
|
||||
// Есть текст - добавляем href атрибут к тегу
|
||||
replacement = fmt.Sprintf(`<a class="tg-link" href="%s">%s</a>`, inviteLinkPreviewURL, linkText)
|
||||
} else {
|
||||
// Пусто - показываем просто текст примера ссылки
|
||||
replacement = fmt.Sprintf(`%s`, inviteLinkPreviewURL)
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("linkText_after_sanitize", linkText).
|
||||
Int("tags_removed", tagsRemoved).
|
||||
Str("replacement", replacement).
|
||||
Msg("Sanitized link text")
|
||||
|
||||
text = text[:startIdx] + replacement + text[endIdx+len("</a>"):]
|
||||
replacementCount++
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Int("replacements_made", replacementCount).
|
||||
Str("final_text", text).
|
||||
Msg("Finished processing tg-links")
|
||||
|
||||
// Также заменяем плейсхолдер {{invite_link}} на preview URL (как в кнопках)
|
||||
text = strings.ReplaceAll(text, inviteLinkPlaceholder, inviteLinkPreviewURL)
|
||||
|
||||
log.Info().Str("text", *e.Text).Msg("GetCreativeText: returning creative text")
|
||||
return result + text
|
||||
if e.Text == nil {
|
||||
return msgCreativeDefault
|
||||
}
|
||||
log.Info().Bool("text_is_nil", e.Text == nil).Msg("GetCreativeText: returning default text")
|
||||
return result + `<i>💭 Я твой креатив
|
||||
|
||||
У меня пока нет текста, добавь его ниже.
|
||||
text := strings.TrimSpace(ui.SanitizeHTML(*e.Text))
|
||||
if text == "" {
|
||||
return msgCreativeDefault
|
||||
}
|
||||
|
||||
</i>`
|
||||
// Заменяем пригласительные ссылки с классом tg-link на preview-ссылку
|
||||
// Находим все вхождения <a class="tg-link">...</a> и заменяем на кликабельную ссылку
|
||||
for strings.Contains(text, `<a class="tg-link">`) {
|
||||
startIdx := strings.Index(text, `<a class="tg-link">`)
|
||||
if startIdx == -1 {
|
||||
break
|
||||
}
|
||||
endIdx := strings.Index(text[startIdx:], "</a>")
|
||||
if endIdx == -1 {
|
||||
log.Warn().Msg("Found <a class=\"tg-link\"> but no closing </a>")
|
||||
break
|
||||
}
|
||||
endIdx += startIdx
|
||||
|
||||
// Извлекаем текст между тегами
|
||||
linkText := text[startIdx+len(`<a class="tg-link">`) : endIdx]
|
||||
// ВАЖНО: Удаляем все HTML-теги из текста ссылки для предотвращения неправильной вложенности
|
||||
// Это нужно для старых креативов с неправильным HTML
|
||||
for {
|
||||
openTag := strings.Index(linkText, "<")
|
||||
if openTag == -1 {
|
||||
break
|
||||
}
|
||||
closeTag := strings.Index(linkText[openTag:], ">")
|
||||
if closeTag == -1 {
|
||||
log.Warn().Str("linkText", linkText).Msg("Found < but no closing >")
|
||||
break
|
||||
}
|
||||
// Удаляем тег
|
||||
linkText = linkText[:openTag] + linkText[openTag+closeTag+1:]
|
||||
}
|
||||
|
||||
linkText = strings.TrimSpace(linkText)
|
||||
|
||||
// Если текст ссылки не пустой, добавляем атрибут href с примером ссылки
|
||||
// Если пустой, показываем просто текст примера ссылки (без тега)
|
||||
var replacement string
|
||||
if linkText != "" {
|
||||
// Есть текст - добавляем href атрибут к тегу
|
||||
replacement = fmt.Sprintf(`<a class="tg-link" href="%s">%s</a>`, inviteLinkPreviewURL, linkText)
|
||||
} else {
|
||||
// Пусто - показываем просто текст примера ссылки
|
||||
replacement = fmt.Sprintf(`%s`, inviteLinkPreviewURL)
|
||||
}
|
||||
|
||||
text = text[:startIdx] + replacement + text[endIdx+len("</a>"):]
|
||||
}
|
||||
|
||||
// Также заменяем плейсхолдер {{invite_link}} на preview URL (как в кнопках)
|
||||
text = strings.ReplaceAll(text, inviteLinkPlaceholder, inviteLinkPreviewURL)
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
// GetCreativeButtons возвращает кнопки для превью креатива
|
||||
@@ -178,14 +170,25 @@ func (e *CreativeEditorFields) SendCreativePreview(b *bot.Bot) {
|
||||
creativeButtons := e.GetCreativeButtons()
|
||||
|
||||
// Создаем клавиатуру с пустым массивом (не nil!)
|
||||
keyboard := echotron.InlineKeyboardMarkup{
|
||||
InlineKeyboard: creativeButtons,
|
||||
}
|
||||
if len(creativeButtons) == 0 {
|
||||
keyboard.InlineKeyboard = [][]echotron.InlineKeyboardButton{}
|
||||
}
|
||||
keyboard := buildCreativeKeyboard(creativeButtons)
|
||||
|
||||
var msgID int
|
||||
sendText := func() (int, error) {
|
||||
res, err := b.SendMessage(creativeText, b.ChatID, &echotron.MessageOptions{
|
||||
ReplyMarkup: keyboard,
|
||||
ParseMode: echotron.HTML,
|
||||
LinkPreviewOptions: echotron.LinkPreviewOptions{
|
||||
IsDisabled: true,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if res.Result == nil {
|
||||
return 0, fmt.Errorf("send message: empty result")
|
||||
}
|
||||
return res.Result.ID, nil
|
||||
}
|
||||
|
||||
// Если есть медиа, отправляем с медиа
|
||||
if e.MediaFileID != "" {
|
||||
@@ -228,15 +231,8 @@ func (e *CreativeEditorFields) SendCreativePreview(b *bot.Bot) {
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("media_type", e.MediaType).Msg("Failed to send media")
|
||||
// Fallback to text message - используем прямой SendMessage
|
||||
res, err := b.SendMessage(creativeText, b.ChatID, &echotron.MessageOptions{
|
||||
ReplyMarkup: keyboard,
|
||||
ParseMode: echotron.HTML,
|
||||
LinkPreviewOptions: echotron.LinkPreviewOptions{
|
||||
IsDisabled: true,
|
||||
},
|
||||
})
|
||||
if err == nil && res.Result != nil {
|
||||
msgID = res.Result.ID
|
||||
if id, err := sendText(); err == nil {
|
||||
msgID = id
|
||||
}
|
||||
} else if res.Result != nil {
|
||||
msgID = res.Result.ID
|
||||
@@ -244,26 +240,19 @@ func (e *CreativeEditorFields) SendCreativePreview(b *bot.Bot) {
|
||||
} else {
|
||||
// Отправляем обычное текстовое сообщение напрямую (не через SendNew)
|
||||
// чтобы не затронуть LastMessageID и не затронуть cleanup
|
||||
res, err := b.SendMessage(creativeText, b.ChatID, &echotron.MessageOptions{
|
||||
ReplyMarkup: keyboard,
|
||||
ParseMode: echotron.HTML,
|
||||
LinkPreviewOptions: echotron.LinkPreviewOptions{
|
||||
IsDisabled: true,
|
||||
},
|
||||
})
|
||||
id, err := sendText()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to send creative preview")
|
||||
return
|
||||
}
|
||||
if res.Result != nil {
|
||||
msgID = res.Result.ID
|
||||
}
|
||||
msgID = id
|
||||
}
|
||||
|
||||
// ВАЖНО: Сохраняем копию значения, а не указатель на переменную!
|
||||
e.CreativeMessageID = &msgID
|
||||
e.previousHasMedia = e.MediaFileID != ""
|
||||
log.Info().Int("creative_msg_id", *e.CreativeMessageID).Bool("has_media", e.MediaFileID != "").Msg("Creative preview sent")
|
||||
e.previousMediaType = e.MediaType
|
||||
e.previousMediaFileID = e.MediaFileID
|
||||
}
|
||||
|
||||
// UpdateCreativePreview обновляет превью креатива
|
||||
@@ -277,17 +266,8 @@ func (e *CreativeEditorFields) UpdateCreativePreview(b *bot.Bot) {
|
||||
|
||||
currentHasMedia := e.MediaFileID != ""
|
||||
|
||||
log.Info().
|
||||
Int("creative_msg_id", *e.CreativeMessageID).
|
||||
Bool("has_media", currentHasMedia).
|
||||
Bool("previous_has_media", e.previousHasMedia).
|
||||
Str("media_type", e.MediaType).
|
||||
Msg("Updating creative preview")
|
||||
|
||||
// Если тип сообщения изменился (текст ↔ медиа), нужно пересоздать оба сообщения
|
||||
if currentHasMedia != e.previousHasMedia {
|
||||
log.Info().Msg("Message type changed, recreating both messages")
|
||||
|
||||
// Удаляем оба сообщения
|
||||
if e.CreativeMessageID != nil {
|
||||
b.DeleteMessage(b.ChatID, *e.CreativeMessageID)
|
||||
@@ -307,29 +287,84 @@ func (e *CreativeEditorFields) UpdateCreativePreview(b *bot.Bot) {
|
||||
creativeText := e.GetCreativeText()
|
||||
creativeButtons := e.GetCreativeButtons()
|
||||
|
||||
keyboard := echotron.InlineKeyboardMarkup{
|
||||
InlineKeyboard: creativeButtons,
|
||||
}
|
||||
if len(creativeButtons) == 0 {
|
||||
keyboard.InlineKeyboard = [][]echotron.InlineKeyboardButton{}
|
||||
}
|
||||
keyboard := buildCreativeKeyboard(creativeButtons)
|
||||
|
||||
msgID := echotron.NewMessageID(b.ChatID, *e.CreativeMessageID)
|
||||
logEditError := func(msg string, err error) {
|
||||
textPreview := creativeText
|
||||
runes := []rune(textPreview)
|
||||
if len(runes) > 200 {
|
||||
textPreview = string(runes[:200]) + "..."
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Int("creative_message_id", *e.CreativeMessageID).
|
||||
Str("media_type", e.MediaType).
|
||||
Int("text_len", len([]rune(creativeText))).
|
||||
Str("text_preview", textPreview).
|
||||
Msg(msg)
|
||||
}
|
||||
|
||||
// Если есть медиа - редактируем caption
|
||||
updated := false
|
||||
if e.MediaFileID != "" {
|
||||
_, err := b.EditMessageCaption(
|
||||
msgID,
|
||||
&echotron.MessageCaptionOptions{
|
||||
Caption: creativeText,
|
||||
ParseMode: echotron.HTML,
|
||||
ReplyMarkup: keyboard,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to edit media caption")
|
||||
mediaChanged := e.MediaFileID != e.previousMediaFileID || e.MediaType != e.previousMediaType
|
||||
if mediaChanged {
|
||||
var media echotron.InputMedia
|
||||
switch e.MediaType {
|
||||
case "photo":
|
||||
media = echotron.InputMediaPhoto{
|
||||
Type: echotron.MediaTypePhoto,
|
||||
Media: echotron.NewInputFileID(e.MediaFileID),
|
||||
Caption: creativeText,
|
||||
ParseMode: echotron.HTML,
|
||||
}
|
||||
case "video":
|
||||
media = echotron.InputMediaVideo{
|
||||
Type: echotron.MediaTypeVideo,
|
||||
Media: echotron.NewInputFileID(e.MediaFileID),
|
||||
Caption: creativeText,
|
||||
ParseMode: echotron.HTML,
|
||||
}
|
||||
case "animation":
|
||||
media = echotron.InputMediaAnimation{
|
||||
Type: echotron.MediaTypeAnimation,
|
||||
Media: echotron.NewInputFileID(e.MediaFileID),
|
||||
Caption: creativeText,
|
||||
ParseMode: echotron.HTML,
|
||||
}
|
||||
}
|
||||
|
||||
if media != nil {
|
||||
_, err := b.EditMessageMedia(
|
||||
msgID,
|
||||
media,
|
||||
&echotron.MessageMediaOptions{
|
||||
ReplyMarkup: keyboard,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
logEditError("Failed to edit message media", err)
|
||||
} else {
|
||||
updated = true
|
||||
}
|
||||
} else {
|
||||
log.Warn().Str("media_type", e.MediaType).Msg("Unsupported media type for edit")
|
||||
}
|
||||
} else {
|
||||
e.previousHasMedia = currentHasMedia
|
||||
_, err := b.EditMessageCaption(
|
||||
msgID,
|
||||
&echotron.MessageCaptionOptions{
|
||||
Caption: creativeText,
|
||||
ParseMode: echotron.HTML,
|
||||
ReplyMarkup: keyboard,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
logEditError("Failed to edit media caption", err)
|
||||
} else {
|
||||
updated = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Текстовое сообщение - редактируем текст
|
||||
@@ -345,11 +380,88 @@ func (e *CreativeEditorFields) UpdateCreativePreview(b *bot.Bot) {
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to edit message text")
|
||||
logEditError("Failed to edit message text", err)
|
||||
} else {
|
||||
e.previousHasMedia = currentHasMedia
|
||||
updated = true
|
||||
}
|
||||
}
|
||||
|
||||
if updated {
|
||||
e.previousHasMedia = currentHasMedia
|
||||
e.previousMediaType = e.MediaType
|
||||
e.previousMediaFileID = e.MediaFileID
|
||||
}
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) DeleteUserMessage(b *bot.Bot, messageID int) {
|
||||
_, err := b.DeleteMessage(b.ChatID, messageID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to delete user message")
|
||||
}
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) SetMediaFromMessage(message *echotron.Message) bool {
|
||||
switch {
|
||||
case message.Photo != nil && len(message.Photo) > 0:
|
||||
photo := message.Photo[len(message.Photo)-1]
|
||||
e.MediaType = "photo"
|
||||
e.MediaFileID = photo.FileID
|
||||
case message.Video != nil:
|
||||
e.MediaType = "video"
|
||||
e.MediaFileID = message.Video.FileID
|
||||
case message.Animation != nil:
|
||||
e.MediaType = "animation"
|
||||
e.MediaFileID = message.Animation.FileID
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
e.MediaChanged = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) AddInviteButton(text string) {
|
||||
e.Buttons = append(e.Buttons, InlineButton{
|
||||
Text: text,
|
||||
URL: inviteLinkPlaceholder,
|
||||
})
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) AddCustomButtonPlaceholder(text string) {
|
||||
e.Buttons = append(e.Buttons, InlineButton{
|
||||
Text: text,
|
||||
URL: buttonURLPlaceholder,
|
||||
})
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) UpdateLastButtonURL(url string) {
|
||||
if len(e.Buttons) > 0 {
|
||||
e.Buttons[len(e.Buttons)-1].URL = url
|
||||
}
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) ClearInputMode() {
|
||||
e.InputMode = ""
|
||||
e.PendingButtonType = ""
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) CancelPendingButton(b *bot.Bot) {
|
||||
if e.InputMode == inputModeButtonURL && len(e.Buttons) > 0 {
|
||||
lastButton := e.Buttons[len(e.Buttons)-1]
|
||||
if lastButton.URL == buttonURLPlaceholder || lastButton.URL == inviteLinkPlaceholder {
|
||||
e.Buttons = e.Buttons[:len(e.Buttons)-1]
|
||||
e.UpdateCreativePreview(b)
|
||||
}
|
||||
}
|
||||
|
||||
e.ClearInputMode()
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) IsValidButtonURL(url string, allowHTTP bool) bool {
|
||||
if allowHTTP {
|
||||
return strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")
|
||||
}
|
||||
return strings.HasPrefix(url, "https://")
|
||||
}
|
||||
|
||||
// ShowManagementPanel показывает панель управления креативом
|
||||
@@ -358,10 +470,13 @@ func (e *CreativeEditorFields) UpdateCreativePreview(b *bot.Bot) {
|
||||
// cancelCallback - callback для кнопки отмены
|
||||
// extraButtons - дополнительные кнопки которые будут добавлены перед финальными кнопками
|
||||
func (e *CreativeEditorFields) ShowManagementPanel(b *bot.Bot, confirmButtonText, confirmCallback, cancelCallback string, extraButtons ...[]echotron.InlineKeyboardButton) {
|
||||
text := `<b>👆Превью креатива выше</b> — так он будет выглядеть при отправке.
|
||||
text := msgCreativeManagement
|
||||
|
||||
Выберите, что изменить:`
|
||||
buttons := e.BuildEditorButtons(confirmButtonText, confirmCallback, "Назад", cancelCallback, extraButtons...)
|
||||
e.ShowControlPanel(b, text, buttons)
|
||||
}
|
||||
|
||||
func (e *CreativeEditorFields) BuildEditorButtons(confirmText, confirmCallback, cancelText, cancelCallback string, extraButtons ...[]echotron.InlineKeyboardButton) [][]echotron.InlineKeyboardButton {
|
||||
var buttons [][]echotron.InlineKeyboardButton
|
||||
|
||||
// Блок редактирования контента
|
||||
@@ -369,7 +484,6 @@ func (e *CreativeEditorFields) ShowManagementPanel(b *bot.Bot, confirmButtonText
|
||||
Button("✎ Текст", "edit_text"),
|
||||
Button("+ Медиа", "add_media"),
|
||||
))
|
||||
// Добавление кнопки сразу под основным блоком
|
||||
buttons = append(buttons, Row(Button("+ Добавить кнопку", "add_button")))
|
||||
|
||||
// Кнопка удаления медиа (если медиа добавлено)
|
||||
@@ -405,18 +519,19 @@ func (e *CreativeEditorFields) ShowManagementPanel(b *bot.Bot, confirmButtonText
|
||||
}
|
||||
|
||||
// Финальные кнопки
|
||||
cancelLabel := "← " + cancelText
|
||||
if e.Text != nil {
|
||||
buttons = append(buttons, Row(
|
||||
Button("← Назад", cancelCallback),
|
||||
Button(confirmButtonText, confirmCallback),
|
||||
Button(cancelLabel, cancelCallback),
|
||||
Button(confirmText, confirmCallback),
|
||||
))
|
||||
} else {
|
||||
buttons = append(buttons, Row(
|
||||
Button("← Назад", cancelCallback),
|
||||
Button(cancelLabel, cancelCallback),
|
||||
))
|
||||
}
|
||||
|
||||
e.ShowControlPanel(b, text, buttons)
|
||||
return buttons
|
||||
}
|
||||
|
||||
// ShowControlPanel редактирует панель управления с произвольным текстом и кнопками
|
||||
@@ -428,211 +543,14 @@ func (e *CreativeEditorFields) ShowControlPanel(b *bot.Bot, text string, buttons
|
||||
// ВАЖНО: Сохраняем копию значения, а не указатель на переменную!
|
||||
controlPanelMsgID := b.LastMessageID
|
||||
e.ControlPanelMessageID = &controlPanelMsgID
|
||||
log.Info().Int("control_panel_msg_id", *e.ControlPanelMessageID).Msg("Control panel sent")
|
||||
} else {
|
||||
// Редактируем существующую панель
|
||||
log.Info().Int("control_panel_msg_id", *e.ControlPanelMessageID).Msg("Editing control panel")
|
||||
|
||||
// Временно заменяем LastMessageID на ID панели управления
|
||||
oldLastMessageID := b.LastMessageID
|
||||
b.LastMessageID = *e.ControlPanelMessageID
|
||||
defer func() { b.LastMessageID = oldLastMessageID }()
|
||||
|
||||
keyboard := Keyboard(buttons...)
|
||||
b.Edit(text, keyboard)
|
||||
|
||||
// Восстанавливаем оригинальный LastMessageID
|
||||
b.LastMessageID = oldLastMessageID
|
||||
log.Info().Msg("Control panel updated")
|
||||
}
|
||||
}
|
||||
|
||||
// GetFormattedText извлекает форматированный текст из сообщения с entities
|
||||
func (e *CreativeEditorFields) GetFormattedText(message *echotron.Message) string {
|
||||
// Определяем откуда брать текст и entities
|
||||
var text string
|
||||
var entities []*echotron.MessageEntity
|
||||
|
||||
if message.Text != "" {
|
||||
text = message.Text
|
||||
entities = message.Entities
|
||||
} else if message.Caption != "" {
|
||||
text = message.Caption
|
||||
entities = message.CaptionEntities
|
||||
}
|
||||
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Если нет entities - возвращаем текст как есть
|
||||
if len(entities) == 0 {
|
||||
return text
|
||||
}
|
||||
|
||||
type tagSpan struct {
|
||||
open string
|
||||
close string
|
||||
start int
|
||||
end int
|
||||
len int
|
||||
}
|
||||
|
||||
// Преобразуем текст в руны для правильной работы с UTF-8
|
||||
runes := []rune(text)
|
||||
|
||||
// Сначала находим все url entities, чтобы исключить перекрывающиеся форматирования
|
||||
urlRanges := make([][2]int, 0)
|
||||
// Также отмечаем диапазоны, которые нужно полностью исключить из текста (простые url ссылки)
|
||||
skipRanges := make(map[[2]int]bool)
|
||||
|
||||
for _, entity := range entities {
|
||||
if entity.Type == "url" || entity.Type == "text_link" {
|
||||
urlRanges = append(urlRanges, [2]int{entity.Offset, entity.Offset + entity.Length})
|
||||
// Для простых url (не text_link) с пригласительными ссылками - пропускаем текст URL
|
||||
// Создаем пустой <a class="tg-link"></a>, а сам URL не сохраняем
|
||||
if entity.Type == "url" {
|
||||
entityText := ""
|
||||
if entity.Offset+entity.Length <= len(runes) {
|
||||
entityText = string(runes[entity.Offset : entity.Offset+entity.Length])
|
||||
}
|
||||
if strings.Contains(entityText, "t.me/+") || strings.Contains(entityText, "t.me/joinchat/") {
|
||||
skipRanges[[2]int{entity.Offset, entity.Offset + entity.Length}] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем, находится ли entity внутри URL
|
||||
isInsideURL := func(offset, length int) bool {
|
||||
for _, urlRange := range urlRanges {
|
||||
// Если entity полностью внутри URL (но не сам URL)
|
||||
if offset > urlRange[0] && offset+length <= urlRange[1] {
|
||||
return true
|
||||
}
|
||||
// Если entity пересекается с URL
|
||||
if offset < urlRange[1] && offset+length > urlRange[0] && (offset != urlRange[0] || length != urlRange[1]-urlRange[0]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var spans []tagSpan
|
||||
for _, entity := range entities {
|
||||
entityText := ""
|
||||
if entity.Offset+entity.Length <= len(runes) {
|
||||
entityText = string(runes[entity.Offset : entity.Offset+entity.Length])
|
||||
}
|
||||
|
||||
// Пропускаем форматирование (bold, italic, etc), если оно находится внутри URL
|
||||
if entity.Type != "url" && entity.Type != "text_link" && isInsideURL(entity.Offset, entity.Length) {
|
||||
continue
|
||||
}
|
||||
|
||||
var openTag, closeTag string
|
||||
switch entity.Type {
|
||||
case "bold":
|
||||
openTag, closeTag = "<b>", "</b>"
|
||||
case "italic":
|
||||
openTag, closeTag = "<i>", "</i>"
|
||||
case "underline":
|
||||
openTag, closeTag = "<u>", "</u>"
|
||||
case "strikethrough":
|
||||
openTag, closeTag = "<s>", "</s>"
|
||||
case "code":
|
||||
openTag, closeTag = "<code>", "</code>"
|
||||
case "pre":
|
||||
openTag, closeTag = "<pre>", "</pre>"
|
||||
case "url":
|
||||
// Конвертируем простые URL в HTML-ссылки
|
||||
// Для пригласительных ссылок (t.me/+ или t.me/joinchat/) используем пустой тег
|
||||
if strings.Contains(entityText, "t.me/+") || strings.Contains(entityText, "t.me/joinchat/") {
|
||||
// Пригласительная ссылка - создаем пустой <a class="tg-link"></a>
|
||||
// Текст ссылки будет пропущен при рендеринге (см. skipRanges)
|
||||
openTag = `<a class="tg-link">`
|
||||
closeTag = "</a>"
|
||||
} else {
|
||||
// Обычная ссылка - оставляем как есть (ссылка на себя)
|
||||
openTag = fmt.Sprintf("<a href=\"%s\">", entityText)
|
||||
closeTag = "</a>"
|
||||
}
|
||||
case "text_link":
|
||||
if entity.URL != "" {
|
||||
// Проверяем, является ли URL пригласительной ссылкой
|
||||
if strings.Contains(entity.URL, "t.me/+") || strings.Contains(entity.URL, "t.me/joinchat/") {
|
||||
openTag = `<a class="tg-link">`
|
||||
closeTag = "</a>"
|
||||
} else {
|
||||
openTag = fmt.Sprintf("<a href=\"%s\">", entity.URL)
|
||||
closeTag = "</a>"
|
||||
}
|
||||
}
|
||||
default:
|
||||
_ = entityText
|
||||
}
|
||||
|
||||
if openTag != "" && closeTag != "" {
|
||||
spans = append(spans, tagSpan{
|
||||
open: openTag,
|
||||
close: closeTag,
|
||||
start: entity.Offset,
|
||||
end: entity.Offset + entity.Length,
|
||||
len: entity.Length,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
opens := make(map[int][]tagSpan)
|
||||
closes := make(map[int][]tagSpan)
|
||||
for _, span := range spans {
|
||||
opens[span.start] = append(opens[span.start], span)
|
||||
closes[span.end] = append(closes[span.end], span)
|
||||
}
|
||||
|
||||
// Функция для проверки, находится ли позиция в skipRanges
|
||||
isInSkipRange := func(pos int) bool {
|
||||
for skipRange := range skipRanges {
|
||||
if pos >= skipRange[0] && pos < skipRange[1] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Пишем текст один раз, вставляя HTML-теги по позициям
|
||||
// и экранируя HTML-спецсимволы
|
||||
var result strings.Builder
|
||||
for i := 0; i <= len(runes); i++ {
|
||||
if closing, ok := closes[i]; ok {
|
||||
sort.Slice(closing, func(a, b int) bool { return closing[a].len < closing[b].len })
|
||||
for _, span := range closing {
|
||||
result.WriteString(span.close)
|
||||
}
|
||||
}
|
||||
if opening, ok := opens[i]; ok {
|
||||
sort.Slice(opening, func(a, b int) bool { return opening[a].len > opening[b].len })
|
||||
for _, span := range opening {
|
||||
result.WriteString(span.open)
|
||||
}
|
||||
}
|
||||
if i < len(runes) {
|
||||
// Пропускаем символы, которые находятся в skipRanges (текст пригласительных ссылок)
|
||||
if isInSkipRange(i) {
|
||||
continue
|
||||
}
|
||||
// Экранируем HTML-спецсимволы
|
||||
switch runes[i] {
|
||||
case '<':
|
||||
result.WriteString("<")
|
||||
case '>':
|
||||
result.WriteString(">")
|
||||
case '&':
|
||||
result.WriteString("&")
|
||||
default:
|
||||
result.WriteRune(runes[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user