numerous-vr-95901
12/10/2025, 9:21 PMtall-airline-16756
12/10/2025, 9:21 PMtall-airline-16756
12/10/2025, 9:21 PMnumerous-vr-95901
12/10/2025, 9:22 PMtall-airline-16756
12/10/2025, 9:22 PMparticipant_joined and participant_left to record session start/stop times.
• Maintain a per-user minutes counter in your database.
• On join, check remaining minutes; if none, immediately disconnect the participant.
• While in a session, enforce limits by scheduling a disconnect or checking elapsed time periodically.
2) Data model (minimal)
• users: { identity, minutes_allowed }
• user_usage: { identity, total_seconds_used }
• active_sessions: { room_id, participant_sid, identity, joined_at }
3) Flow and key actions
• participant_joined webhook:
a. Insert active_sessions record with joined_at timestamp.
b. Compute remaining = minutes_allowed*60 - total_seconds_used.
c. If remaining <= 0 -> disconnect now (see API call below).
d. Else schedule a job to disconnect after remaining seconds (or store scheduled job id).
• participant_left webhook:
a. Lookup active_sessions by participant_sid (or identity + room_id).
b. Compute session_seconds = now - joined_at.
c. Add session_seconds to user_usage.total_seconds_used.
d. Remove active_sessions record.
e. If you had a scheduled disconnect job, cancel it.
• Periodic safety check (optional):
◦ Run a short cron (e.g., every 30s) that scans active_sessions and enforces disconnects for any that exceed allowed time (guards against missed webhooks or clock skew).
4) How to disconnect a participant (LiveKit REST call)
• Use the LiveKit REST/admin API to remove a participant from a room by participant SID (server-side). Call the participant removal endpoint when you decide to end the session.
• Perform this from your backend (server-authenticated) — do not rely on client-side disconnects for enforcement.
5) Race conditions & reliability tips
• Use participant SID as the canonical session key (safer than identity alone).
• Persist joined_at immediately on webhook receipt to avoid lost events.
• Use idempotent updates when adding session seconds (e.g., mark processed events).
• Schedule a server-side job for the disconnect rather than trusting client timers.
• Implement periodic reconciliation via the Analytics API or room queries to repair missed updates.
6) Example sequence (summary)
1. participant_joined -> store joined_at, calc remaining, schedule disconnect in remaining seconds.
2. participant_left -> compute elapsed, increment usage, cancel scheduled disconnect.
3. Scheduled disconnect fires -> call LiveKit participant remove API, update usage as needed.
If you’d like, I can:
• Provide example webhook payload handling pseudo-code in your language (Node/Python/Go).
• Show the exact REST call payload to remove a participant (with participant_sid) and error handling.
Which would you prefer?numerous-vr-95901
12/10/2025, 9:29 PMtall-airline-16756
12/10/2025, 9:29 PMnumerous-vr-95901
12/10/2025, 9:33 PMtall-airline-16756
12/10/2025, 9:34 PMnumerous-vr-95901
12/10/2025, 9:36 PMtall-airline-16756
12/10/2025, 9:36 PMjoinedAt, leftAt, and connectionMinutes.
• A short example request + minimal response parsing to compute/aggregate minutes per user.
2) Quick facts you can rely on
• Use the Analytics API endpoints: List Sessions, then Get Session Details for each session. Session details include per‑participant timestamps and connectionMinutes.
• Authenticate with your project/server credentials (server-side only).
• You can aggregate connectionMinutes per participant identity across sessions to get total minutes.
Which runtime would you like the sample code in (Node, Python, or Go)?numerous-vr-95901
12/10/2025, 9:37 PMtall-airline-16756
12/10/2025, 9:37 PMconnectionMinutes. Replace API_KEY, API_SECRET, and ANALYTICS_BASE_URL with your project credentials and the Analytics API base URL.
Node (fetch + HMAC auth signing)
// Node 18+ or environment with fetch
import crypto from "crypto";
const API_KEY = "API_KEY";
const API_SECRET = "API_SECRET";
const BASE = "https://analytics.livekit.io/v1"; // replace if different
function makeAuthHeader(path, method = "GET", body = "") {
const ts = Math.floor(Date.now() / 1000);
const payload = `${ts}\n${method}\n${path}\n${body}`;
const sig = crypto.createHmac("sha256", API_SECRET).update(payload).digest("hex");
return `LiveKit ${API_KEY}:${sig}:${ts}`;
}
async function listSessions(limit = 100, pageToken = "") {
const path = `/sessions?limit=${limit}${pageToken ? `&pageToken=${pageToken}` : ""}`;
const headers = { Authorization: makeAuthHeader(path) };
const res = await fetch(BASE + path, { headers });
return res.json();
}
async function getSessionDetails(sessionId) {
const path = `/sessions/${sessionId}`;
const headers = { Authorization: makeAuthHeader(path) };
const res = await fetch(BASE + path, { headers });
return res.json();
}
async function aggregateConnectionMinutes() {
let pageToken = "";
const totals = {}; // identity -> minutes
do {
const sessionsResp = await listSessions(100, pageToken);
for (const s of sessionsResp.sessions || []) {
const details = await getSessionDetails(s.sessionId);
for (const p of details.participants || []) {
const id = p.participantIdentity || p.identity || p.participantIdentity;
const minutes = p.connectionMinutes ?? 0;
totals[id] = (totals[id] || 0) + minutes;
}
}
pageToken = sessionsResp.nextPageToken || "";
} while (pageToken);
return totals;
}
// Example usage
aggregateConnectionMinutes().then(console.log).catch(console.error);
Python (requests + HMAC auth signing)
import time
import hmac
import hashlib
import requests
API_KEY = "API_KEY"
API_SECRET = b"API_SECRET"
BASE = "https://analytics.livekit.io/v1" # replace if different
def make_auth_header(path, method="GET", body=""):
ts = str(int(time.time()))
payload = f"{ts}\n{method}\n{path}\n{body}".encode()
sig = hmac.new(API_SECRET, payload, hashlib.sha256).hexdigest()
return f"LiveKit {API_KEY}:{sig}:{ts}"
def list_sessions(limit=100, page_token=""):
path = f"/sessions?limit={limit}"
if page_token:
path += f"&pageToken={page_token}"
headers = {"Authorization": make_auth_header(path)}
r = requests.get(BASE + path, headers=headers)
r.raise_for_status()
return r.json()
def get_session_details(session_id):
path = f"/sessions/{session_id}"
headers = {"Authorization": make_auth_header(path)}
r = requests.get(BASE + path, headers=headers)
r.raise_for_status()
return r.json()
def aggregate_connection_minutes():
page_token = ""
totals = {} # identity -> minutes
while True:
sessions_resp = list_sessions(100, page_token)
for s in sessions_resp.get("sessions", []):
details = get_session_details(s["sessionId"])
for p in details.get("participants", []):
identity = p.get("participantIdentity") or p.get("identity")
minutes = p.get("connectionMinutes", 0)
totals[identity] = totals.get(identity, 0) + minutes
page_token = sessions_resp.get("nextPageToken") or ""
if not page_token:
break
return totals
if __name__ == "__main__":
print(aggregate_connection_minutes())
Notes and tips
• The examples use HMAC signing (timestamp + method + path + body). Adjust if your Analytics endpoint uses a different auth scheme; ensure server-side only usage of the API key/secret.
• connectionMinutes is available in session details per participant; aggregate by participant identity to get totals.
• Handle pagination (nextPageToken) when listing sessions.
• Use session detail timestamps (`joinedAt`/`leftAt`) if you need raw times instead of the precomputed connectionMinutes.
If you want, I can:
• Convert these into production-ready snippets with retries, backoff, and error handling.
• Provide an example that aggregates minutes for a single participant over a given date range. Which would you like?