segment.go 2.3 KB

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