-
Notifications
You must be signed in to change notification settings - Fork 621
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add initial Microsoft Teams support #967
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
26e2e14
Vendor libraries needed for msteams support
42wim 850b64c
Add initial Microsoft Teams support
42wim 0118bd3
Support receiving attachments from msteams
42wim d6a532b
Support threading from other bridges to msteams
42wim f4f804b
Make linter happy and cleanup (msteams)
42wim 3bc9fc9
Add scopes again
42wim ff0b926
Support code snippets from msteams
42wim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
The diff you're trying to view is too large. We only load the first 3000 changed files.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
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" | ||
) | ||
|
||
func (b *Bmsteams) findFile(weburl string) (string, error) { | ||
itemRB, err := b.gc.GetDriveItemByURL(b.ctx, weburl) | ||
if err != nil { | ||
return "", err | ||
} | ||
itemRB.Workbook().Worksheets() | ||
b.gc.Workbooks() | ||
item, err := itemRB.Request().Get(b.ctx) | ||
if err != nil { | ||
return "", err | ||
} | ||
if url, ok := item.GetAdditionalData("@microsoft.graph.downloadUrl"); ok { | ||
return url.(string), nil | ||
} | ||
return "", nil | ||
} | ||
|
||
// handleDownloadFile handles file download | ||
func (b *Bmsteams) handleDownloadFile(rmsg *config.Message, filename, weburl string) error { | ||
realURL, err := b.findFile(weburl) | ||
if err != nil { | ||
return err | ||
} | ||
// Actually download the file. | ||
data, err := helper.DownloadFile(realURL) | ||
if err != nil { | ||
return fmt.Errorf("download %s failed %#v", weburl, err) | ||
} | ||
|
||
// If a comment is attached to the file(s) it is in the 'Text' field of the teams messge event | ||
// and should be added as comment to only one of the files. We reset the 'Text' field to ensure | ||
// that the comment is not duplicated. | ||
comment := rmsg.Text | ||
rmsg.Text = "" | ||
helper.HandleDownloadData(b.Log, rmsg, filename, comment, weburl, data, b.General) | ||
return nil | ||
} | ||
|
||
func (b *Bmsteams) handleAttachments(rmsg *config.Message, msg msgraph.ChatMessage) { | ||
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 { | ||
b.Log.Errorf("download of %s failed: %s", *a.Name, err) | ||
} | ||
} | ||
} | ||
|
||
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" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
package bmsteams | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"regexp" | ||
"strings" | ||
"time" | ||
|
||
"github.com/42wim/matterbridge/bridge" | ||
"github.com/42wim/matterbridge/bridge/config" | ||
|
||
// "github.com/davecgh/go-spew/spew" | ||
"github.com/mattn/godown" | ||
msgraph "github.com/yaegashi/msgraph.go/beta" | ||
"github.com/yaegashi/msgraph.go/msauth" | ||
|
||
"golang.org/x/oauth2" | ||
) | ||
|
||
var defaultScopes = []string{"openid", "profile", "offline_access", "Group.Read.All", "Group.ReadWrite.All"} | ||
var attachRE = regexp.MustCompile(`<attachment id=.*?attachment>`) | ||
|
||
type Bmsteams struct { | ||
gc *msgraph.GraphServiceRequestBuilder | ||
ctx context.Context | ||
botID string | ||
*bridge.Config | ||
} | ||
|
||
func New(cfg *bridge.Config) bridge.Bridger { | ||
return &Bmsteams{Config: cfg} | ||
} | ||
|
||
func (b *Bmsteams) Connect() error { | ||
tokenCachePath := b.GetString("sessionFile") | ||
if tokenCachePath == "" { | ||
tokenCachePath = "msteams_session.json" | ||
} | ||
ctx := context.Background() | ||
m := msauth.NewManager() | ||
m.LoadFile(tokenCachePath) //nolint:errcheck | ||
ts, err := m.DeviceAuthorizationGrant(ctx, b.GetString("TenantID"), b.GetString("ClientID"), defaultScopes, nil) | ||
if err != nil { | ||
return err | ||
} | ||
err = m.SaveFile(tokenCachePath) | ||
if err != nil { | ||
b.Log.Errorf("Couldn't save sessionfile in %s: %s", tokenCachePath, err) | ||
} | ||
// make file readable only for matterbridge user | ||
err = os.Chmod(tokenCachePath, 0600) | ||
if err != nil { | ||
b.Log.Errorf("Couldn't change permissions for %s: %s", tokenCachePath, err) | ||
} | ||
httpClient := oauth2.NewClient(ctx, ts) | ||
graphClient := msgraph.NewClient(httpClient) | ||
b.gc = graphClient | ||
b.ctx = ctx | ||
|
||
err = b.setBotID() | ||
if err != nil { | ||
return err | ||
} | ||
b.Log.Info("Connection succeeded") | ||
return nil | ||
} | ||
|
||
func (b *Bmsteams) Disconnect() error { | ||
return nil | ||
} | ||
|
||
func (b *Bmsteams) JoinChannel(channel config.ChannelInfo) error { | ||
go b.poll(channel.Name) | ||
return nil | ||
} | ||
|
||
func (b *Bmsteams) Send(msg config.Message) (string, error) { | ||
b.Log.Debugf("=> Receiving %#v", msg) | ||
if msg.ParentID != "" && msg.ParentID != "msg-parent-not-found" { | ||
return b.sendReply(msg) | ||
} | ||
if msg.ParentID == "msg-parent-not-found" { | ||
msg.ParentID = "" | ||
msg.Text = fmt.Sprintf("[thread]: %s", msg.Text) | ||
} | ||
ct := b.gc.Teams().ID(b.GetString("TeamID")).Channels().ID(msg.Channel).Messages().Request() | ||
text := msg.Username + msg.Text | ||
content := &msgraph.ItemBody{Content: &text} | ||
rmsg := &msgraph.ChatMessage{Body: content} | ||
res, err := ct.Add(b.ctx, rmsg) | ||
if err != nil { | ||
return "", err | ||
} | ||
return *res.ID, nil | ||
} | ||
|
||
func (b *Bmsteams) sendReply(msg config.Message) (string, error) { | ||
ct := b.gc.Teams().ID(b.GetString("TeamID")).Channels().ID(msg.Channel).Messages().ID(msg.ParentID).Replies().Request() | ||
// Handle prefix hint for unthreaded messages. | ||
|
||
text := msg.Username + msg.Text | ||
content := &msgraph.ItemBody{Content: &text} | ||
rmsg := &msgraph.ChatMessage{Body: content} | ||
res, err := ct.Add(b.ctx, rmsg) | ||
if err != nil { | ||
return "", err | ||
} | ||
return *res.ID, nil | ||
} | ||
|
||
func (b *Bmsteams) getMessages(channel string) ([]msgraph.ChatMessage, error) { | ||
ct := b.gc.Teams().ID(b.GetString("TeamID")).Channels().ID(channel).Messages().Request() | ||
rct, err := ct.Get(b.ctx) | ||
if err != nil { | ||
return nil, err | ||
} | ||
b.Log.Debugf("got %#v messages", len(rct)) | ||
return rct, nil | ||
} | ||
|
||
//nolint:gocognit | ||
func (b *Bmsteams) poll(channelName string) { | ||
msgmap := make(map[string]time.Time) | ||
b.Log.Debug("getting initial messages") | ||
res, err := b.getMessages(channelName) | ||
if err != nil { | ||
panic(err) | ||
} | ||
for _, msg := range res { | ||
msgmap[*msg.ID] = *msg.CreatedDateTime | ||
if msg.LastModifiedDateTime != nil { | ||
msgmap[*msg.ID] = *msg.LastModifiedDateTime | ||
} | ||
} | ||
time.Sleep(time.Second * 5) | ||
b.Log.Debug("polling for messages") | ||
for { | ||
res, err := b.getMessages(channelName) | ||
if err != nil { | ||
panic(err) | ||
} | ||
for i := len(res) - 1; i >= 0; i-- { | ||
msg := res[i] | ||
if mtime, ok := msgmap[*msg.ID]; ok { | ||
if mtime == *msg.CreatedDateTime && msg.LastModifiedDateTime == nil { | ||
continue | ||
} | ||
if msg.LastModifiedDateTime != nil && mtime == *msg.LastModifiedDateTime { | ||
continue | ||
} | ||
} | ||
if *msg.From.User.ID == b.botID { | ||
b.Log.Debug("skipping own message") | ||
msgmap[*msg.ID] = *msg.CreatedDateTime | ||
continue | ||
} | ||
msgmap[*msg.ID] = *msg.CreatedDateTime | ||
if msg.LastModifiedDateTime != nil { | ||
msgmap[*msg.ID] = *msg.LastModifiedDateTime | ||
} | ||
b.Log.Debugf("<= Sending message from %s on %s to gateway", *msg.From.User.DisplayName, b.Account) | ||
text := b.convertToMD(*msg.Body.Content) | ||
rmsg := config.Message{ | ||
Username: *msg.From.User.DisplayName, | ||
Text: text, | ||
Channel: channelName, | ||
Account: b.Account, | ||
Avatar: "", | ||
UserID: *msg.From.User.ID, | ||
ID: *msg.ID, | ||
Extra: make(map[string][]interface{}), | ||
} | ||
|
||
b.handleAttachments(&rmsg, msg) | ||
b.Log.Debugf("<= Message is %#v", rmsg) | ||
b.Remote <- rmsg | ||
} | ||
time.Sleep(time.Second * 5) | ||
} | ||
} | ||
|
||
func (b *Bmsteams) setBotID() error { | ||
req := b.gc.Me().Request() | ||
r, err := req.Get(b.ctx) | ||
if err != nil { | ||
return err | ||
} | ||
b.botID = *r.ID | ||
return nil | ||
} | ||
|
||
func (b *Bmsteams) convertToMD(text string) string { | ||
if !strings.Contains(text, "<div>") { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does html-generated MSTeams formatting always have a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. According to my tests, yes |
||
return text | ||
} | ||
var sb strings.Builder | ||
err := godown.Convert(&sb, strings.NewReader(text), nil) | ||
if err != nil { | ||
b.Log.Errorf("Couldn't convert message to markdown %s", text) | ||
return text | ||
} | ||
return sb.String() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there any cleanup to be done in the
Disconnect
method?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, no clean-ups needed (no state)