Skip to content

Commit

Permalink
added gif support
Browse files Browse the repository at this point in the history
  • Loading branch information
Dennis Fricke committed Aug 30, 2021
1 parent 357e4ec commit 6e769ae
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 21 deletions.
23 changes: 18 additions & 5 deletions discord/discord_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/bwmarrin/discordgo"
"regexp"
"slack2discord/helper"
"slack2discord/image"
"slack2discord/model"
"strings"
"time"
Expand Down Expand Up @@ -53,8 +54,12 @@ func (c Client) mapAttachments(attachments []*discordgo.MessageAttachment) []mod
if err != nil {
panic(err)
}
data, err := image.TranslateToReadableImageForAll(download)
if err != nil {
panic(err)
}
result = append(result, model.Attachment{
Data: bytes.NewReader(download),
Data: bytes.NewReader(data),
ContentType: "",
Name: attachment.Filename,
})
Expand All @@ -70,7 +75,7 @@ func (c Client) cleanupMessage(text string, message *discordgo.Message) string {
for mi := range message.Mentions {
mention := message.Mentions[mi]
if mention.ID == match[1] {
text = strings.Replace(text, match[0], "@" + mention.Username, -1)
text = strings.Replace(text, match[0], "@"+mention.Username, -1)
}
}
}
Expand Down Expand Up @@ -113,16 +118,24 @@ func (c Client) SendMessage(message model.Message) {
Reader: attachment.Data,
})
}
messageText := message.User + ": " + message.Text
if message.DoNotPrintUser {
messageText = message.Text
}
_, err := c.DiscordClient.ChannelMessageSendComplex(c.ChannelId, &discordgo.MessageSend{
Content: message.User + ": " + message.Text,
Files: files,
Content: messageText,
Files: files,
})
if err != nil {
fmt.Println(err)
panic(err)
}
} else {
_, err := c.DiscordClient.ChannelMessageSend(c.ChannelId, message.User+": "+message.Text)
messageText := message.User + ": " + message.Text
if message.DoNotPrintUser {
messageText = message.Text
}
_, err := c.DiscordClient.ChannelMessageSend(c.ChannelId, messageText)
if err != nil {
panic(err)
}
Expand Down
86 changes: 86 additions & 0 deletions image/image_translator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package image

import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"io"
)

type InvalidFormatError struct {
}

func (e *InvalidFormatError) Error() string {
return fmt.Sprintf("Invalid image format")
}

func bufferStartsWith(buffer []byte, needle []byte) bool {
if len(buffer) < len(needle) {
return false
}
for i := range needle {
if buffer[i] != needle[i] {
return false
}
}
return true
}

func isJpegFile(buffer []byte) bool {
return bufferStartsWith(buffer, []byte{0xff, 0xd8, 0xff, 0xe0})
}

func isPngFile(buffer []byte) bool {
return bufferStartsWith(buffer, []byte{0x89, 0x50, 0x4e, 0x47})
}

func isGifFile(buffer []byte) bool {
return bufferStartsWith(buffer, []byte{0x47, 0x49, 0x46, 0x38})
}

func isBmpFile(buffer []byte) bool {
return bufferStartsWith(buffer, []byte{0x42, 0x4d})
}

func TranslatePngToJpeg(buffer []byte) ([]byte, error) {
decode, err := png.Decode(bytes.NewReader(buffer))
if err != nil {
return []byte{}, nil
}

newImg := image.NewRGBA(decode.Bounds())
draw.Draw(newImg, newImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)

draw.Draw(newImg, newImg.Bounds(), decode, decode.Bounds().Min, draw.Over)

buff := new(bytes.Buffer)
writer := io.Writer(buff)

var opt jpeg.Options
opt.Quality = 100

err = jpeg.Encode(writer, newImg, &opt)
if err != nil {
return []byte{}, nil
}

return buff.Bytes(), nil
}

func TranslateToReadableImageForAll(buffer []byte) ([]byte, error) {
if isJpegFile(buffer) {
return buffer, nil
}
if isPngFile(buffer) {
toJpeg, err := TranslatePngToJpeg(buffer)
return toJpeg, err
}
if isGifFile(buffer) {
return buffer, nil
}
return []byte{}, &InvalidFormatError{}
}
11 changes: 6 additions & 5 deletions model/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ type Attachment struct {
}

type Message struct {
Id string
Text string
User string
Time time.Time
Attachments []Attachment
Id string
Text string
User string
DoNotPrintUser bool
Time time.Time
Attachments []Attachment
}
44 changes: 33 additions & 11 deletions slack/slack_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@ import (
"github.com/slack-go/slack"
"regexp"
"slack2discord/helper"
"slack2discord/image"
"slack2discord/model"
"strconv"
"strings"
"time"
)

var fileMap = map[string]string {
"jpg": "image/jpeg",
var fileMap = map[string]string{
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"png": "image/png",
}

type Client struct {
Expand All @@ -24,6 +25,7 @@ type Client struct {
SlackClient *slack.Client
users map[string]string
ownUserId string
ownBotId string
}

func NewClient(token string, channelId string) *Client {
Expand All @@ -37,6 +39,7 @@ func NewClient(token string, channelId string) *Client {
panic(err)
}
c.ownUserId = identity.UserID
c.ownBotId = identity.BotID
return c
}

Expand All @@ -61,7 +64,7 @@ func (c Client) cleanupMessage(text string) string {
matches := regex.FindAllStringSubmatch(text, -1)
for i := range matches {
match := matches[i]
text = strings.Replace(text, match[0], "@" + c.GetUserName(match[1]), -1)
text = strings.Replace(text, match[0], "@"+c.GetUserName(match[1]), -1)
}
return text
}
Expand All @@ -87,19 +90,35 @@ func (c Client) mapAttachments(attachments []slack.File) []model.Attachment {
if err != nil {
panic(err)
}
data, err := image.TranslateToReadableImageForAll(download)
if err != nil {
panic(err)
}
filetype := "application/octet-stream"
if t, ok := fileMap[attachment.Filetype]; ok {
filetype = t
}
result = append(result, model.Attachment{
Data: bytes.NewReader(download),
Data: bytes.NewReader(data),
ContentType: filetype,
Name: attachment.Name,
})
}
return result
}

func (c Client) parseGiphyMessage(message slack.Message) model.Message {
imageBlock := message.Blocks.BlockSet[0]
return model.Message{
Id: message.Timestamp,
Text: imageBlock.(*slack.ImageBlock).ImageURL,
User: c.GetUserName(message.User),
DoNotPrintUser: true,
Time: formatTimestamp(message.Timestamp),
Attachments: []model.Attachment{},
}
}

func (c Client) GetNewMessages(last string) []model.Message {
var result []model.Message

Expand All @@ -116,9 +135,12 @@ func (c Client) GetNewMessages(last string) []model.Message {

for i := range history.Messages {
message := history.Messages[i]
if message.User == c.ownUserId || len(message.BotID) > 0 {
if message.User == c.ownUserId || message.BotID == c.ownBotId {
continue
}
if message.BotProfile != nil && message.BotProfile.Name == "giphy" {
result = append([]model.Message{c.parseGiphyMessage(message)}, result...)
}
result = append([]model.Message{{
Id: message.Timestamp,
Text: c.cleanupMessage(message.Text),
Expand All @@ -137,12 +159,12 @@ func (c Client) SendMessage(message model.Message) {
for i := range message.Attachments {
attachment := message.Attachments[i]
_, err := c.SlackClient.UploadFile(slack.FileUploadParameters{
Reader: attachment.Data,
Filename: "file",
Channels: []string{c.ChannelId},
Reader: attachment.Data,
Filename: "file",
Channels: []string{c.ChannelId},
InitialComment: comment,
Filetype: attachment.ContentType,
Title: message.User,
Filetype: attachment.ContentType,
Title: message.User,
})

comment = ""
Expand Down

0 comments on commit 6e769ae

Please sign in to comment.