telegram.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package integration
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "strconv"
  8. "unicode/utf16"
  9. "github.com/pkg/errors"
  10. apiv1 "github.com/usememos/memos/api/v1"
  11. "github.com/usememos/memos/plugin/telegram"
  12. "github.com/usememos/memos/store"
  13. )
  14. type TelegramHandler struct {
  15. store *store.Store
  16. }
  17. func NewTelegramHandler(store *store.Store) *TelegramHandler {
  18. return &TelegramHandler{store: store}
  19. }
  20. func (t *TelegramHandler) BotToken(ctx context.Context) string {
  21. return t.store.GetSystemSettingValueWithDefault(&ctx, apiv1.SystemSettingTelegramBotTokenName.String(), "")
  22. }
  23. const (
  24. workingMessage = "Working on sending your memo..."
  25. successMessage = "Success"
  26. )
  27. func (t *TelegramHandler) MessageHandle(ctx context.Context, bot *telegram.Bot, message telegram.Message, attachments []telegram.Attachment) error {
  28. reply, err := bot.SendReplyMessage(ctx, message.Chat.ID, message.MessageID, workingMessage)
  29. if err != nil {
  30. return errors.Wrap(err, "Failed to SendReplyMessage")
  31. }
  32. var creatorID int32
  33. userSettingList, err := t.store.ListUserSettings(ctx, &store.FindUserSetting{
  34. Key: apiv1.UserSettingTelegramUserIDKey.String(),
  35. })
  36. if err != nil {
  37. return errors.Wrap(err, "Failed to find userSettingList")
  38. }
  39. for _, userSetting := range userSettingList {
  40. var value string
  41. if err := json.Unmarshal([]byte(userSetting.Value), &value); err != nil {
  42. continue
  43. }
  44. if value == strconv.FormatInt(message.From.ID, 10) {
  45. creatorID = userSetting.UserID
  46. }
  47. }
  48. if creatorID == 0 {
  49. _, err := bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Please set your telegram userid %d in UserSetting of Memos", message.From.ID), nil)
  50. return err
  51. }
  52. create := &store.Memo{
  53. CreatorID: creatorID,
  54. Visibility: store.Private,
  55. }
  56. if message.Text != nil {
  57. create.Content = convertToMarkdown(*message.Text, message.Entities)
  58. }
  59. if message.Caption != nil {
  60. create.Content = convertToMarkdown(*message.Caption, message.CaptionEntities)
  61. }
  62. if message.ForwardFromChat != nil {
  63. create.Content += fmt.Sprintf("\n\n[Message link](%s)", message.GetMessageLink())
  64. }
  65. memoMessage, err := t.store.CreateMemo(ctx, create)
  66. if err != nil {
  67. _, err := bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Failed to CreateMemo: %s", err), nil)
  68. return err
  69. }
  70. // create resources
  71. for _, attachment := range attachments {
  72. // Fill the common field of create
  73. create := store.Resource{
  74. CreatorID: creatorID,
  75. Filename: attachment.FileName,
  76. Type: attachment.GetMimeType(),
  77. Size: attachment.FileSize,
  78. }
  79. err := apiv1.SaveResourceBlob(ctx, t.store, &create, bytes.NewReader(attachment.Data))
  80. if err != nil {
  81. _, err := bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Failed to SaveResourceBlob: %s", err), nil)
  82. return err
  83. }
  84. resource, err := t.store.CreateResource(ctx, &create)
  85. if err != nil {
  86. _, err := bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Failed to CreateResource: %s", err), nil)
  87. return err
  88. }
  89. _, err = t.store.UpsertMemoResource(ctx, &store.UpsertMemoResource{
  90. MemoID: memoMessage.ID,
  91. ResourceID: resource.ID,
  92. })
  93. if err != nil {
  94. _, err := bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Failed to UpsertMemoResource: %s", err), nil)
  95. return err
  96. }
  97. }
  98. keyboard := generateKeyboardForMemoID(memoMessage.ID)
  99. _, err = bot.EditMessage(ctx, message.Chat.ID, reply.MessageID, fmt.Sprintf("Saved as %s Memo %d", memoMessage.Visibility, memoMessage.ID), keyboard)
  100. return err
  101. }
  102. func (t *TelegramHandler) CallbackQueryHandle(ctx context.Context, bot *telegram.Bot, callbackQuery telegram.CallbackQuery) error {
  103. var memoID int32
  104. var visibility store.Visibility
  105. n, err := fmt.Sscanf(callbackQuery.Data, "%s %d", &visibility, &memoID)
  106. if err != nil || n != 2 {
  107. return bot.AnswerCallbackQuery(ctx, callbackQuery.ID, fmt.Sprintf("Failed to parse callbackQuery.Data %s", callbackQuery.Data))
  108. }
  109. update := store.UpdateMemo{
  110. ID: memoID,
  111. Visibility: &visibility,
  112. }
  113. err = t.store.UpdateMemo(ctx, &update)
  114. if err != nil {
  115. return bot.AnswerCallbackQuery(ctx, callbackQuery.ID, fmt.Sprintf("Failed to call UpdateMemo %s", err))
  116. }
  117. keyboard := generateKeyboardForMemoID(memoID)
  118. _, err = bot.EditMessage(ctx, callbackQuery.Message.Chat.ID, callbackQuery.Message.MessageID, fmt.Sprintf("Saved as %s Memo %d", visibility, memoID), keyboard)
  119. if err != nil {
  120. return bot.AnswerCallbackQuery(ctx, callbackQuery.ID, fmt.Sprintf("Failed to EditMessage %s", err))
  121. }
  122. return bot.AnswerCallbackQuery(ctx, callbackQuery.ID, fmt.Sprintf("Success changing Memo %d to %s", memoID, visibility))
  123. }
  124. func generateKeyboardForMemoID(id int32) [][]telegram.InlineKeyboardButton {
  125. allVisibility := []store.Visibility{
  126. store.Public,
  127. store.Protected,
  128. store.Private,
  129. }
  130. buttons := make([]telegram.InlineKeyboardButton, 0, len(allVisibility))
  131. for _, v := range allVisibility {
  132. button := telegram.InlineKeyboardButton{
  133. Text: v.String(),
  134. CallbackData: fmt.Sprintf("%s %d", v, id),
  135. }
  136. buttons = append(buttons, button)
  137. }
  138. return [][]telegram.InlineKeyboardButton{buttons}
  139. }
  140. func convertToMarkdown(text string, messageEntities []telegram.MessageEntity) string {
  141. insertions := make(map[int]string)
  142. for _, e := range messageEntities {
  143. var before, after string
  144. // this is supported by the current markdown
  145. switch e.Type {
  146. case telegram.Bold:
  147. before = "**"
  148. after = "**"
  149. case telegram.Italic:
  150. before = "*"
  151. after = "*"
  152. case telegram.Strikethrough:
  153. before = "~~"
  154. after = "~~"
  155. case telegram.Code:
  156. before = "`"
  157. after = "`"
  158. case telegram.Pre:
  159. before = "```" + e.Language
  160. after = "```"
  161. case telegram.TextLink:
  162. before = "["
  163. after = fmt.Sprintf(`](%s)`, e.URL)
  164. }
  165. if before != "" {
  166. insertions[e.Offset] += before
  167. insertions[e.Offset+e.Length] = after + insertions[e.Offset+e.Length]
  168. }
  169. }
  170. input := []rune(text)
  171. var output []rune
  172. utf16pos := 0
  173. for i := 0; i < len(input); i++ {
  174. output = append(output, []rune(insertions[utf16pos])...)
  175. output = append(output, input[i])
  176. utf16pos += len(utf16.Encode([]rune{input[i]}))
  177. }
  178. output = append(output, []rune(insertions[utf16pos])...)
  179. return string(output)
  180. }