Skip to content

Commit

Permalink
Fixed #13
Browse files Browse the repository at this point in the history
Probably?
  • Loading branch information
HirbodBehnam committed Aug 3, 2024
1 parent cce2421 commit 61f53cc
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- goarch: "386"
goos: darwin
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: wangyoucao577/go-release-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
Expand Down
26 changes: 14 additions & 12 deletions internal/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"RedditDownloaderBot/pkg/reddit"
"RedditDownloaderBot/pkg/util"
"encoding/json"
"errors"
"log"
"strings"

Expand Down Expand Up @@ -74,12 +75,12 @@ func fetchPostDetailsAndSend(text string, chatID int64, messageID int) {
// Check the result type
msg := tgbotapi.NewMessage(chatID, "")
msg.ReplyToMessageID = messageID
msg.ParseMode = Markdown
msg.ParseMode = MarkdownV2
switch data := result.(type) {
case reddit.FetchResultText:
msg.Text = data.Title + "\n" + data.Text + "\n" + "[" + data.Title + "](text)"
msg.Text = addLinkIfNeeded(data.Title+"\n"+data.Text, text)
case reddit.FetchResultComment:
msg.Text = data.Text + "\n" + "[" + data.Text + "](text)"
msg.Text = addLinkIfNeeded(data.Text, text)
case reddit.FetchResultMedia:
if len(data.Medias) == 0 {
msg.Text = "No media found!"
Expand All @@ -90,13 +91,13 @@ func fetchPostDetailsAndSend(text string, chatID int64, messageID int) {
if len(data.Medias) == 1 && data.Type != reddit.FetchResultMediaTypePhoto {
switch data.Type {
case reddit.FetchResultMediaTypeGif:
handleGifUpload(data.Medias[0].Link, data.Title, data.ThumbnailLink, chatID)
handleGifUpload(data.Medias[0].Link, data.Title, data.ThumbnailLink, text, chatID)
return
case reddit.FetchResultMediaTypeVideo:
// If the video does have an audio, ask user if they want the audio
if _, hasAudio := data.HasAudio(); !hasAudio {
// Otherwise, just download the video
handleVideoUpload(data.Medias[0].Link, "", data.Title, data.ThumbnailLink, data.Duration, chatID)
handleVideoUpload(data.Medias[0].Link, "", data.Title, data.ThumbnailLink, text, data.Duration, chatID)
return
}
}
Expand All @@ -115,6 +116,7 @@ func fetchPostDetailsAndSend(text string, chatID int64, messageID int) {
}
// Insert the id in cache
err := CallbackCache.SetMediaCache(idString, cache.CallbackDataCached{
PostLink: text,
Links: data.Medias.ToLinkMap(),
Title: data.Title,
ThumbnailLink: data.ThumbnailLink,
Expand Down Expand Up @@ -175,15 +177,15 @@ func handleCallback(dataString string, chatID int64, msgId int) {
}
// Get the cache from database
cachedData, err := CallbackCache.GetAndDeleteMediaCache(data.ID)
if err == cache.NotFoundErr {
if errors.Is(err, cache.NotFoundErr) {
// Check albums
var album reddit.FetchResultAlbum
album, err = CallbackCache.GetAndDeleteAlbumCache(data.ID)
if err == nil {
handleAlbumUpload(album, chatID, data.Mode == CallbackButtonDataModeFile)
return
} else if err == cache.NotFoundErr {
// It does not exists...
} else if errors.Is(err, cache.NotFoundErr) {
// It does not exist...
bot.Send(tgbotapi.NewMessage(chatID, "Please resend the link to bot"))
return
}
Expand All @@ -204,15 +206,15 @@ func handleCallback(dataString string, chatID int64, msgId int) {
// Check the media type
switch cachedData.Type {
case reddit.FetchResultMediaTypeGif:
handleGifUpload(link, cachedData.Title, cachedData.ThumbnailLink, chatID)
handleGifUpload(link, cachedData.Title, cachedData.ThumbnailLink, cachedData.PostLink, chatID)
case reddit.FetchResultMediaTypePhoto:
handlePhotoUpload(link, cachedData.Title, cachedData.ThumbnailLink, chatID, data.Mode == CallbackButtonDataModePhoto)
handlePhotoUpload(link, cachedData.Title, cachedData.ThumbnailLink, cachedData.PostLink, chatID, data.Mode == CallbackButtonDataModePhoto)
case reddit.FetchResultMediaTypeVideo:
if data.LinkKey == cachedData.AudioIndex {
handleAudioUpload(link, cachedData.Title, cachedData.Duration, chatID)
handleAudioUpload(link, cachedData.Title, cachedData.PostLink, cachedData.Duration, chatID)
} else {
audioURL := cachedData.Links[cachedData.AudioIndex]
handleVideoUpload(link, audioURL, cachedData.Title, cachedData.ThumbnailLink, cachedData.Duration, chatID)
handleVideoUpload(link, audioURL, cachedData.Title, cachedData.ThumbnailLink, cachedData.PostLink, cachedData.Duration, chatID)
}
}
}
4 changes: 2 additions & 2 deletions internal/bot/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ const PhotoMaxUploadSize = 10 * 1000 * 1000
// Otherwise the telegram will show them without one
const NoThumbnailNeededSize = 10 * 1000 * 1000

// Markdown is the styling format used in telegram messages
const Markdown = "Markdown"
// MarkdownV2 is the styling format used in telegram messages
const MarkdownV2 = "MarkdownV2"
23 changes: 14 additions & 9 deletions internal/bot/uploader.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

// handleGifUpload downloads a gif and then uploads it to Telegram
func handleGifUpload(gifUrl, title, thumbnailUrl string, chatID int64) {
func handleGifUpload(gifUrl, title, thumbnailUrl, postUrl string, chatID int64) {
// Inform the user we are doing some shit
stopReportChannel := statusReporter(chatID, "upload_video")
defer close(stopReportChannel)
Expand Down Expand Up @@ -47,7 +47,8 @@ func handleGifUpload(gifUrl, title, thumbnailUrl string, chatID int64) {
}
// Upload it
msg := tgbotapi.NewAnimation(chatID, telegramUploadOsFile{tmpFile})
msg.Caption = title + "\n" + "[" + title + "](text)"
msg.Caption = addLinkIfNeeded(escapeMarkdown(title), postUrl)
msg.ParseMode = MarkdownV2
if tmpThumbnailFile != nil {
msg.Thumb = telegramUploadOsFile{tmpThumbnailFile}
}
Expand All @@ -60,7 +61,7 @@ func handleGifUpload(gifUrl, title, thumbnailUrl string, chatID int64) {
}

// handleVideoUpload downloads a video and then uploads it to Telegram
func handleVideoUpload(vidUrl, audioUrl, title, thumbnailUrl string, duration int, chatID int64) {
func handleVideoUpload(vidUrl, audioUrl, title, thumbnailUrl, postUrl string, duration int, chatID int64) {
// Inform the user we are doing some shit
stopReportChannel := statusReporter(chatID, "upload_video")
defer close(stopReportChannel)
Expand Down Expand Up @@ -97,9 +98,10 @@ func handleVideoUpload(vidUrl, audioUrl, title, thumbnailUrl string, duration in
}
// Upload it
msg := tgbotapi.NewVideo(chatID, telegramUploadOsFile{tmpFile})
msg.Caption = title + "\n" + "[" + title + "](text)"
msg.Caption = addLinkIfNeeded(escapeMarkdown(title), postUrl)
msg.Duration = duration
msg.SupportsStreaming = true
msg.ParseMode = MarkdownV2
if tmpThumbnailFile != nil {
msg.Thumb = telegramUploadOsFile{tmpThumbnailFile}
}
Expand All @@ -112,7 +114,7 @@ func handleVideoUpload(vidUrl, audioUrl, title, thumbnailUrl string, duration in
}

// handleVideoUpload downloads a photo and then uploads it to Telegram
func handlePhotoUpload(photoUrl, title, thumbnailUrl string, chatID int64, asPhoto bool) {
func handlePhotoUpload(photoUrl, title, thumbnailUrl, postUrl string, chatID int64, asPhoto bool) {
// Inform the user we are doing some shit
var stopReportChannel chan struct{}
if asPhoto {
Expand Down Expand Up @@ -155,14 +157,16 @@ func handlePhotoUpload(photoUrl, title, thumbnailUrl string, chatID int64, asPho
var msg tgbotapi.Chattable
if asPhoto {
photo := tgbotapi.NewPhoto(chatID, telegramUploadOsFile{tmpFile})
photo.Caption = title
photo.Caption = addLinkIfNeeded(escapeMarkdown(title), postUrl)
photo.ParseMode = MarkdownV2
if tmpThumbnailFile != nil {
photo.Thumb = telegramUploadOsFile{tmpThumbnailFile}
}
msg = photo
} else {
photo := tgbotapi.NewDocument(chatID, telegramUploadOsFile{tmpFile})
photo.Caption = title
photo.Caption = addLinkIfNeeded(escapeMarkdown(title), postUrl)
photo.ParseMode = MarkdownV2
if tmpThumbnailFile != nil {
photo.Thumb = telegramUploadOsFile{tmpThumbnailFile}
}
Expand Down Expand Up @@ -278,7 +282,7 @@ func handleAlbumUpload(album reddit.FetchResultAlbum, chatID int64, asFile bool)
}

// handleAudioUpload simply downloads then uploads an audio to Telegram
func handleAudioUpload(audioURL, title string, duration int, chatID int64) {
func handleAudioUpload(audioURL, title, postUrl string, duration int, chatID int64) {
// Send status
stopReportChannel := statusReporter(chatID, "upload_voice")
defer close(stopReportChannel)
Expand All @@ -294,7 +298,8 @@ func handleAudioUpload(audioURL, title string, duration int, chatID int64) {
}()
// Simply upload it to telegram
msg := tgbotapi.NewAudio(chatID, telegramUploadOsFile{audioFile})
msg.Caption = title + "\n" + "[" + title + "](text)"
msg.Caption = addLinkIfNeeded(escapeMarkdown(title), postUrl)
msg.ParseMode = MarkdownV2
msg.Duration = duration
_, err = bot.Send(msg)
if err != nil {
Expand Down
22 changes: 22 additions & 0 deletions internal/bot/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@ package bot

import (
"RedditDownloaderBot/pkg/reddit"
"RedditDownloaderBot/pkg/util"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"io"
"os"
"strings"
)

// If this value is false, we will not add the link of the post to each message caption.
var disableIncludeLinkInCaption = util.ParseEnvironmentVariableBool("DISABLE_LINK_IN_CAPTION")

// The characters which needs to be escaped based on
// https://core.telegram.org/bots/api#formatting-options
var markdownEscaper = strings.NewReplacer("_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>", "#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|", "\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!")

// createPhotoInlineKeyboard creates inline keyboards to get the quality info of a photo
// Each row represents a quality and each row has two columns: Send as photo or send as file
// The id must match the ID in the mediaCache
Expand Down Expand Up @@ -62,6 +71,19 @@ func createVideoInlineKeyboard(id string, medias reddit.FetchResultMedia) tgbota
return tgbotapi.InlineKeyboardMarkup{InlineKeyboard: rows}
}

// Adds the link of the post to a text if needed (the INCLUDE_LINK is set)
func addLinkIfNeeded(text, link string) string {
if disableIncludeLinkInCaption {
return text
}
return text + "\n\n" + "[🔗 Link](" + link + ")"
}

// escapeMarkdown will escape the characters which are not ok in markdown
func escapeMarkdown(text string) string {
return markdownEscaper.Replace(text)
}

// telegramUploadOsFile is wrapper for os.File in order to make it uploadable in Telegram
type telegramUploadOsFile struct {
*os.File
Expand Down
2 changes: 2 additions & 0 deletions internal/cache/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import "RedditDownloaderBot/pkg/reddit"
// CallbackDataCached is the data we store associated with an ID which is CallbackButtonData.ID
// We store this type in mediaCache
type CallbackDataCached struct {
// The link of the post itself
PostLink string
// The list of links which the one in CallbackButtonData.LinkKey is used
Links map[int]string
// Title of the post
Expand Down

0 comments on commit 61f53cc

Please sign in to comment.