fixes lol
All checks were successful
Build and Push / build-all (push) Successful in 9m6s

This commit is contained in:
doomtube 2026-01-08 22:57:43 -05:00
parent 9ff89fa18b
commit 7bcbc6b73b
5 changed files with 131 additions and 26 deletions

View file

@ -767,6 +767,7 @@ void RealmController::getRealmByName(const HttpRequestPtr &,
"r.chat_enabled, r.chat_guests_allowed, " "r.chat_enabled, r.chat_guests_allowed, "
"r.chat_slow_mode_seconds, r.chat_retention_hours, " "r.chat_slow_mode_seconds, r.chat_retention_hours, "
"r.offline_image_url, r.description, r.user_id, r.playlist_control_mode, r.playlist_whitelist, r.title_color, " "r.offline_image_url, r.description, r.user_id, r.playlist_control_mode, r.playlist_whitelist, r.title_color, "
"r.live_started_at, "
"u.username, u.avatar_url, u.user_color FROM realms r " "u.username, u.avatar_url, u.user_color FROM realms r "
"JOIN users u ON r.user_id = u.id " "JOIN users u ON r.user_id = u.id "
"WHERE r.name = $1 AND r.is_active = true" "WHERE r.name = $1 AND r.is_active = true"
@ -808,6 +809,10 @@ void RealmController::getRealmByName(const HttpRequestPtr &,
realm["avatarUrl"] = r[0]["avatar_url"].isNull() ? "" : r[0]["avatar_url"].as<std::string>(); realm["avatarUrl"] = r[0]["avatar_url"].isNull() ? "" : r[0]["avatar_url"].as<std::string>();
realm["colorCode"] = r[0]["user_color"].isNull() ? "" : r[0]["user_color"].as<std::string>(); realm["colorCode"] = r[0]["user_color"].isNull() ? "" : r[0]["user_color"].as<std::string>();
realm["titleColor"] = r[0]["title_color"].isNull() ? "#ffffff" : r[0]["title_color"].as<std::string>(); realm["titleColor"] = r[0]["title_color"].isNull() ? "#ffffff" : r[0]["title_color"].as<std::string>();
// Include live_started_at for stream duration display
if (!r[0]["live_started_at"].isNull()) {
realm["liveStartedAt"] = r[0]["live_started_at"].as<std::string>();
}
callback(jsonResp(resp)); callback(jsonResp(resp));
} }

View file

@ -119,8 +119,10 @@ void StatsService::pollOmeStats() {
LOG_INFO << "Processing active stream: " << streamKey; LOG_INFO << "Processing active stream: " << streamKey;
// IMMEDIATELY update database to mark as live and get realm ID // IMMEDIATELY update database to mark as live and get realm ID
// Set live_started_at only if not already set (preserves start time across polls)
auto dbClient = app().getDbClient(); auto dbClient = app().getDbClient();
*dbClient << "UPDATE realms SET is_live = true, viewer_count = 0, " *dbClient << "UPDATE realms SET is_live = true, viewer_count = 0, "
"live_started_at = COALESCE(live_started_at, CURRENT_TIMESTAMP), "
"updated_at = CURRENT_TIMESTAMP WHERE stream_key = $1 RETURNING id" "updated_at = CURRENT_TIMESTAMP WHERE stream_key = $1 RETURNING id"
<< streamKey << streamKey
>> [streamKey](const orm::Result& r) { >> [streamKey](const orm::Result& r) {
@ -150,6 +152,7 @@ void StatsService::pollOmeStats() {
if (activeStreamKeys.find(key) == activeStreamKeys.end()) { if (activeStreamKeys.find(key) == activeStreamKeys.end()) {
LOG_INFO << "Marking realm as offline: " << key; LOG_INFO << "Marking realm as offline: " << key;
*db << "UPDATE realms SET is_live = false, viewer_count = 0, " *db << "UPDATE realms SET is_live = false, viewer_count = 0, "
"live_started_at = NULL, "
"updated_at = CURRENT_TIMESTAMP WHERE stream_key = $1" "updated_at = CURRENT_TIMESTAMP WHERE stream_key = $1"
<< key << key
>> [key](const orm::Result&) { >> [key](const orm::Result&) {
@ -185,29 +188,44 @@ void StatsService::updateStreamStats(const std::string& streamKey) {
// Only broadcast if stream has meaningful data or is live // Only broadcast if stream has meaningful data or is live
if (updatedStats.isLive || updatedStats.totalBytesIn > 0 || updatedStats.uniqueViewers > 0) { if (updatedStats.isLive || updatedStats.totalBytesIn > 0 || updatedStats.uniqueViewers > 0) {
Json::Value msg; // Fetch live_started_at for duration display
msg["type"] = "stats_update"; auto dbClient = app().getDbClient();
msg["stream_key"] = streamKey; *dbClient << "SELECT live_started_at FROM realms WHERE stream_key = $1"
<< streamKey
>> [streamKey, updatedStats](const orm::Result& r) {
Json::Value msg;
msg["type"] = "stats_update";
msg["stream_key"] = streamKey;
auto& s = msg["stats"]; auto& s = msg["stats"];
JSON_INT(s, "connections", updatedStats.uniqueViewers); JSON_INT(s, "connections", updatedStats.uniqueViewers);
JSON_INT(s, "raw_connections", updatedStats.currentConnections); JSON_INT(s, "raw_connections", updatedStats.currentConnections);
s["bitrate"] = updatedStats.bitrate; s["bitrate"] = updatedStats.bitrate;
s["resolution"] = updatedStats.resolution; s["resolution"] = updatedStats.resolution;
s["fps"] = updatedStats.fps; s["fps"] = updatedStats.fps;
s["codec"] = updatedStats.codec; s["codec"] = updatedStats.codec;
s["is_live"] = updatedStats.isLive; s["is_live"] = updatedStats.isLive;
JSON_INT(s, "bytes_in", updatedStats.totalBytesIn); JSON_INT(s, "bytes_in", updatedStats.totalBytesIn);
JSON_INT(s, "bytes_out", updatedStats.totalBytesOut); JSON_INT(s, "bytes_out", updatedStats.totalBytesOut);
// Protocol breakdown // Include live_started_at for duration tracking
auto& pc = s["protocol_connections"]; if (!r.empty() && !r[0]["live_started_at"].isNull()) {
JSON_INT(pc, "webrtc", updatedStats.protocolConnections.webrtc); s["live_started_at"] = r[0]["live_started_at"].as<std::string>();
JSON_INT(pc, "hls", updatedStats.protocolConnections.hls); }
JSON_INT(pc, "llhls", updatedStats.protocolConnections.llhls);
JSON_INT(pc, "dash", updatedStats.protocolConnections.dash);
StreamWebSocketController::broadcastStatsUpdate(msg); // Protocol breakdown
auto& pc = s["protocol_connections"];
JSON_INT(pc, "webrtc", updatedStats.protocolConnections.webrtc);
JSON_INT(pc, "hls", updatedStats.protocolConnections.hls);
JSON_INT(pc, "llhls", updatedStats.protocolConnections.llhls);
JSON_INT(pc, "dash", updatedStats.protocolConnections.dash);
StreamWebSocketController::broadcastStatsUpdate(msg);
}
>> [streamKey](const orm::DrogonDbException& e) {
LOG_ERROR << "Failed to fetch live_started_at for " << streamKey
<< ": " << e.base().what();
};
} }
} }
}); });

View file

@ -1251,3 +1251,18 @@ BEGIN
ALTER TABLE users ADD COLUMN screensaver_timeout_minutes INTEGER DEFAULT 5; ALTER TABLE users ADD COLUMN screensaver_timeout_minutes INTEGER DEFAULT 5;
END IF; END IF;
END $$; END $$;
-- ============================================
-- LIVE STREAM DURATION TRACKING
-- ============================================
-- Add live_started_at column to realms table (tracks when stream went live for duration display)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'realms' AND column_name = 'live_started_at'
) THEN
ALTER TABLE realms ADD COLUMN live_started_at TIMESTAMP WITH TIME ZONE;
END IF;
END $$;

View file

@ -1,5 +1,6 @@
<script> <script>
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import { get } from 'svelte/store';
import { import {
filteredMessages, filteredMessages,
connectionStatus, connectionStatus,
@ -40,6 +41,7 @@
let messagesContainer; let messagesContainer;
let autoScroll = true; let autoScroll = true;
let initialScrollDone = false; // Prevent handleScroll from disabling autoScroll before initial scroll
let showMenu = false; // Combined settings + participants menu let showMenu = false; // Combined settings + participants menu
let configCollapsed = false; // Track if config section is collapsed let configCollapsed = false; // Track if config section is collapsed
let usersCollapsed = false; // Track if users section is collapsed let usersCollapsed = false; // Track if users section is collapsed
@ -207,13 +209,15 @@
const scrollToBottom = () => { const scrollToBottom = () => {
if (autoScroll && messagesContainer) { if (autoScroll && messagesContainer) {
requestAnimationFrame(() => { requestAnimationFrame(() => {
if ($chatLayout.messagesFromTop) { const messagesFromTop = get(chatLayout).messagesFromTop;
if (messagesFromTop) {
// column-reverse: newest at top, scroll to top // column-reverse: newest at top, scroll to top
messagesContainer.scrollTop = 0; messagesContainer.scrollTop = 0;
} else { } else {
// normal: newest at bottom, scroll to bottom // normal: newest at bottom, scroll to bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight; messagesContainer.scrollTop = messagesContainer.scrollHeight;
} }
initialScrollDone = true;
}); });
} }
}; };
@ -273,6 +277,9 @@
} }
function handleScroll() { function handleScroll() {
// Ignore scroll events before initial scroll is done (prevents browser's initial position from disabling autoScroll)
if (!initialScrollDone) return;
const { scrollTop, scrollHeight, clientHeight } = messagesContainer; const { scrollTop, scrollHeight, clientHeight } = messagesContainer;
if ($chatLayout.messagesFromTop) { if ($chatLayout.messagesFromTop) {
// column-reverse: user at "newest" means scrollTop near 0 // column-reverse: user at "newest" means scrollTop near 0

View file

@ -72,9 +72,14 @@
resolution: 'N/A', resolution: 'N/A',
codec: 'N/A', codec: 'N/A',
fps: 0, fps: 0,
isLive: false isLive: false,
liveStartedAt: null
}; };
// Duration display for live stream
let durationDisplay = '';
let durationInterval;
onMount(async () => { onMount(async () => {
const realmName = $page.params.realm; const realmName = $page.params.realm;
@ -154,6 +159,9 @@
if (statsInterval) { if (statsInterval) {
clearInterval(statsInterval); clearInterval(statsInterval);
} }
if (durationInterval) {
clearInterval(durationInterval);
}
if (llhlsRetryTimeout) { if (llhlsRetryTimeout) {
clearTimeout(llhlsRetryTimeout); clearTimeout(llhlsRetryTimeout);
} }
@ -166,6 +174,12 @@
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
realm = data.realm; realm = data.realm;
// Initialize liveStartedAt from realm data if stream is live
if (realm.isLive && realm.liveStartedAt) {
stats.liveStartedAt = realm.liveStartedAt;
stats.isLive = true;
startDurationTimer();
}
// Get the stream key from the database // Get the stream key from the database
const keyResponse = await fetch(`/api/realms/${realm.id}`); const keyResponse = await fetch(`/api/realms/${realm.id}`);
if (keyResponse.ok && keyResponse.status !== 404) { if (keyResponse.ok && keyResponse.status !== 404) {
@ -277,15 +291,27 @@
} }
function updateStatsFromData(data) { function updateStatsFromData(data) {
const wasLive = stats.isLive;
stats = { stats = {
connections: data.connections || 0, connections: data.connections || 0,
bitrate: data.bitrate || 0, bitrate: data.bitrate || 0,
resolution: data.resolution || 'N/A', resolution: data.resolution || 'N/A',
codec: data.codec || 'N/A', codec: data.codec || 'N/A',
fps: data.fps || 0, fps: data.fps || 0,
isLive: data.is_live || false isLive: data.is_live || false,
liveStartedAt: data.live_started_at || stats.liveStartedAt || null
}; };
// Start/stop duration timer based on live status
if (stats.isLive && stats.liveStartedAt && !wasLive) {
startDurationTimer();
} else if (!stats.isLive && wasLive) {
stopDurationTimer();
} else if (stats.isLive && stats.liveStartedAt && !durationInterval) {
// Ensure timer is running if we're live with a start time
startDurationTimer();
}
// Only update isStreaming from stats if player isn't actively playing // Only update isStreaming from stats if player isn't actively playing
// This prevents stats from overriding the player's live state during connection // This prevents stats from overriding the player's live state during connection
if (!playerPlaying) { if (!playerPlaying) {
@ -510,6 +536,36 @@
} }
} }
function formatDuration(startTime) {
if (!startTime) return '';
const elapsed = Math.floor((Date.now() - new Date(startTime).getTime()) / 1000);
if (elapsed < 0) return '0:00';
const hours = Math.floor(elapsed / 3600);
const minutes = Math.floor((elapsed % 3600) / 60);
const seconds = elapsed % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
return `${minutes}:${String(seconds).padStart(2, '0')}`;
}
function startDurationTimer() {
if (durationInterval) return;
durationDisplay = formatDuration(stats.liveStartedAt);
durationInterval = setInterval(() => {
durationDisplay = formatDuration(stats.liveStartedAt);
}, 1000);
}
function stopDurationTimer() {
if (durationInterval) {
clearInterval(durationInterval);
durationInterval = null;
}
durationDisplay = '';
}
// Tiled streams (exclude current stream) // Tiled streams (exclude current stream)
$: tiledStreams = $streamTiles.streams.filter(s => s.streamKey !== streamKey); $: tiledStreams = $streamTiles.streams.filter(s => s.streamKey !== streamKey);
$: hasTiledStreams = tiledStreams.length > 0; $: hasTiledStreams = tiledStreams.length > 0;
@ -1375,6 +1431,10 @@
<span class="badge-divider"></span> <span class="badge-divider"></span>
<span class="badge-segment">{formatBitrate(stats.bitrate)}</span> <span class="badge-segment">{formatBitrate(stats.bitrate)}</span>
{/if} {/if}
{#if stats.isLive && durationDisplay}
<span class="badge-divider"></span>
<span class="badge-segment">{durationDisplay}</span>
{/if}
<span class="badge-divider"></span> <span class="badge-divider"></span>
<span class="badge-segment status" class:live={stats.isLive}> <span class="badge-segment status" class:live={stats.isLive}>
{stats.isLive ? 'LIVE' : 'Offline'} {stats.isLive ? 'LIVE' : 'Offline'}