presence.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2019 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package whatsappExt
  17. import (
  18. "encoding/json"
  19. "strings"
  20. "github.com/Rhymen/go-whatsapp"
  21. )
  22. type Presence struct {
  23. JID string `json:"id"`
  24. SenderJID string `json:"participant"`
  25. Status whatsapp.Presence `json:"type"`
  26. Timestamp int64 `json:"t"`
  27. Deny bool `json:"deny"`
  28. }
  29. type PresenceHandler interface {
  30. whatsapp.Handler
  31. HandlePresence(Presence)
  32. }
  33. func (ext *ExtendedConn) handleMessagePresence(message []byte) {
  34. var event Presence
  35. err := json.Unmarshal(message, &event)
  36. if err != nil {
  37. ext.jsonParseError(err)
  38. return
  39. }
  40. event.JID = strings.Replace(event.JID, OldUserSuffix, NewUserSuffix, 1)
  41. if len(event.SenderJID) == 0 {
  42. event.SenderJID = event.JID
  43. } else {
  44. event.SenderJID = strings.Replace(event.SenderJID, OldUserSuffix, NewUserSuffix, 1)
  45. }
  46. for _, handler := range ext.handlers {
  47. presenceHandler, ok := handler.(PresenceHandler)
  48. if !ok {
  49. continue
  50. }
  51. if ext.shouldCallSynchronously(presenceHandler) {
  52. presenceHandler.HandlePresence(event)
  53. } else {
  54. go presenceHandler.HandlePresence(event)
  55. }
  56. }
  57. }