segment.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan, Sumner Evans
  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 main
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "net/http"
  21. log "maunium.net/go/maulogger/v2"
  22. "maunium.net/go/mautrix/id"
  23. )
  24. const SegmentURL = "https://api.segment.io/v1/track"
  25. type SegmentClient struct {
  26. key string
  27. log log.Logger
  28. client http.Client
  29. }
  30. var Segment SegmentClient
  31. func (sc *SegmentClient) trackSync(userID id.UserID, event string, properties map[string]interface{}) error {
  32. var buf bytes.Buffer
  33. err := json.NewEncoder(&buf).Encode(map[string]interface{}{
  34. "userId": userID,
  35. "event": event,
  36. "properties": properties,
  37. })
  38. if err != nil {
  39. return err
  40. }
  41. req, err := http.NewRequest("POST", SegmentURL, &buf)
  42. if err != nil {
  43. return err
  44. }
  45. req.SetBasicAuth(sc.key, "")
  46. resp, err := sc.client.Do(req)
  47. if err != nil {
  48. return err
  49. }
  50. defer resp.Body.Close()
  51. return nil
  52. }
  53. func (sc *SegmentClient) IsEnabled() bool {
  54. return len(sc.key) > 0
  55. }
  56. func (sc *SegmentClient) Track(userID id.UserID, event string, properties ...map[string]interface{}) {
  57. if !sc.IsEnabled() {
  58. return
  59. } else if len(properties) > 1 {
  60. panic("Track should be called with at most one property map")
  61. }
  62. go func() {
  63. props := map[string]interface{}{}
  64. if len(properties) > 0 {
  65. props = properties[0]
  66. }
  67. props["bridge"] = "whatsapp"
  68. err := sc.trackSync(userID, event, props)
  69. if err != nil {
  70. sc.log.Errorfln("Error tracking %s: %v", event, err)
  71. } else {
  72. sc.log.Debugln("Tracked", event)
  73. }
  74. }()
  75. }