Skip to content

Commit

Permalink
analytics: generisize to any Segment-compatible API
Browse files Browse the repository at this point in the history
Signed-off-by: Sumner Evans <[email protected]>
  • Loading branch information
sumnerevans committed Sep 29, 2023
1 parent 9e7cd5d commit 5b62118
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 61 deletions.
13 changes: 7 additions & 6 deletions linkedin_matrix/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
from mautrix.util.async_db import Database

from . import commands as _ # noqa: F401
from .analytics import init as init_analytics
from .config import Config
from .db import init as init_db, upgrade_table
from .matrix import MatrixHandler
from .portal import Portal # noqa: I100 (needs to be after because it relies on Puppet)
from .puppet import Puppet
from .segment_analytics import init as init_segment
from .user import User
from .version import linkified_version, version
from .web import ProvisioningAPI
Expand Down Expand Up @@ -66,16 +66,17 @@ def prepare_stop(self):
def prepare_bridge(self):
super().prepare_bridge()
if self.config["appservice.provisioning.enabled"]:
segment_key = self.config["appservice.provisioning.segment_key"]
segment_user_id = self.config["appservice.provisioning.segment_user_id"]
if segment_key:
init_segment(segment_key, segment_user_id)

secret = self.config["appservice.provisioning.shared_secret"]
prefix = self.config["appservice.provisioning.prefix"]
self.provisioning_api = ProvisioningAPI(secret)
self.az.app.add_subapp(prefix, self.provisioning_api.app)

if self.config["analytics.token"]:
token = self.config["analytics.token"]
user_id = self.config["analytics.user_id"]
if token:
init_analytics(token, user_id)

async def stop(self):
await Puppet.close()
self.log.debug("Saving user sessions")
Expand Down
48 changes: 48 additions & 0 deletions linkedin_matrix/analytics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

from urllib.parse import urlunparse
import logging

import aiohttp

from mautrix.util import background_task

from . import user as u

log = logging.getLogger("mau.web.public.analytics")
http: aiohttp.ClientSession | None = None
analytics_url: str | None = None
analytics_token: str | None = None
analytics_user_id: str | None = None


async def _track(user: u.User, event: str, properties: dict) -> None:
assert analytics_token
assert analytics_url
assert http
await http.post(
analytics_url,
json={
"userId": analytics_user_id or user.mxid,
"event": event,
"properties": {"bridge": "linkedin", **properties},
},
auth=aiohttp.BasicAuth(login=analytics_token, encoding="utf-8"),
)
log.debug(f"Tracked {event}")


def track(user: u.User, event: str, properties: dict | None = None):
if analytics_token:
background_task.create(_track(user, event, properties or {}))


def init(base_url: str | None, token: str | None, user_id: str | None = None):
if not base_url or not token:
return
log.info("Initialising segment-compatible analytics")
global analytics_url, analytics_token, analytics_user_id, http
analytics_url = urlunparse(("https", base_url, "/v1/track", "", "", ""))
analytics_token = token
analytics_user_id = user_id
http = aiohttp.ClientSession()
13 changes: 11 additions & 2 deletions linkedin_matrix/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ def do_update(self, helper: ConfigUpdateHelper):
copy("appservice.provisioning.shared_secret")
if base["appservice.provisioning.shared_secret"] == "generate":
base["appservice.provisioning.shared_secret"] = self._new_token()
copy("appservice.provisioning.segment_key")
copy("appservice.provisioning.segment_user_id")

# bridge
copy("bridge.backfill.disable_notifications")
Expand Down Expand Up @@ -74,6 +72,17 @@ def do_update(self, helper: ConfigUpdateHelper):
if base["bridge.private_chat_portal_meta"] not in ("default", "always", "never"):
base["bridge.private_chat_portal_meta"] = "default"

# analytics
copy("analytics.host")
if "appservice.provisioning.segment_key" in self:
base["analytics.token"] = self["appservice.provisioning.segment_key"]
else:
copy("analytics.token")
if "appservice.provisioning.segment_user_id" in self:
base["analytics.user_id"] = self["appservice.provisioning.segment_user_id"]
else:
copy("analytics.user_id")

# Metrics
copy("metrics.enabled")
copy("metrics.listen_port")
Expand Down
15 changes: 9 additions & 6 deletions linkedin_matrix/example-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ appservice:
# Set to "generate" to generate and save a new token.
shared_secret: generate

# Segment API key to enable analytics tracking for web server endpoints. Set to null to disable.
# Currently the only events are login start, success and fail.
segment_key: null
# Optional user_id to use when sending Segment events. If null, defaults to using mxID.
segment_user_id: null

# The unique ID of this appservice.
id: linkedin
# Username of the appservice bot.
Expand All @@ -84,6 +78,15 @@ appservice:
as_token: "This value is generated when generating the registration"
hs_token: "This value is generated when generating the registration"

# Segment-compatible analytics endpoint for tracking some events, like provisioning API login and encryption errors.
analytics:
# Hostname of the tracking server. The path is hardcoded to /v1/track
host: api.segment.io
# API key to send with tracking requests. Tracking is disabled if this is null.
token: null
# Optional user ID for tracking events. If null, defaults to using Matrix user ID.
user_id: null

# Prometheus telemetry config. Requires prometheus-client to be installed.
metrics:
enabled: false
Expand Down
46 changes: 0 additions & 46 deletions linkedin_matrix/segment_analytics.py

This file was deleted.

2 changes: 1 addition & 1 deletion linkedin_matrix/web/provisioning_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from mautrix.util.logging import TraceLogger

from .. import user as u
from ..segment_analytics import track
from ..analytics import track


class ProvisioningAPI:
Expand Down

0 comments on commit 5b62118

Please sign in to comment.