From 3f06a40bd55b242c3c2540e8262b8b13e3e8afcf Mon Sep 17 00:00:00 2001 From: Wim Date: Fri, 17 Jan 2020 00:46:11 +0100 Subject: [PATCH] Support code snippets from msteams --- bridge/msteams/handler.go | 42 +++++++++++++++++++++++++++++++++++++++ bridge/msteams/msteams.go | 1 + 2 files changed, 43 insertions(+) diff --git a/bridge/msteams/handler.go b/bridge/msteams/handler.go index 8cccfe0c..c8f0c468 100644 --- a/bridge/msteams/handler.go +++ b/bridge/msteams/handler.go @@ -1,10 +1,14 @@ package bmsteams import ( + "encoding/json" "fmt" + "io/ioutil" + "strings" "github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/helper" + msgraph "github.com/yaegashi/msgraph.go/beta" ) @@ -50,6 +54,13 @@ func (b *Bmsteams) handleAttachments(rmsg *config.Message, msg msgraph.ChatMessa for _, a := range msg.Attachments { //remove the attachment tags from the text rmsg.Text = attachRE.ReplaceAllString(rmsg.Text, "") + + //handle a code snippet (code block) + if *a.ContentType == "application/vnd.microsoft.card.codesnippet" { + b.handleCodeSnippet(rmsg, a) + continue + } + //handle the download err := b.handleDownloadFile(rmsg, *a.Name, *a.ContentURL) if err != nil { @@ -57,3 +68,34 @@ func (b *Bmsteams) handleAttachments(rmsg *config.Message, msg msgraph.ChatMessa } } } + +type AttachContent struct { + Language string `json:"language"` + CodeSnippetURL string `json:"codeSnippetUrl"` +} + +func (b *Bmsteams) handleCodeSnippet(rmsg *config.Message, attach msgraph.ChatMessageAttachment) { + var content AttachContent + err := json.Unmarshal([]byte(*attach.Content), &content) + if err != nil { + b.Log.Errorf("unmarshal codesnippet failed: %s", err) + return + } + s := strings.Split(content.CodeSnippetURL, "/") + if len(s) != 13 { + b.Log.Errorf("codesnippetUrl has unexpected size: %s", content.CodeSnippetURL) + return + } + resp, err := b.gc.Teams().Request().Client().Get(content.CodeSnippetURL) + if err != nil { + b.Log.Errorf("retrieving snippet content failed:%s", err) + return + } + defer resp.Body.Close() + res, err := ioutil.ReadAll(resp.Body) + if err != nil { + b.Log.Errorf("reading snippet data failed: %s", err) + return + } + rmsg.Text = rmsg.Text + "\n```" + content.Language + "\n" + string(res) + "\n```\n" +} diff --git a/bridge/msteams/msteams.go b/bridge/msteams/msteams.go index da0e31ff..3633924a 100644 --- a/bridge/msteams/msteams.go +++ b/bridge/msteams/msteams.go @@ -120,6 +120,7 @@ func (b *Bmsteams) getMessages(channel string) ([]msgraph.ChatMessage, error) { return rct, nil } +//nolint:gocognit func (b *Bmsteams) poll(channelName string) { msgmap := make(map[string]time.Time) b.Log.Debug("getting initial messages")