stream.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "github.com/Rhymen/go-whatsapp"
  20. )
  21. type StreamType string
  22. const (
  23. StreamUpdate = "update"
  24. StreamSleep = "asleep"
  25. )
  26. type StreamEvent struct {
  27. Type StreamType
  28. Boolean bool
  29. Version string
  30. }
  31. type StreamEventHandler interface {
  32. whatsapp.Handler
  33. HandleStreamEvent(StreamEvent)
  34. }
  35. func (ext *ExtendedConn) handleMessageStream(message []json.RawMessage) {
  36. var event StreamEvent
  37. err := json.Unmarshal(message[0], &event.Type)
  38. if err != nil {
  39. ext.jsonParseError(err)
  40. return
  41. }
  42. if event.Type == StreamUpdate && len(message) > 4 {
  43. json.Unmarshal(message[1], event.Boolean)
  44. json.Unmarshal(message[2], event.Version)
  45. }
  46. for _, handler := range ext.handlers {
  47. streamHandler, ok := handler.(StreamEventHandler)
  48. if !ok {
  49. continue
  50. }
  51. if ext.shouldCallSynchronously(streamHandler) {
  52. streamHandler.HandleStreamEvent(event)
  53. } else {
  54. go streamHandler.HandleStreamEvent(event)
  55. }
  56. }
  57. }