stream.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. IsOutdated bool
  29. Version string
  30. Extra []json.RawMessage
  31. }
  32. type StreamEventHandler interface {
  33. whatsapp.Handler
  34. HandleStreamEvent(StreamEvent)
  35. }
  36. func (ext *ExtendedConn) handleMessageStream(message []json.RawMessage) {
  37. var event StreamEvent
  38. err := json.Unmarshal(message[0], &event.Type)
  39. if err != nil {
  40. ext.jsonParseError(err)
  41. return
  42. }
  43. if event.Type == StreamUpdate && len(message) >= 3 {
  44. _ = json.Unmarshal(message[1], &event.IsOutdated)
  45. _ = json.Unmarshal(message[2], &event.Version)
  46. if len(message) >= 4 {
  47. event.Extra = message[3:]
  48. }
  49. } else if len(message) >= 2 {
  50. event.Extra = message[1:]
  51. }
  52. for _, handler := range ext.handlers {
  53. streamHandler, ok := handler.(StreamEventHandler)
  54. if !ok {
  55. continue
  56. }
  57. if ext.shouldCallSynchronously(streamHandler) {
  58. streamHandler.HandleStreamEvent(event)
  59. } else {
  60. go streamHandler.HandleStreamEvent(event)
  61. }
  62. }
  63. }