stream.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. go streamHandler.HandleStreamEvent(event)
  52. }
  53. }