mautrix-whatsapp/analytics.go

97 lines
2.4 KiB
Go
Raw Normal View History

// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2022 Tulir Asokan, Sumner Evans
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/id"
)
type AnalyticsClient struct {
url string
2022-05-16 12:46:18 +02:00
key string
userID string
2022-05-16 12:46:18 +02:00
log log.Logger
client http.Client
}
var Analytics AnalyticsClient
func (sc *AnalyticsClient) trackSync(userID id.UserID, event string, properties map[string]interface{}) error {
2022-05-16 12:46:18 +02:00
var buf bytes.Buffer
var analyticsUserID string
if Analytics.userID != "" {
analyticsUserID = Analytics.userID
} else {
analyticsUserID = userID.String()
}
2022-05-16 12:46:18 +02:00
err := json.NewEncoder(&buf).Encode(map[string]interface{}{
"userId": analyticsUserID,
"event": event,
"properties": properties,
2022-05-16 12:46:18 +02:00
})
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, sc.url, &buf)
if err != nil {
return err
}
2022-05-16 12:46:18 +02:00
req.SetBasicAuth(sc.key, "")
resp, err := sc.client.Do(req)
if err != nil {
return err
}
_ = resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
return nil
}
func (sc *AnalyticsClient) IsEnabled() bool {
2022-05-16 12:46:18 +02:00
return len(sc.key) > 0
}
func (sc *AnalyticsClient) Track(userID id.UserID, event string, properties ...map[string]interface{}) {
2022-05-16 12:46:18 +02:00
if !sc.IsEnabled() {
return
2022-05-16 12:46:18 +02:00
} else if len(properties) > 1 {
panic("Track should be called with at most one property map")
}
2022-05-16 12:46:18 +02:00
go func() {
props := map[string]interface{}{}
if len(properties) > 0 {
props = properties[0]
}
props["bridge"] = "whatsapp"
2022-05-16 12:46:18 +02:00
err := sc.trackSync(userID, event, props)
if err != nil {
2022-05-16 12:46:18 +02:00
sc.log.Errorfln("Error tracking %s: %v", event, err)
} else {
sc.log.Debugln("Tracked", event)
}
2022-05-16 12:46:18 +02:00
}()
}