Skip to content
This repository has been archived by the owner on Mar 2, 2024. It is now read-only.

add generic analytics section for segment compatible api #323

Merged
merged 3 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions mautrix_facebook/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@
from mautrix.bridge import Bridge
from mautrix.types import RoomID, UserID

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
from .presence import PresenceUpdater
from .puppet import Puppet
from .segment_analytics import init as init_segment
from .user import User
from .util.interval import get_interval
from .version import linkified_version, version
Expand Down Expand Up @@ -65,10 +65,6 @@ def prepare_bridge(self) -> None:
super().prepare_bridge()
if self.config["appservice.public.enabled"]:
secret = self.config["appservice.public.shared_secret"]
segment_key = self.config["appservice.public.segment_key"]
segment_user_id = self.config["appservice.public.segment_user_id"]
if segment_key:
init_segment(segment_key, segment_user_id)
self.public_website = PublicBridgeWebsite(
loop=self.loop,
shared_secret=secret,
Expand All @@ -78,6 +74,10 @@ def prepare_bridge(self) -> None:
)
else:
self.public_website = None

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

Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
from __future__ import annotations

from urllib.parse import urlunparse
import logging

from yarl import URL
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The imports and type hint of analytics_url also need to be changed (github just isn't nice for suggestions across many places)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, as soon as I pushed the commit suggestion I realised that would happen.

import aiohttp

from mautrix.util import background_task

from . import user as u

log = logging.getLogger("mau.web.public.analytics")
segment_url: URL = URL("https://api.segment.io/v1/track")
http: aiohttp.ClientSession | None = None
segment_key: str | None = None
segment_user_id: str | 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:
await http.post(
segment_url,
analytics_url,
json={
"userId": segment_user_id or user.mxid,
"userId": analytics_user_id or user.mxid,
"event": event,
"properties": {"bridge": "facebook", **properties},
},
auth=aiohttp.BasicAuth(login=segment_key, encoding="utf-8"),
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 segment_key:
if analytics_token:
background_task.create(_track(user, event, properties or {}))


def init(key, user_id: str | None = None):
global segment_key, segment_user_id, http
segment_key = key
segment_user_id = user_id
def init(host: str | None, token: str | None, user_id: str | None = None):
if not host or not token:
return
global analytics_url, analytics_token, analytics_user_id, http
analytics_url = URL.build(scheme="https", host=host, path="/v1/track")
analytics_token = token
analytics_user_id = user_id
http = aiohttp.ClientSession()
12 changes: 10 additions & 2 deletions mautrix_facebook/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,16 @@ def do_update(self, helper: ConfigUpdateHelper) -> None:
else:
copy("appservice.public.shared_secret")
copy("appservice.public.allow_matrix_login")
copy("appservice.public.segment_key")
copy("appservice.public.segment_user_id")

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")

copy("metrics.enabled")
copy("metrics.listen_port")
Expand Down
14 changes: 9 additions & 5 deletions mautrix_facebook/example-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,6 @@ appservice:
shared_secret: generate
# Allow logging in within Matrix. If false, users can only log in using the web interface.
allow_matrix_login: true
# 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: facebook
Expand All @@ -88,6 +83,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
2 changes: 1 addition & 1 deletion mautrix_facebook/portal.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus

from . import matrix as m, puppet as p, user as u
from .analytics import track
from .config import Config
from .db import (
Backfill,
Expand All @@ -78,7 +79,6 @@
UserPortal as UserPortal,
)
from .formatter import facebook_to_matrix, matrix_to_facebook
from .segment_analytics import track

if TYPE_CHECKING:
from .__main__ import MessengerBridge
Expand Down
2 changes: 1 addition & 1 deletion mautrix_facebook/web/public.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from mautrix.util.signed_token import verify_token

from .. import puppet as pu, user as u
from ..segment_analytics import track
from ..analytics import track


class InvalidTokenError(Exception):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import setuptools

from mautrix_facebook.get_version import git_tag, git_revision, version, linkified_version
from mautrix_facebook.get_version import git_revision, git_tag, linkified_version, version

try:
long_desc = open("README.md").read()
Expand Down
Loading