video_monitor/app/services/telemetry.py

64 lines
2.4 KiB
Python
Raw Normal View History

2026-08-30 22:22:11 +08:00
"""Opt-in, minimal, HTTPS-only telemetry and update checks."""
import os
from urllib.parse import urlparse
def _https_endpoint(env_name):
endpoint = os.environ.get(env_name, "").strip()
if not endpoint:
return ""
parsed = urlparse(endpoint)
if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password:
raise ValueError("%s must be an HTTPS URL without embedded credentials" % env_name)
return endpoint
def heartbeat_payload(sequence):
from framework.settings import PROJECT_FLAG, PROJECT_VERSION
return {
"event": "heartbeat",
"product": PROJECT_FLAG,
"version": PROJECT_VERSION,
"sequence": int(sequence),
}
def send_heartbeat(sequence, session=None):
from app.utils.GlobalUtils import g_config
if not getattr(g_config, "telemetryEnabled", False):
return False, "telemetry disabled"
endpoint = _https_endpoint("MONITOR_TELEMETRY_ENDPOINT")
if not endpoint:
return False, "telemetry endpoint not configured"
if session is None:
import requests
session = requests
response = session.post(
endpoint, json=heartbeat_payload(sequence), timeout=10, allow_redirects=False
)
return response.status_code == 200, "status=%s" % response.status_code
def check_update(lang=None, session=None):
from app.utils.GlobalUtils import g_config
if not getattr(g_config, "updateCheckEnabled", False):
return False, False, "update check disabled", {}
endpoint = _https_endpoint("MONITOR_UPDATE_ENDPOINT")
if not endpoint:
return False, False, "update endpoint not configured", {}
from framework.settings import PROJECT_FLAG, PROJECT_VERSION
payload = {"product": PROJECT_FLAG, "version": PROJECT_VERSION, "lang": (lang or "")[:12]}
if session is None:
import requests
session = requests
try:
response = session.post(endpoint, json=payload, timeout=10, allow_redirects=False)
if response.status_code != 200:
return True, False, "status=%s" % response.status_code, {}
result = response.json()
if result.get("code") == 1000:
return True, True, str(result.get("msg", "ok")), result.get("data") or {}
return True, False, str(result.get("msg", "no update")), {}
except Exception as exc:
return False, False, str(exc), {}