mirror of
https://github.com/cwinfo/matterbridge.git
synced 2024-11-22 07:00:27 +00:00
Rewrite whatsapp bridge to use whatsmeow
This commit is contained in:
parent
17da95b094
commit
e7b193788a
@ -4,126 +4,92 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"mime"
|
"mime"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/42wim/matterbridge/bridge/config"
|
"github.com/42wim/matterbridge/bridge/config"
|
||||||
"github.com/42wim/matterbridge/bridge/helper"
|
"github.com/42wim/matterbridge/bridge/helper"
|
||||||
"github.com/Rhymen/go-whatsapp"
|
|
||||||
"github.com/jpillora/backoff"
|
"go.mau.fi/whatsmeow/binary/proto"
|
||||||
|
"go.mau.fi/whatsmeow/types"
|
||||||
|
"go.mau.fi/whatsmeow/types/events"
|
||||||
)
|
)
|
||||||
|
|
||||||
/*
|
// nolint:gocritic
|
||||||
Implement handling messages coming from WhatsApp
|
func (b *Bwhatsapp) eventHandler(evt interface{}) {
|
||||||
Check:
|
switch e := evt.(type) {
|
||||||
- https://github.com/Rhymen/go-whatsapp#add-message-handlers
|
case *events.Message:
|
||||||
- https://github.com/Rhymen/go-whatsapp/blob/master/handler.go
|
b.handleMessage(e)
|
||||||
- https://github.com/tulir/mautrix-whatsapp/tree/master/whatsapp-ext for more advanced command handling
|
}
|
||||||
*/
|
}
|
||||||
|
|
||||||
// HandleError received from WhatsApp
|
func (b *Bwhatsapp) handleMessage(message *events.Message) {
|
||||||
func (b *Bwhatsapp) HandleError(err error) {
|
msg := message.Message
|
||||||
// ignore received invalid data errors. https://github.com/42wim/matterbridge/issues/843
|
switch {
|
||||||
// ignore tag 174 errors. https://github.com/42wim/matterbridge/issues/1094
|
case msg == nil, message.Info.IsFromMe, message.Info.Timestamp.Before(b.startedAt):
|
||||||
if strings.Contains(err.Error(), "error processing data: received invalid data") ||
|
|
||||||
strings.Contains(err.Error(), "invalid string with tag 174") {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
switch err.(type) {
|
switch {
|
||||||
case *whatsapp.ErrConnectionClosed, *whatsapp.ErrConnectionFailed:
|
case msg.Conversation != nil || msg.ExtendedTextMessage != nil:
|
||||||
b.reconnect(err)
|
b.handleTextMessage(message.Info, msg)
|
||||||
default:
|
case msg.VideoMessage != nil:
|
||||||
switch err {
|
b.handleVideoMessage(message)
|
||||||
case whatsapp.ErrConnectionTimeout:
|
case msg.AudioMessage != nil:
|
||||||
b.reconnect(err)
|
b.handleAudioMessage(message)
|
||||||
default:
|
case msg.DocumentMessage != nil:
|
||||||
b.Log.Errorf("%v", err)
|
b.handleDocumentMessage(message)
|
||||||
}
|
case msg.ImageMessage != nil:
|
||||||
}
|
b.handleImageMessage(message)
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) reconnect(err error) {
|
|
||||||
bf := &backoff.Backoff{
|
|
||||||
Min: time.Second,
|
|
||||||
Max: 5 * time.Minute,
|
|
||||||
Jitter: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
d := bf.Duration()
|
|
||||||
|
|
||||||
b.Log.Errorf("Connection failed, underlying error: %v", err)
|
|
||||||
b.Log.Infof("Waiting %s...", d)
|
|
||||||
|
|
||||||
time.Sleep(d)
|
|
||||||
|
|
||||||
b.Log.Info("Reconnecting...")
|
|
||||||
|
|
||||||
err := b.conn.Restore()
|
|
||||||
if err == nil {
|
|
||||||
bf.Reset()
|
|
||||||
b.startedAt = uint64(time.Now().Unix())
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// HandleTextMessage sent from WhatsApp, relay it to the brige
|
|
||||||
func (b *Bwhatsapp) HandleTextMessage(message whatsapp.TextMessage) {
|
|
||||||
if message.Info.FromMe {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// whatsapp sends last messages to show context , cut them
|
|
||||||
if message.Info.Timestamp < b.startedAt {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
groupJID := message.Info.RemoteJid
|
|
||||||
senderJID := message.Info.SenderJid
|
|
||||||
|
|
||||||
if len(senderJID) == 0 {
|
|
||||||
if message.Info.Source != nil && message.Info.Source.Participant != nil {
|
|
||||||
senderJID = *message.Info.Source.Participant
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// translate sender's JID to the nicest username we can get
|
func (b *Bwhatsapp) handleTextMessage(messageInfo types.MessageInfo, msg *proto.Message) {
|
||||||
senderName := b.getSenderName(senderJID)
|
senderJID := messageInfo.Sender
|
||||||
|
|
||||||
|
senderName := b.getSenderName(messageInfo.Sender)
|
||||||
if senderName == "" {
|
if senderName == "" {
|
||||||
senderName = "Someone" // don't expose telephone number
|
senderName = "Someone" // don't expose telephone number
|
||||||
}
|
}
|
||||||
|
|
||||||
extText := message.Info.Source.Message.ExtendedTextMessage
|
if msg.GetExtendedTextMessage() == nil {
|
||||||
if extText != nil && extText.ContextInfo != nil && extText.ContextInfo.MentionedJid != nil {
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
text := msg.GetExtendedTextMessage().GetText()
|
||||||
|
ci := msg.GetExtendedTextMessage().GetContextInfo()
|
||||||
|
|
||||||
|
if senderJID == (types.JID{}) && ci.Participant != nil {
|
||||||
|
senderJID = types.NewJID(ci.GetParticipant(), types.DefaultUserServer)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ci.MentionedJid != nil {
|
||||||
// handle user mentions
|
// handle user mentions
|
||||||
for _, mentionedJID := range extText.ContextInfo.MentionedJid {
|
for _, mentionedJID := range ci.MentionedJid {
|
||||||
numberAndSuffix := strings.SplitN(mentionedJID, "@", 2)
|
numberAndSuffix := strings.SplitN(mentionedJID, "@", 2)
|
||||||
|
|
||||||
// mentions comes as telephone numbers and we don't want to expose it to other bridges
|
// mentions comes as telephone numbers and we don't want to expose it to other bridges
|
||||||
// replace it with something more meaninful to others
|
// replace it with something more meaninful to others
|
||||||
mention := b.getSenderNotify(numberAndSuffix[0] + "@s.whatsapp.net")
|
mention := b.getSenderNotify(types.NewJID(numberAndSuffix[0], types.DefaultUserServer))
|
||||||
if mention == "" {
|
if mention == "" {
|
||||||
mention = "someone"
|
mention = "someone"
|
||||||
}
|
}
|
||||||
|
|
||||||
message.Text = strings.Replace(message.Text, "@"+numberAndSuffix[0], "@"+mention, 1)
|
text = strings.Replace(text, "@"+numberAndSuffix[0], "@"+mention, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{
|
rmsg := config.Message{
|
||||||
UserID: senderJID,
|
UserID: senderJID.String(),
|
||||||
Username: senderName,
|
Username: senderName,
|
||||||
Text: message.Text,
|
Text: msg.GetExtendedTextMessage().GetText(),
|
||||||
Channel: groupJID,
|
Channel: ci.GetRemoteJid(),
|
||||||
Account: b.Account,
|
Account: b.Account,
|
||||||
Protocol: b.Protocol,
|
Protocol: b.Protocol,
|
||||||
Extra: make(map[string][]interface{}),
|
Extra: make(map[string][]interface{}),
|
||||||
// ParentID: TODO, // TODO handle thread replies // map from Info.QuotedMessageID string
|
// ParentID: TODO, // TODO handle thread replies // map from Info.QuotedMessageID string
|
||||||
ID: message.Info.Id,
|
ID: messageInfo.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatarURL, exists := b.userAvatars[senderJID]; exists {
|
if avatarURL, exists := b.userAvatars[senderJID.String()]; exists {
|
||||||
rmsg.Avatar = avatarURL
|
rmsg.Avatar = avatarURL
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -134,36 +100,32 @@ func (b *Bwhatsapp) HandleTextMessage(message whatsapp.TextMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HandleImageMessage sent from WhatsApp, relay it to the brige
|
// HandleImageMessage sent from WhatsApp, relay it to the brige
|
||||||
func (b *Bwhatsapp) HandleImageMessage(message whatsapp.ImageMessage) {
|
func (b *Bwhatsapp) handleImageMessage(msg *events.Message) {
|
||||||
if message.Info.FromMe || message.Info.Timestamp < b.startedAt {
|
imsg := msg.Message.GetImageMessage()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
senderJID := message.Info.SenderJid
|
senderJID := msg.Info.Sender
|
||||||
if len(message.Info.SenderJid) == 0 && message.Info.Source != nil && message.Info.Source.Participant != nil {
|
senderName := b.getSenderName(senderJID)
|
||||||
senderJID = *message.Info.Source.Participant
|
ci := imsg.GetContextInfo()
|
||||||
}
|
|
||||||
|
|
||||||
senderName := b.getSenderName(message.Info.SenderJid)
|
if senderJID == (types.JID{}) && ci.Participant != nil {
|
||||||
if senderName == "" {
|
senderJID = types.NewJID(ci.GetParticipant(), types.DefaultUserServer)
|
||||||
senderName = "Someone" // don't expose telephone number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{
|
rmsg := config.Message{
|
||||||
UserID: senderJID,
|
UserID: senderJID.String(),
|
||||||
Username: senderName,
|
Username: senderName,
|
||||||
Channel: message.Info.RemoteJid,
|
Channel: ci.GetRemoteJid(),
|
||||||
Account: b.Account,
|
Account: b.Account,
|
||||||
Protocol: b.Protocol,
|
Protocol: b.Protocol,
|
||||||
Extra: make(map[string][]interface{}),
|
Extra: make(map[string][]interface{}),
|
||||||
ID: message.Info.Id,
|
ID: msg.Info.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatarURL, exists := b.userAvatars[senderJID]; exists {
|
if avatarURL, exists := b.userAvatars[senderJID.String()]; exists {
|
||||||
rmsg.Avatar = avatarURL
|
rmsg.Avatar = avatarURL
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExt, err := mime.ExtensionsByType(message.Type)
|
fileExt, err := mime.ExtensionsByType(imsg.GetMimetype())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Mimetype detection error: %s", err)
|
b.Log.Errorf("Mimetype detection error: %s", err)
|
||||||
|
|
||||||
@ -180,11 +142,11 @@ func (b *Bwhatsapp) HandleImageMessage(message whatsapp.ImageMessage) {
|
|||||||
fileExt[0] = ".jpg"
|
fileExt[0] = ".jpg"
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := fmt.Sprintf("%v%v", message.Info.Id, fileExt[0])
|
filename := fmt.Sprintf("%v%v", msg.Info.ID, fileExt[0])
|
||||||
|
|
||||||
b.Log.Debugf("Trying to download %s with type %s", filename, message.Type)
|
b.Log.Debugf("Trying to download %s with type %s", filename, imsg.GetMimetype())
|
||||||
|
|
||||||
data, err := message.Download()
|
data, err := b.wc.Download(imsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Download image failed: %s", err)
|
b.Log.Errorf("Download image failed: %s", err)
|
||||||
|
|
||||||
@ -192,7 +154,7 @@ func (b *Bwhatsapp) HandleImageMessage(message whatsapp.ImageMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Move file to bridge storage
|
// Move file to bridge storage
|
||||||
helper.HandleDownloadData(b.Log, &rmsg, filename, message.Caption, "", &data, b.General)
|
helper.HandleDownloadData(b.Log, &rmsg, filename, imsg.GetCaption(), "", &data, b.General)
|
||||||
|
|
||||||
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJID, b.Account)
|
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJID, b.Account)
|
||||||
b.Log.Debugf("<= Message is %#v", rmsg)
|
b.Log.Debugf("<= Message is %#v", rmsg)
|
||||||
@ -201,36 +163,32 @@ func (b *Bwhatsapp) HandleImageMessage(message whatsapp.ImageMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HandleVideoMessage downloads video messages
|
// HandleVideoMessage downloads video messages
|
||||||
func (b *Bwhatsapp) HandleVideoMessage(message whatsapp.VideoMessage) {
|
func (b *Bwhatsapp) handleVideoMessage(msg *events.Message) {
|
||||||
if message.Info.FromMe || message.Info.Timestamp < b.startedAt {
|
imsg := msg.Message.GetVideoMessage()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
senderJID := message.Info.SenderJid
|
senderJID := msg.Info.Sender
|
||||||
if len(message.Info.SenderJid) == 0 && message.Info.Source != nil && message.Info.Source.Participant != nil {
|
senderName := b.getSenderName(senderJID)
|
||||||
senderJID = *message.Info.Source.Participant
|
ci := imsg.GetContextInfo()
|
||||||
}
|
|
||||||
|
|
||||||
senderName := b.getSenderName(message.Info.SenderJid)
|
if senderJID == (types.JID{}) && ci.Participant != nil {
|
||||||
if senderName == "" {
|
senderJID = types.NewJID(ci.GetParticipant(), types.DefaultUserServer)
|
||||||
senderName = "Someone" // don't expose telephone number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{
|
rmsg := config.Message{
|
||||||
UserID: senderJID,
|
UserID: senderJID.String(),
|
||||||
Username: senderName,
|
Username: senderName,
|
||||||
Channel: message.Info.RemoteJid,
|
Channel: ci.GetRemoteJid(),
|
||||||
Account: b.Account,
|
Account: b.Account,
|
||||||
Protocol: b.Protocol,
|
Protocol: b.Protocol,
|
||||||
Extra: make(map[string][]interface{}),
|
Extra: make(map[string][]interface{}),
|
||||||
ID: message.Info.Id,
|
ID: msg.Info.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatarURL, exists := b.userAvatars[senderJID]; exists {
|
if avatarURL, exists := b.userAvatars[senderJID.String()]; exists {
|
||||||
rmsg.Avatar = avatarURL
|
rmsg.Avatar = avatarURL
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExt, err := mime.ExtensionsByType(message.Type)
|
fileExt, err := mime.ExtensionsByType(imsg.GetMimetype())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Mimetype detection error: %s", err)
|
b.Log.Errorf("Mimetype detection error: %s", err)
|
||||||
|
|
||||||
@ -241,11 +199,11 @@ func (b *Bwhatsapp) HandleVideoMessage(message whatsapp.VideoMessage) {
|
|||||||
fileExt = append(fileExt, ".mp4")
|
fileExt = append(fileExt, ".mp4")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := fmt.Sprintf("%v%v", message.Info.Id, fileExt[0])
|
filename := fmt.Sprintf("%v%v", msg.Info.ID, fileExt[0])
|
||||||
|
|
||||||
b.Log.Debugf("Trying to download %s with size %#v and type %s", filename, message.Length, message.Type)
|
b.Log.Debugf("Trying to download %s with size %#v and type %s", filename, imsg.GetFileLength(), imsg.GetMimetype())
|
||||||
|
|
||||||
data, err := message.Download()
|
data, err := b.wc.Download(imsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Download video failed: %s", err)
|
b.Log.Errorf("Download video failed: %s", err)
|
||||||
|
|
||||||
@ -253,7 +211,7 @@ func (b *Bwhatsapp) HandleVideoMessage(message whatsapp.VideoMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Move file to bridge storage
|
// Move file to bridge storage
|
||||||
helper.HandleDownloadData(b.Log, &rmsg, filename, message.Caption, "", &data, b.General)
|
helper.HandleDownloadData(b.Log, &rmsg, filename, imsg.GetCaption(), "", &data, b.General)
|
||||||
|
|
||||||
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJID, b.Account)
|
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJID, b.Account)
|
||||||
b.Log.Debugf("<= Message is %#v", rmsg)
|
b.Log.Debugf("<= Message is %#v", rmsg)
|
||||||
@ -262,36 +220,32 @@ func (b *Bwhatsapp) HandleVideoMessage(message whatsapp.VideoMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HandleAudioMessage downloads audio messages
|
// HandleAudioMessage downloads audio messages
|
||||||
func (b *Bwhatsapp) HandleAudioMessage(message whatsapp.AudioMessage) {
|
func (b *Bwhatsapp) handleAudioMessage(msg *events.Message) {
|
||||||
if message.Info.FromMe || message.Info.Timestamp < b.startedAt {
|
imsg := msg.Message.GetAudioMessage()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
senderJID := message.Info.SenderJid
|
senderJID := msg.Info.Sender
|
||||||
if len(message.Info.SenderJid) == 0 && message.Info.Source != nil && message.Info.Source.Participant != nil {
|
senderName := b.getSenderName(senderJID)
|
||||||
senderJID = *message.Info.Source.Participant
|
ci := imsg.GetContextInfo()
|
||||||
}
|
|
||||||
|
|
||||||
senderName := b.getSenderName(message.Info.SenderJid)
|
if senderJID == (types.JID{}) && ci.Participant != nil {
|
||||||
if senderName == "" {
|
senderJID = types.NewJID(ci.GetParticipant(), types.DefaultUserServer)
|
||||||
senderName = "Someone" // don't expose telephone number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{
|
rmsg := config.Message{
|
||||||
UserID: senderJID,
|
UserID: senderJID.String(),
|
||||||
Username: senderName,
|
Username: senderName,
|
||||||
Channel: message.Info.RemoteJid,
|
Channel: ci.GetRemoteJid(),
|
||||||
Account: b.Account,
|
Account: b.Account,
|
||||||
Protocol: b.Protocol,
|
Protocol: b.Protocol,
|
||||||
Extra: make(map[string][]interface{}),
|
Extra: make(map[string][]interface{}),
|
||||||
ID: message.Info.Id,
|
ID: msg.Info.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatarURL, exists := b.userAvatars[senderJID]; exists {
|
if avatarURL, exists := b.userAvatars[senderJID.String()]; exists {
|
||||||
rmsg.Avatar = avatarURL
|
rmsg.Avatar = avatarURL
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExt, err := mime.ExtensionsByType(message.Type)
|
fileExt, err := mime.ExtensionsByType(imsg.GetMimetype())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Mimetype detection error: %s", err)
|
b.Log.Errorf("Mimetype detection error: %s", err)
|
||||||
|
|
||||||
@ -302,13 +256,13 @@ func (b *Bwhatsapp) HandleAudioMessage(message whatsapp.AudioMessage) {
|
|||||||
fileExt = append(fileExt, ".ogg")
|
fileExt = append(fileExt, ".ogg")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := fmt.Sprintf("%v%v", message.Info.Id, fileExt[0])
|
filename := fmt.Sprintf("%v%v", msg.Info.ID, fileExt[0])
|
||||||
|
|
||||||
b.Log.Debugf("Trying to download %s with size %#v and type %s", filename, message.Length, message.Type)
|
b.Log.Debugf("Trying to download %s with size %#v and type %s", filename, imsg.GetFileLength(), imsg.GetMimetype())
|
||||||
|
|
||||||
data, err := message.Download()
|
data, err := b.wc.Download(imsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Download audio failed: %s", err)
|
b.Log.Errorf("Download video failed: %s", err)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -323,47 +277,43 @@ func (b *Bwhatsapp) HandleAudioMessage(message whatsapp.AudioMessage) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HandleDocumentMessage downloads documents
|
// HandleDocumentMessage downloads documents
|
||||||
func (b *Bwhatsapp) HandleDocumentMessage(message whatsapp.DocumentMessage) {
|
func (b *Bwhatsapp) handleDocumentMessage(msg *events.Message) {
|
||||||
if message.Info.FromMe || message.Info.Timestamp < b.startedAt {
|
imsg := msg.Message.GetDocumentMessage()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
senderJID := message.Info.SenderJid
|
senderJID := msg.Info.Sender
|
||||||
if len(message.Info.SenderJid) == 0 && message.Info.Source != nil && message.Info.Source.Participant != nil {
|
senderName := b.getSenderName(senderJID)
|
||||||
senderJID = *message.Info.Source.Participant
|
ci := imsg.GetContextInfo()
|
||||||
}
|
|
||||||
|
|
||||||
senderName := b.getSenderName(message.Info.SenderJid)
|
if senderJID == (types.JID{}) && ci.Participant != nil {
|
||||||
if senderName == "" {
|
senderJID = types.NewJID(ci.GetParticipant(), types.DefaultUserServer)
|
||||||
senderName = "Someone" // don't expose telephone number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{
|
rmsg := config.Message{
|
||||||
UserID: senderJID,
|
UserID: senderJID.String(),
|
||||||
Username: senderName,
|
Username: senderName,
|
||||||
Channel: message.Info.RemoteJid,
|
Channel: ci.GetRemoteJid(),
|
||||||
Account: b.Account,
|
Account: b.Account,
|
||||||
Protocol: b.Protocol,
|
Protocol: b.Protocol,
|
||||||
Extra: make(map[string][]interface{}),
|
Extra: make(map[string][]interface{}),
|
||||||
ID: message.Info.Id,
|
ID: msg.Info.ID,
|
||||||
}
|
}
|
||||||
|
|
||||||
if avatarURL, exists := b.userAvatars[senderJID]; exists {
|
if avatarURL, exists := b.userAvatars[senderJID.String()]; exists {
|
||||||
rmsg.Avatar = avatarURL
|
rmsg.Avatar = avatarURL
|
||||||
}
|
}
|
||||||
|
|
||||||
fileExt, err := mime.ExtensionsByType(message.Type)
|
fileExt, err := mime.ExtensionsByType(imsg.GetMimetype())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Mimetype detection error: %s", err)
|
b.Log.Errorf("Mimetype detection error: %s", err)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := fmt.Sprintf("%v", message.FileName)
|
filename := fmt.Sprintf("%v", imsg.GetFileName())
|
||||||
|
|
||||||
b.Log.Debugf("Trying to download %s with extension %s and type %s", filename, fileExt, message.Type)
|
b.Log.Debugf("Trying to download %s with extension %s and type %s", filename, fileExt, imsg.GetMimetype())
|
||||||
|
|
||||||
data, err := message.Download()
|
data, err := b.wc.Download(imsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Download document message failed: %s", err)
|
b.Log.Errorf("Download document message failed: %s", err)
|
||||||
|
|
||||||
|
@ -1,15 +1,12 @@
|
|||||||
package bwhatsapp
|
package bwhatsapp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/gob"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
|
"go.mau.fi/whatsmeow/store"
|
||||||
"github.com/Rhymen/go-whatsapp"
|
"go.mau.fi/whatsmeow/store/sqlstore"
|
||||||
|
"go.mau.fi/whatsmeow/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ProfilePicInfo struct {
|
type ProfilePicInfo struct {
|
||||||
@ -18,141 +15,71 @@ type ProfilePicInfo struct {
|
|||||||
Status int16 `json:"status"`
|
Status int16 `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func qrFromTerminal(invert bool) chan string {
|
func (b *Bwhatsapp) getSenderName(senderJid types.JID) string {
|
||||||
qr := make(chan string)
|
if sender, exists := b.contacts[senderJid]; exists {
|
||||||
|
if sender.FullName != "" {
|
||||||
go func() {
|
return sender.FullName
|
||||||
terminal := qrcodeTerminal.New()
|
|
||||||
|
|
||||||
if invert {
|
|
||||||
terminal = qrcodeTerminal.New2(qrcodeTerminal.ConsoleColors.BrightWhite, qrcodeTerminal.ConsoleColors.BrightBlack, qrcodeTerminal.QRCodeRecoveryLevels.Medium)
|
|
||||||
}
|
|
||||||
|
|
||||||
terminal.Get(<-qr).Print()
|
|
||||||
}()
|
|
||||||
|
|
||||||
return qr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) readSession() (whatsapp.Session, error) {
|
|
||||||
session := whatsapp.Session{}
|
|
||||||
sessionFile := b.Config.GetString(sessionFile)
|
|
||||||
|
|
||||||
if sessionFile == "" {
|
|
||||||
return session, errors.New("if you won't set SessionFile then you will need to scan QR code on every restart")
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Open(sessionFile)
|
|
||||||
if err != nil {
|
|
||||||
return session, err
|
|
||||||
}
|
|
||||||
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
decoder := gob.NewDecoder(file)
|
|
||||||
|
|
||||||
return session, decoder.Decode(&session)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) writeSession(session whatsapp.Session) error {
|
|
||||||
sessionFile := b.Config.GetString(sessionFile)
|
|
||||||
|
|
||||||
if sessionFile == "" {
|
|
||||||
// we already sent a warning while starting the bridge, so let's be quiet here
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Create(sessionFile)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
encoder := gob.NewEncoder(file)
|
|
||||||
|
|
||||||
return encoder.Encode(session)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) restoreSession() (*whatsapp.Session, error) {
|
|
||||||
session, err := b.readSession()
|
|
||||||
if err != nil {
|
|
||||||
b.Log.Warn(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
b.Log.Debugln("Restoring WhatsApp session..")
|
|
||||||
|
|
||||||
session, err = b.conn.RestoreWithSession(session)
|
|
||||||
if err != nil {
|
|
||||||
// restore session connection timed out (I couldn't get over it without logging in again)
|
|
||||||
return nil, errors.New("failed to restore session: " + err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
b.Log.Debugln("Session restored successfully!")
|
|
||||||
|
|
||||||
return &session, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) getSenderName(senderJid string) string {
|
|
||||||
if sender, exists := b.users[senderJid]; exists {
|
|
||||||
if sender.Name != "" {
|
|
||||||
return sender.Name
|
|
||||||
}
|
}
|
||||||
// if user is not in phone contacts
|
// if user is not in phone contacts
|
||||||
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
|
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
|
||||||
// users can change it in their WhatsApp settings -> profile -> click on Avatar
|
// users can change it in their WhatsApp settings -> profile -> click on Avatar
|
||||||
if sender.Notify != "" {
|
if sender.PushName != "" {
|
||||||
return sender.Notify
|
return sender.PushName
|
||||||
}
|
}
|
||||||
|
|
||||||
if sender.Short != "" {
|
if sender.FirstName != "" {
|
||||||
return sender.Short
|
return sender.FirstName
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// try to reload this contact
|
// try to reload this contact
|
||||||
_, err := b.conn.Contacts()
|
if _, err := b.wc.Store.Contacts.GetAllContacts(); err != nil {
|
||||||
|
b.Log.Errorf("error on update of contacts: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
allcontacts, err := b.wc.Store.Contacts.GetAllContacts()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("error on update of contacts: %v", err)
|
b.Log.Errorf("error on update of contacts: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if contact, exists := b.conn.Store.Contacts[senderJid]; exists {
|
if len(allcontacts) > 0 {
|
||||||
// Add it to the user map
|
b.contacts = allcontacts
|
||||||
b.users[senderJid] = contact
|
}
|
||||||
|
|
||||||
if contact.Name != "" {
|
if sender, exists := b.contacts[senderJid]; exists {
|
||||||
return contact.Name
|
if sender.FullName != "" {
|
||||||
|
return sender.FullName
|
||||||
}
|
}
|
||||||
// if user is not in phone contacts
|
// if user is not in phone contacts
|
||||||
// same as above
|
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
|
||||||
return contact.Notify
|
// users can change it in their WhatsApp settings -> profile -> click on Avatar
|
||||||
|
if sender.PushName != "" {
|
||||||
|
return sender.PushName
|
||||||
|
}
|
||||||
|
|
||||||
|
if sender.FirstName != "" {
|
||||||
|
return sender.FirstName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Someone"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bwhatsapp) getSenderNotify(senderJid types.JID) string {
|
||||||
|
if sender, exists := b.contacts[senderJid]; exists {
|
||||||
|
return sender.PushName
|
||||||
}
|
}
|
||||||
|
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bwhatsapp) getSenderNotify(senderJid string) string {
|
func (b *Bwhatsapp) GetProfilePicThumb(jid string) (*types.ProfilePictureInfo, error) {
|
||||||
if sender, exists := b.users[senderJid]; exists {
|
pjid, _ := types.ParseJID(jid)
|
||||||
return sender.Notify
|
info, err := b.wc.GetProfilePictureInfo(pjid, true)
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bwhatsapp) GetProfilePicThumb(jid string) (*ProfilePicInfo, error) {
|
|
||||||
data, err := b.conn.GetProfilePicThumb(jid)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to get avatar: %v", err)
|
return nil, fmt.Errorf("failed to get avatar: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
content := <-data
|
|
||||||
info := &ProfilePicInfo{}
|
|
||||||
|
|
||||||
err = json.Unmarshal([]byte(content), info)
|
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("failed to unmarshal avatar info: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -161,3 +88,19 @@ func isGroupJid(identifier string) bool {
|
|||||||
strings.HasSuffix(identifier, "@temp") ||
|
strings.HasSuffix(identifier, "@temp") ||
|
||||||
strings.HasSuffix(identifier, "@broadcast")
|
strings.HasSuffix(identifier, "@broadcast")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Bwhatsapp) getDevice() (*store.Device, error) {
|
||||||
|
device := &store.Device{}
|
||||||
|
|
||||||
|
storeContainer, err := sqlstore.New("sqlite", "file:"+b.Config.GetString("sessionfile")+".db?_foreign_keys=on", nil)
|
||||||
|
if err != nil {
|
||||||
|
return device, fmt.Errorf("failed to connect to database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
device, err = storeContainer.GetFirstDevice()
|
||||||
|
if err != nil {
|
||||||
|
return device, fmt.Errorf("failed to get device: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return device, nil
|
||||||
|
}
|
||||||
|
@ -1,38 +1,41 @@
|
|||||||
package bwhatsapp
|
package bwhatsapp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"context"
|
||||||
"crypto/rand"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"mime"
|
"mime"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/42wim/matterbridge/bridge"
|
"github.com/42wim/matterbridge/bridge"
|
||||||
"github.com/42wim/matterbridge/bridge/config"
|
"github.com/42wim/matterbridge/bridge/config"
|
||||||
"github.com/Rhymen/go-whatsapp"
|
"github.com/mdp/qrterminal"
|
||||||
|
|
||||||
|
"go.mau.fi/whatsmeow"
|
||||||
|
"go.mau.fi/whatsmeow/binary/proto"
|
||||||
|
"go.mau.fi/whatsmeow/types"
|
||||||
|
waLog "go.mau.fi/whatsmeow/util/log"
|
||||||
|
|
||||||
|
goproto "google.golang.org/protobuf/proto"
|
||||||
|
|
||||||
|
_ "modernc.org/sqlite" // needed for sqlite
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// Account config parameters
|
// Account config parameters
|
||||||
cfgNumber = "Number"
|
cfgNumber = "Number"
|
||||||
qrOnWhiteTerminal = "QrOnWhiteTerminal"
|
|
||||||
sessionFile = "SessionFile"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Bwhatsapp Bridge structure keeping all the information needed for relying
|
// Bwhatsapp Bridge structure keeping all the information needed for relying
|
||||||
type Bwhatsapp struct {
|
type Bwhatsapp struct {
|
||||||
*bridge.Config
|
*bridge.Config
|
||||||
|
|
||||||
session *whatsapp.Session
|
startedAt time.Time
|
||||||
conn *whatsapp.Conn
|
wc *whatsmeow.Client
|
||||||
startedAt uint64
|
contacts map[types.JID]types.ContactInfo
|
||||||
|
users map[string]types.ContactInfo
|
||||||
users map[string]whatsapp.Contact
|
|
||||||
userAvatars map[string]string
|
userAvatars map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +50,7 @@ func New(cfg *bridge.Config) bridge.Bridger {
|
|||||||
b := &Bwhatsapp{
|
b := &Bwhatsapp{
|
||||||
Config: cfg,
|
Config: cfg,
|
||||||
|
|
||||||
users: make(map[string]whatsapp.Contact),
|
users: make(map[string]types.ContactInfo),
|
||||||
userAvatars: make(map[string]string),
|
userAvatars: make(map[string]string),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -56,54 +59,56 @@ func New(cfg *bridge.Config) bridge.Bridger {
|
|||||||
|
|
||||||
// Connect to WhatsApp. Required implementation of the Bridger interface
|
// Connect to WhatsApp. Required implementation of the Bridger interface
|
||||||
func (b *Bwhatsapp) Connect() error {
|
func (b *Bwhatsapp) Connect() error {
|
||||||
|
device, err := b.getDevice()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
number := b.GetString(cfgNumber)
|
number := b.GetString(cfgNumber)
|
||||||
if number == "" {
|
if number == "" {
|
||||||
return errors.New("whatsapp's telephone number need to be configured")
|
return errors.New("whatsapp's telephone number need to be configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Log.Debugln("Connecting to WhatsApp..")
|
b.Log.Debugln("Connecting to WhatsApp..")
|
||||||
conn, err := whatsapp.NewConn(20 * time.Second)
|
|
||||||
|
b.wc = whatsmeow.NewClient(device, waLog.Stdout("Client", "INFO", true))
|
||||||
|
b.wc.AddEventHandler(b.eventHandler)
|
||||||
|
|
||||||
|
// No ID stored, new login
|
||||||
|
qrChan, err := b.wc.GetQRChannel(context.Background())
|
||||||
|
// This error means that we're already logged in, so ignore it.
|
||||||
|
if err != nil && !errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
|
||||||
|
return errors.New("failed to to get QR channel:" + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
err = b.wc.Connect()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("failed to connect to WhatsApp: " + err.Error())
|
return errors.New("failed to connect to WhatsApp: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
b.conn = conn
|
for evt := range qrChan {
|
||||||
|
if evt.Event == "code" {
|
||||||
|
// Render the QR code here
|
||||||
|
qrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)
|
||||||
|
} else {
|
||||||
|
b.Log.Infof("QR channel result: %s", evt.Event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
b.conn.AddHandler(b)
|
b.Log.Infoln("WhatsApp connection successful")
|
||||||
b.Log.Debugln("WhatsApp connection successful")
|
|
||||||
|
|
||||||
// load existing session in order to keep it between restarts
|
b.contacts, err = b.wc.Store.Contacts.GetAllContacts()
|
||||||
b.session, err = b.restoreSession()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Warn(err.Error())
|
return errors.New("failed to get contacts: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
// login to a new session
|
b.startedAt = time.Now()
|
||||||
if b.session == nil {
|
|
||||||
if err = b.Login(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
b.startedAt = uint64(time.Now().Unix())
|
|
||||||
|
|
||||||
_, err = b.conn.Contacts()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("error on update of contacts: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// see https://github.com/Rhymen/go-whatsapp/issues/137#issuecomment-480316013
|
|
||||||
for len(b.conn.Store.Contacts) == 0 {
|
|
||||||
b.conn.Contacts() // nolint:errcheck
|
|
||||||
|
|
||||||
<-time.After(1 * time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
// map all the users
|
// map all the users
|
||||||
for id, contact := range b.conn.Store.Contacts {
|
for id, contact := range b.contacts {
|
||||||
if !isGroupJid(id) && id != "status@broadcast" {
|
if !isGroupJid(id.String()) && id.String() != "status@broadcast" {
|
||||||
// it is user
|
// it is user
|
||||||
b.users[id] = contact
|
b.users[id.String()] = contact
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -128,38 +133,11 @@ func (b *Bwhatsapp) Connect() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Login to WhatsApp creating a new session. This will require to scan a QR code on your mobile device
|
|
||||||
func (b *Bwhatsapp) Login() error {
|
|
||||||
b.Log.Debugln("Logging in..")
|
|
||||||
|
|
||||||
invert := b.GetBool(qrOnWhiteTerminal) // false is the default
|
|
||||||
qrChan := qrFromTerminal(invert)
|
|
||||||
|
|
||||||
session, err := b.conn.Login(qrChan)
|
|
||||||
if err != nil {
|
|
||||||
b.Log.Warnln("Failed to log in:", err)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
b.session = &session
|
|
||||||
|
|
||||||
b.Log.Infof("Logged into session: %#v", session)
|
|
||||||
b.Log.Infof("Connection: %#v", b.conn)
|
|
||||||
|
|
||||||
err = b.writeSession(session)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "error saving session: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Disconnect is called while reconnecting to the bridge
|
// Disconnect is called while reconnecting to the bridge
|
||||||
// Required implementation of the Bridger interface
|
// Required implementation of the Bridger interface
|
||||||
func (b *Bwhatsapp) Disconnect() error {
|
func (b *Bwhatsapp) Disconnect() error {
|
||||||
// We could Logout, but that would close the session completely and would require a new QR code scan
|
b.wc.Disconnect()
|
||||||
// https://github.com/Rhymen/go-whatsapp/blob/c31092027237441cffba1b9cb148eadf7c83c3d2/session.go#L377-L381
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -169,16 +147,19 @@ func (b *Bwhatsapp) Disconnect() error {
|
|||||||
func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
|
func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
|
||||||
byJid := isGroupJid(channel.Name)
|
byJid := isGroupJid(channel.Name)
|
||||||
|
|
||||||
// see https://github.com/Rhymen/go-whatsapp/issues/137#issuecomment-480316013
|
|
||||||
for len(b.conn.Store.Contacts) == 0 {
|
|
||||||
b.conn.Contacts() // nolint:errcheck
|
|
||||||
<-time.After(1 * time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
// verify if we are member of the given group
|
// verify if we are member of the given group
|
||||||
if byJid {
|
if byJid {
|
||||||
|
gJID, err := types.ParseJID(channel.Name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
// channel.Name specifies static group jID, not the name
|
// channel.Name specifies static group jID, not the name
|
||||||
if _, exists := b.conn.Store.Contacts[channel.Name]; !exists {
|
info, err := b.wc.Store.Contacts.GetContact(gJID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !info.Found {
|
||||||
return fmt.Errorf("account doesn't belong to group with jid %s", channel.Name)
|
return fmt.Errorf("account doesn't belong to group with jid %s", channel.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,18 +168,22 @@ func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
|
|||||||
|
|
||||||
// channel.Name specifies group name that might change, warn about it
|
// channel.Name specifies group name that might change, warn about it
|
||||||
var jids []string
|
var jids []string
|
||||||
for id, contact := range b.conn.Store.Contacts {
|
allContacts, err := b.wc.Store.Contacts.GetAllContacts()
|
||||||
if isGroupJid(id) && contact.Name == channel.Name {
|
if err != nil {
|
||||||
jids = append(jids, id)
|
return err
|
||||||
|
}
|
||||||
|
for id := range allContacts {
|
||||||
|
if isGroupJid(id.String()) && id.String() == channel.Name {
|
||||||
|
jids = append(jids, id.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch len(jids) {
|
switch len(jids) {
|
||||||
case 0:
|
case 0:
|
||||||
// didn't match any group - print out possibilites
|
// didn't match any group - print out possibilites
|
||||||
for id, contact := range b.conn.Store.Contacts {
|
for id, contact := range allContacts {
|
||||||
if isGroupJid(id) {
|
if isGroupJid(id.String()) {
|
||||||
b.Log.Infof("%s %s", contact.Jid, contact.Name)
|
b.Log.Infof("%s %s", id, contact.FullName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -212,68 +197,75 @@ func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
|
|||||||
|
|
||||||
// Post a document message from the bridge to WhatsApp
|
// Post a document message from the bridge to WhatsApp
|
||||||
func (b *Bwhatsapp) PostDocumentMessage(msg config.Message, filetype string) (string, error) {
|
func (b *Bwhatsapp) PostDocumentMessage(msg config.Message, filetype string) (string, error) {
|
||||||
|
groupJID, _ := types.ParseJID(msg.Channel)
|
||||||
|
|
||||||
fi := msg.Extra["file"][0].(config.FileInfo)
|
fi := msg.Extra["file"][0].(config.FileInfo)
|
||||||
|
|
||||||
|
resp, err := b.wc.Upload(context.Background(), *fi.Data, whatsmeow.MediaDocument)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
// Post document message
|
// Post document message
|
||||||
message := whatsapp.DocumentMessage{
|
var message proto.Message
|
||||||
Info: whatsapp.MessageInfo{
|
|
||||||
RemoteJid: msg.Channel,
|
message.DocumentMessage = &proto.DocumentMessage{
|
||||||
},
|
Title: &fi.Name,
|
||||||
Title: fi.Name,
|
FileName: &fi.Name,
|
||||||
FileName: fi.Name,
|
Mimetype: &filetype,
|
||||||
Type: filetype,
|
MediaKey: resp.MediaKey,
|
||||||
Content: bytes.NewReader(*fi.Data),
|
FileEncSha256: resp.FileEncSHA256,
|
||||||
|
FileSha256: resp.FileSHA256,
|
||||||
|
FileLength: goproto.Uint64(resp.FileLength),
|
||||||
|
Url: &resp.URL,
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Log.Debugf("=> Sending %#v", msg)
|
b.Log.Debugf("=> Sending %#v", msg)
|
||||||
|
|
||||||
// create message ID
|
ID := whatsmeow.GenerateMessageID()
|
||||||
// TODO follow and act if https://github.com/Rhymen/go-whatsapp/issues/101 implemented
|
_, err = b.wc.SendMessage(groupJID, ID, &message)
|
||||||
idBytes := make([]byte, 10)
|
|
||||||
if _, err := rand.Read(idBytes); err != nil {
|
|
||||||
b.Log.Warn(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
message.Info.Id = strings.ToUpper(hex.EncodeToString(idBytes))
|
return ID, err
|
||||||
_, err := b.conn.Send(message)
|
|
||||||
|
|
||||||
return message.Info.Id, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post an image message from the bridge to WhatsApp
|
// Post an image message from the bridge to WhatsApp
|
||||||
// Handle, for sure image/jpeg, image/png and image/gif MIME types
|
// Handle, for sure image/jpeg, image/png and image/gif MIME types
|
||||||
func (b *Bwhatsapp) PostImageMessage(msg config.Message, filetype string) (string, error) {
|
func (b *Bwhatsapp) PostImageMessage(msg config.Message, filetype string) (string, error) {
|
||||||
|
groupJID, _ := types.ParseJID(msg.Channel)
|
||||||
|
|
||||||
fi := msg.Extra["file"][0].(config.FileInfo)
|
fi := msg.Extra["file"][0].(config.FileInfo)
|
||||||
|
|
||||||
// Post image message
|
caption := msg.Username + fi.Comment
|
||||||
message := whatsapp.ImageMessage{
|
|
||||||
Info: whatsapp.MessageInfo{
|
resp, err := b.wc.Upload(context.Background(), *fi.Data, whatsmeow.MediaImage)
|
||||||
RemoteJid: msg.Channel,
|
if err != nil {
|
||||||
},
|
return "", err
|
||||||
Type: filetype,
|
}
|
||||||
Caption: msg.Username + fi.Comment,
|
|
||||||
Content: bytes.NewReader(*fi.Data),
|
var message proto.Message
|
||||||
|
|
||||||
|
message.ImageMessage = &proto.ImageMessage{
|
||||||
|
Mimetype: &filetype,
|
||||||
|
Caption: &caption,
|
||||||
|
MediaKey: resp.MediaKey,
|
||||||
|
FileEncSha256: resp.FileEncSHA256,
|
||||||
|
FileSha256: resp.FileSHA256,
|
||||||
|
FileLength: goproto.Uint64(resp.FileLength),
|
||||||
|
Url: &resp.URL,
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Log.Debugf("=> Sending %#v", msg)
|
b.Log.Debugf("=> Sending %#v", msg)
|
||||||
|
|
||||||
// create message ID
|
ID := whatsmeow.GenerateMessageID()
|
||||||
// TODO follow and act if https://github.com/Rhymen/go-whatsapp/issues/101 implemented
|
_, err = b.wc.SendMessage(groupJID, ID, &message)
|
||||||
idBytes := make([]byte, 10)
|
|
||||||
if _, err := rand.Read(idBytes); err != nil {
|
|
||||||
b.Log.Warn(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
message.Info.Id = strings.ToUpper(hex.EncodeToString(idBytes))
|
return ID, err
|
||||||
_, err := b.conn.Send(message)
|
|
||||||
|
|
||||||
return message.Info.Id, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send a message from the bridge to WhatsApp
|
// Send a message from the bridge to WhatsApp
|
||||||
// Required implementation of the Bridger interface
|
|
||||||
// https://github.com/42wim/matterbridge/blob/2cfd880cdb0df29771bf8f31df8d990ab897889d/bridge/bridge.go#L11-L16
|
|
||||||
func (b *Bwhatsapp) Send(msg config.Message) (string, error) {
|
func (b *Bwhatsapp) Send(msg config.Message) (string, error) {
|
||||||
|
groupJID, _ := types.ParseJID(msg.Channel)
|
||||||
|
|
||||||
b.Log.Debugf("=> Receiving %#v", msg)
|
b.Log.Debugf("=> Receiving %#v", msg)
|
||||||
|
|
||||||
// Delete message
|
// Delete message
|
||||||
@ -284,7 +276,7 @@ func (b *Bwhatsapp) Send(msg config.Message) (string, error) {
|
|||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := b.conn.RevokeMessage(msg.Channel, msg.ID, true)
|
_, err := b.wc.RevokeMessage(groupJID, msg.ID)
|
||||||
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@ -317,20 +309,18 @@ func (b *Bwhatsapp) Send(msg config.Message) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post text message
|
var message proto.Message
|
||||||
message := whatsapp.TextMessage{
|
|
||||||
Info: whatsapp.MessageInfo{
|
text := msg.Username + msg.Text
|
||||||
RemoteJid: msg.Channel, // which equals to group id
|
|
||||||
},
|
message.ExtendedTextMessage = &proto.ExtendedTextMessage{
|
||||||
Text: msg.Username + msg.Text,
|
Text: &text,
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Log.Debugf("=> Sending %#v", msg)
|
b.Log.Debugf("=> Sending %#v", msg)
|
||||||
|
|
||||||
return b.conn.Send(message)
|
ID := whatsmeow.GenerateMessageID()
|
||||||
}
|
_, err := b.wc.SendMessage(groupJID, ID, &message)
|
||||||
|
|
||||||
// TODO do we want that? to allow login with QR code from a bridged channel? https://github.com/tulir/mautrix-whatsapp/blob/513eb18e2d59bada0dd515ee1abaaf38a3bfe3d5/commands.go#L76
|
return ID, err
|
||||||
//func (b *Bwhatsapp) Command(cmd string) string {
|
}
|
||||||
// return ""
|
|
||||||
//}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user