Reduce browser console debug logs in web player overlay

parent 140f1b85
...@@ -25,25 +25,31 @@ ...@@ -25,25 +25,31 @@
// Store original console.log BEFORE any overrides happen // Store original console.log BEFORE any overrides happen
const originalConsoleLog = console.log.bind(console); const originalConsoleLog = console.log.bind(console);
originalConsoleLog('[WebAdapter] Loading overlay web adapter...'); // Debug mode - set to true to enable verbose logging
const DEBUG = false;
// Debug log function - only logs when DEBUG is true
const debugLog = (...args) => {
if (DEBUG) {
originalConsoleLog('[WebAdapter]', ...args);
}
};
// Check if we're running in Qt WebChannel environment // Check if we're running in Qt WebChannel environment
const isQtEnvironment = typeof qt !== 'undefined' && qt.webChannelTransport; const isQtEnvironment = typeof qt !== 'undefined' && qt.webChannelTransport;
originalConsoleLog('[WebAdapter] Environment detected:', isQtEnvironment ? 'Qt WebChannel' : 'Web Browser');
// If in Qt environment, don't run the web adapter - Qt scripts are loaded by the template // If in Qt environment, don't run the web adapter - Qt scripts are loaded by the template
if (isQtEnvironment) { if (isQtEnvironment) {
originalConsoleLog('[WebAdapter] Qt environment detected, web adapter not needed'); debugLog('Qt environment detected, web adapter not needed');
return; return;
} }
originalConsoleLog('[WebAdapter] Web environment detected, setting up postMessage bridge'); debugLog('Web environment detected, setting up postMessage bridge');
// Web environment - prevent Qt script loading errors // Web environment - prevent Qt script loading errors
// Create dummy QWebChannel for browsers (prevents errors from qrc:/// URLs) // Create dummy QWebChannel for browsers (prevents errors from qrc:/// URLs)
window.QWebChannel = function(transport, callback) { window.QWebChannel = function(transport, callback) {
originalConsoleLog('[WebAdapter] QWebChannel called in web environment - using adapter instead'); debugLog('QWebChannel called in web environment - using adapter instead');
// The adapter already set up window.overlay, so just call callback if provided // The adapter already set up window.overlay, so just call callback if provided
if (callback && window.overlay) { if (callback && window.overlay) {
callback({ objects: { overlay: window.overlay } }); callback({ objects: { overlay: window.overlay } });
...@@ -55,7 +61,7 @@ ...@@ -55,7 +61,7 @@
if (event.target && (event.target.tagName === 'SCRIPT' || event.target.tagName === 'LINK')) { if (event.target && (event.target.tagName === 'SCRIPT' || event.target.tagName === 'LINK')) {
const src = event.target.src || event.target.href || ''; const src = event.target.src || event.target.href || '';
if (src.startsWith('qrc:///') || src.startsWith('overlay://')) { if (src.startsWith('qrc:///') || src.startsWith('overlay://')) {
originalConsoleLog('[WebAdapter] Suppressed Qt URL error:', src); debugLog('Suppressed Qt URL error:', src);
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
return true; return true;
...@@ -68,7 +74,7 @@ ...@@ -68,7 +74,7 @@
if (event.reason && event.reason.message) { if (event.reason && event.reason.message) {
const msg = event.reason.message; const msg = event.reason.message;
if (msg.includes('qrc:///') || msg.includes('overlay://')) { if (msg.includes('qrc:///') || msg.includes('overlay://')) {
originalConsoleLog('[WebAdapter] Suppressed Qt URL promise rejection:', msg); debugLog('Suppressed Qt URL promise rejection:', msg);
event.preventDefault(); event.preventDefault();
return true; return true;
} }
...@@ -79,7 +85,7 @@ ...@@ -79,7 +85,7 @@
const originalFetch = window.fetch; const originalFetch = window.fetch;
window.fetch = function(url, options) { window.fetch = function(url, options) {
if (typeof url === 'string' && (url.startsWith('qrc:///') || url.startsWith('overlay://'))) { if (typeof url === 'string' && (url.startsWith('qrc:///') || url.startsWith('overlay://'))) {
originalConsoleLog('[WebAdapter] Blocking fetch to Qt URL:', url); debugLog('Blocking fetch to Qt URL:', url);
return Promise.resolve(new Response('', { status: 200 })); return Promise.resolve(new Response('', { status: 200 }));
} }
return originalFetch.apply(this, arguments); return originalFetch.apply(this, arguments);
...@@ -89,7 +95,7 @@ ...@@ -89,7 +95,7 @@
const originalOpen = XMLHttpRequest.prototype.open; const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) { XMLHttpRequest.prototype.open = function(method, url) {
if (typeof url === 'string' && (url.startsWith('qrc:///') || url.startsWith('overlay://'))) { if (typeof url === 'string' && (url.startsWith('qrc:///') || url.startsWith('overlay://'))) {
originalConsoleLog('[WebAdapter] Blocking XHR to Qt URL:', url); debugLog('Blocking XHR to Qt URL:', url);
// Return without actually opening - will fail silently // Return without actually opening - will fail silently
return; return;
} }
...@@ -100,19 +106,19 @@ ...@@ -100,19 +106,19 @@
const originalWrite = document.write; const originalWrite = document.write;
document.write = function(content) { document.write = function(content) {
if (typeof content === 'string' && (content.includes('qrc:///') || content.includes('overlay://'))) { if (typeof content === 'string' && (content.includes('qrc:///') || content.includes('overlay://'))) {
originalConsoleLog('[WebAdapter] Blocking document.write with Qt URLs'); debugLog('Blocking document.write with Qt URLs');
return; return;
} }
return originalWrite.apply(this, arguments); return originalWrite.apply(this, arguments);
}; };
// Web environment - set up postMessage bridge // Web environment - set up postMessage bridge
originalConsoleLog('[WebAdapter] Setting up postMessage bridge for web environment'); debugLog('Setting up postMessage bridge for web environment');
// Check if we're in standalone mode (no parent window to respond) // Check if we're in standalone mode (no parent window to respond)
const isStandaloneMode = window.parent === window; const isStandaloneMode = window.parent === window;
if (isStandaloneMode) { if (isStandaloneMode) {
originalConsoleLog('[WebAdapter] Standalone mode detected - no parent window, will use direct API calls'); debugLog('Standalone mode detected - no parent window, will use direct API calls');
} }
// Data storage // Data storage
...@@ -158,20 +164,20 @@ ...@@ -158,20 +164,20 @@
// Log function - use original console.log to avoid recursion // Log function - use original console.log to avoid recursion
log: function(message) { log: function(message) {
originalConsoleLog('[Overlay]', message); debugLog('[Overlay]', message);
}, },
// Get fixture data - returns Promise (async like Qt) // Get fixture data - returns Promise (async like Qt)
getFixtureData: function() { getFixtureData: function() {
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
originalConsoleLog('[WebAdapter] getFixtureData called, current data:', fixtureData ? fixtureData.length + ' fixtures' : 'null'); debugLog('getFixtureData called, current data:', fixtureData ? fixtureData.length + ' fixtures' : 'null');
if (fixtureData && fixtureData.length > 0) { if (fixtureData && fixtureData.length > 0) {
originalConsoleLog('[WebAdapter] Returning cached fixture data'); debugLog('Returning cached fixture data');
resolve(JSON.stringify(fixtureData)); resolve(JSON.stringify(fixtureData));
} else if (isStandaloneMode) { } else if (isStandaloneMode) {
// Standalone mode - fetch directly from API // Standalone mode - fetch directly from API
originalConsoleLog('[WebAdapter] Standalone mode - fetching fixture data directly from API'); debugLog('Standalone mode - fetching fixture data directly from API');
try { try {
const apiBaseUrl = window.location.origin; const apiBaseUrl = window.location.origin;
const response = await fetch(`${apiBaseUrl}/api/overlay/fixtures`, { const response = await fetch(`${apiBaseUrl}/api/overlay/fixtures`, {
...@@ -185,20 +191,20 @@ ...@@ -185,20 +191,20 @@
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
originalConsoleLog('[WebAdapter] API returned fixture data:', data ? data.length : 0, 'fixtures'); debugLog('API returned fixture data:', data ? data.length : 0, 'fixtures');
fixtureData = data || []; fixtureData = data || [];
resolve(JSON.stringify(fixtureData)); resolve(JSON.stringify(fixtureData));
} else { } else {
originalConsoleLog('[WebAdapter] API request failed:', response.status, response.statusText); debugLog('API request failed:', response.status, response.statusText);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} catch (error) { } catch (error) {
originalConsoleLog('[WebAdapter] API fetch error:', error.message); debugLog('API fetch error:', error.message);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} else { } else {
// Request data from parent // Request data from parent
originalConsoleLog('[WebAdapter] Requesting fixture data from parent'); debugLog('Requesting fixture data from parent');
requestFixtureData(); requestFixtureData();
// Wait for response with timeout // Wait for response with timeout
let attempts = 0; let attempts = 0;
...@@ -207,11 +213,11 @@ ...@@ -207,11 +213,11 @@
attempts++; attempts++;
if (fixtureData && fixtureData.length > 0) { if (fixtureData && fixtureData.length > 0) {
clearInterval(checkData); clearInterval(checkData);
originalConsoleLog('[WebAdapter] Fixture data received after', attempts * 100, 'ms'); debugLog('Fixture data received after', attempts * 100, 'ms');
resolve(JSON.stringify(fixtureData)); resolve(JSON.stringify(fixtureData));
} else if (attempts > maxAttempts) { } else if (attempts > maxAttempts) {
clearInterval(checkData); clearInterval(checkData);
originalConsoleLog('[WebAdapter] Fixture data timeout, returning empty array'); debugLog('Fixture data timeout, returning empty array');
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
}, 100); }, 100);
...@@ -252,14 +258,14 @@ ...@@ -252,14 +258,14 @@
// Get completed matches - returns Promise // Get completed matches - returns Promise
getCompletedMatches: function() { getCompletedMatches: function() {
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
originalConsoleLog('[WebAdapter] getCompletedMatches called, current data:', completedMatches ? completedMatches.length + ' matches' : 'null'); debugLog('getCompletedMatches called, current data:', completedMatches ? completedMatches.length + ' matches' : 'null');
if (completedMatches && completedMatches.length > 0) { if (completedMatches && completedMatches.length > 0) {
originalConsoleLog('[WebAdapter] Returning cached completed matches'); debugLog('Returning cached completed matches');
resolve(JSON.stringify(completedMatches)); resolve(JSON.stringify(completedMatches));
} else if (isStandaloneMode) { } else if (isStandaloneMode) {
// Standalone mode - fetch directly from API // Standalone mode - fetch directly from API
originalConsoleLog('[WebAdapter] Standalone mode - fetching completed matches directly from API'); debugLog('Standalone mode - fetching completed matches directly from API');
try { try {
const apiBaseUrl = window.location.origin; const apiBaseUrl = window.location.origin;
const response = await fetch(`${apiBaseUrl}/api/overlay/completed-matches`, { const response = await fetch(`${apiBaseUrl}/api/overlay/completed-matches`, {
...@@ -273,20 +279,20 @@ ...@@ -273,20 +279,20 @@
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
originalConsoleLog('[WebAdapter] API returned completed matches:', data ? data.length : 0, 'matches'); debugLog('API returned completed matches:', data ? data.length : 0, 'matches');
completedMatches = data || []; completedMatches = data || [];
resolve(JSON.stringify(completedMatches)); resolve(JSON.stringify(completedMatches));
} else { } else {
originalConsoleLog('[WebAdapter] API request failed:', response.status, response.statusText); debugLog('API request failed:', response.status, response.statusText);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} catch (error) { } catch (error) {
originalConsoleLog('[WebAdapter] API fetch error:', error.message); debugLog('API fetch error:', error.message);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} else { } else {
// Request data from parent // Request data from parent
originalConsoleLog('[WebAdapter] Requesting completed matches from parent'); debugLog('Requesting completed matches from parent');
requestCompletedMatches(); requestCompletedMatches();
let attempts = 0; let attempts = 0;
const maxAttempts = 50; const maxAttempts = 50;
...@@ -294,11 +300,11 @@ ...@@ -294,11 +300,11 @@
attempts++; attempts++;
if (completedMatches && completedMatches.length > 0) { if (completedMatches && completedMatches.length > 0) {
clearInterval(checkData); clearInterval(checkData);
originalConsoleLog('[WebAdapter] Completed matches received after', attempts * 100, 'ms'); debugLog('Completed matches received after', attempts * 100, 'ms');
resolve(JSON.stringify(completedMatches)); resolve(JSON.stringify(completedMatches));
} else if (attempts > maxAttempts) { } else if (attempts > maxAttempts) {
clearInterval(checkData); clearInterval(checkData);
originalConsoleLog('[WebAdapter] Completed matches timeout, returning empty array'); debugLog('Completed matches timeout, returning empty array');
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
}, 100); }, 100);
...@@ -311,7 +317,7 @@ ...@@ -311,7 +317,7 @@
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
if (isStandaloneMode) { if (isStandaloneMode) {
// Standalone mode - fetch directly from API // Standalone mode - fetch directly from API
originalConsoleLog('[WebAdapter] Standalone mode - fetching winning outcomes from API for match:', matchId); debugLog('Standalone mode - fetching winning outcomes from API for match:', matchId);
try { try {
const apiBaseUrl = window.location.origin; const apiBaseUrl = window.location.origin;
const response = await fetch(`${apiBaseUrl}/api/overlay/winning-outcomes/${matchId}`, { const response = await fetch(`${apiBaseUrl}/api/overlay/winning-outcomes/${matchId}`, {
...@@ -325,14 +331,14 @@ ...@@ -325,14 +331,14 @@
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
originalConsoleLog('[WebAdapter] API returned winning outcomes:', data ? data.length : 0, 'outcomes'); debugLog('API returned winning outcomes:', data ? data.length : 0, 'outcomes');
resolve(JSON.stringify(data || [])); resolve(JSON.stringify(data || []));
} else { } else {
originalConsoleLog('[WebAdapter] API request failed:', response.status, response.statusText); debugLog('API request failed:', response.status, response.statusText);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} catch (error) { } catch (error) {
originalConsoleLog('[WebAdapter] API fetch error:', error.message); debugLog('API fetch error:', error.message);
resolve(JSON.stringify([])); resolve(JSON.stringify([]));
} }
} else { } else {
...@@ -394,13 +400,12 @@ ...@@ -394,13 +400,12 @@
return; return;
} }
originalConsoleLog('[WebAdapter] Received message:', message.type); debugLog('Received message:', message.type);
switch (message.type) { switch (message.type) {
case 'fixtureData': case 'fixtureData':
fixtureData = message.fixtures || []; fixtureData = message.fixtures || [];
originalConsoleLog('[WebAdapter] Fixture data updated:', fixtureData.length, 'fixtures'); debugLog('Fixture data updated:', fixtureData.length, 'fixtures');
originalConsoleLog('[WebAdapter] Fixture data sample:', fixtureData.slice(0, 2));
break; break;
case 'timerState': case 'timerState':
...@@ -408,7 +413,7 @@ ...@@ -408,7 +413,7 @@
running: message.running, running: message.running,
remaining_seconds: message.remaining_seconds || 0 remaining_seconds: message.remaining_seconds || 0
} : message; } : message;
originalConsoleLog('[WebAdapter] Timer state updated:', timerState); debugLog('Timer state updated:', timerState);
// Emit signal for templates listening to dataUpdated // Emit signal for templates listening to dataUpdated
window.overlay.dataUpdated.emit({ timer_update: timerState }); window.overlay.dataUpdated.emit({ timer_update: timerState });
break; break;
...@@ -418,23 +423,23 @@ ...@@ -418,23 +423,23 @@
running: message.running, running: message.running,
remaining_seconds: message.remaining_seconds || 0 remaining_seconds: message.remaining_seconds || 0
} : message; } : message;
originalConsoleLog('[WebAdapter] Timer update received:', timerState); debugLog('Timer update received:', timerState);
window.overlay.dataUpdated.emit({ timer_update: timerState }); window.overlay.dataUpdated.emit({ timer_update: timerState });
break; break;
case 'licenseText': case 'licenseText':
licenseText = message.licenseText || ''; licenseText = message.licenseText || '';
originalConsoleLog('[WebAdapter] License text updated'); debugLog('License text updated');
break; break;
case 'completedMatches': case 'completedMatches':
completedMatches = message.matches || []; completedMatches = message.matches || [];
originalConsoleLog('[WebAdapter] Completed matches updated:', completedMatches.length, 'matches'); debugLog('Completed matches updated:', completedMatches.length, 'matches');
break; break;
case 'winningOutcomes': case 'winningOutcomes':
winningOutcomes = message.outcomes || []; winningOutcomes = message.outcomes || [];
originalConsoleLog('[WebAdapter] Winning outcomes updated:', winningOutcomes.length, 'outcomes'); debugLog('Winning outcomes updated:', winningOutcomes.length, 'outcomes');
break; break;
case 'initialData': case 'initialData':
...@@ -448,7 +453,7 @@ ...@@ -448,7 +453,7 @@
if (message.licenseText) { if (message.licenseText) {
licenseText = message.licenseText; licenseText = message.licenseText;
} }
originalConsoleLog('[WebAdapter] Initial data received'); debugLog('Initial data received');
// Emit signal for templates // Emit signal for templates
window.overlay.dataUpdated.emit(overlayData); window.overlay.dataUpdated.emit(overlayData);
break; break;
...@@ -456,27 +461,27 @@ ...@@ -456,27 +461,27 @@
case 'dataUpdated': case 'dataUpdated':
// Overlay data update // Overlay data update
overlayData = { ...overlayData, ...message }; overlayData = { ...overlayData, ...message };
originalConsoleLog('[WebAdapter] Overlay data updated:', Object.keys(message)); debugLog('Overlay data updated:', Object.keys(message));
// Emit signal for templates // Emit signal for templates
window.overlay.dataUpdated.emit(message); window.overlay.dataUpdated.emit(message);
break; break;
case 'matchUpdate': case 'matchUpdate':
originalConsoleLog('[WebAdapter] Match update received'); debugLog('Match update received');
window.overlay.dataUpdated.emit({ match_update: message }); window.overlay.dataUpdated.emit({ match_update: message });
break; break;
case 'resultUpdate': case 'resultUpdate':
originalConsoleLog('[WebAdapter] Result update received'); debugLog('Result update received');
window.overlay.dataUpdated.emit({ result_update: message }); window.overlay.dataUpdated.emit({ result_update: message });
break; break;
case 'videoStateChanged': case 'videoStateChanged':
originalConsoleLog('[WebAdapter] Video state changed:', message.state); debugLog('Video state changed:', message.state);
break; break;
case 'streamStateChanged': case 'streamStateChanged':
originalConsoleLog('[WebAdapter] Stream state changed:', message.state); debugLog('Stream state changed:', message.state);
break; break;
case 'positionChanged': case 'positionChanged':
...@@ -484,13 +489,13 @@ ...@@ -484,13 +489,13 @@
break; break;
default: default:
originalConsoleLog('[WebAdapter] Unknown message type:', message.type); debugLog('Unknown message type:', message.type);
} }
}); });
// Request initial data when DOM is ready // Request initial data when DOM is ready
function requestInitialData() { function requestInitialData() {
originalConsoleLog('[WebAdapter] Requesting initial data from parent'); debugLog('Requesting initial data from parent');
if (window.parent !== window) { if (window.parent !== window) {
window.parent.postMessage({ type: 'requestInitialData' }, '*'); window.parent.postMessage({ type: 'requestInitialData' }, '*');
...@@ -513,7 +518,7 @@ ...@@ -513,7 +518,7 @@
setTimeout(requestInitialData, 100); setTimeout(requestInitialData, 100);
} }
originalConsoleLog('[WebAdapter] Web overlay adapter initialized'); debugLog('Web overlay adapter initialized');
// Flush any buffered console logs // Flush any buffered console logs
if (typeof window.flushConsoleBuffer === 'function') { if (typeof window.flushConsoleBuffer === 'function') {
......
...@@ -89,11 +89,11 @@ class WebOverlayController { ...@@ -89,11 +89,11 @@ class WebOverlayController {
*/ */
async initialize() { async initialize() {
if (this.initialized) { if (this.initialized) {
console.log('[OverlayController] Already initialized, skipping'); this.log('Already initialized, skipping');
return; return;
} }
console.log('[OverlayController] Starting initialization...'); this.log('Starting initialization...');
// Set up video event listeners for synchronization // Set up video event listeners for synchronization
if (this.videoElement) { if (this.videoElement) {
...@@ -106,7 +106,7 @@ class WebOverlayController { ...@@ -106,7 +106,7 @@ class WebOverlayController {
// Set up message listener for iframe communication // Set up message listener for iframe communication
window.addEventListener('message', this.onIframeMessage.bind(this)); window.addEventListener('message', this.onIframeMessage.bind(this));
console.log('[OverlayController] Message listener set up for iframe communication'); this.log('Message listener set up for iframe communication');
// Set up resize observer for overlay scaling // Set up resize observer for overlay scaling
this.setupResizeObserver(); this.setupResizeObserver();
...@@ -118,16 +118,16 @@ class WebOverlayController { ...@@ -118,16 +118,16 @@ class WebOverlayController {
this.startRealTimeUpdates(); this.startRealTimeUpdates();
// Load default template // Load default template
console.log('[OverlayController] Loading default template...'); this.log('Loading default template...');
await this.loadTemplate('default'); await this.loadTemplate('default');
console.log('[OverlayController] Default template loaded'); this.log('Default template loaded');
this.initialized = true; this.initialized = true;
console.log('[OverlayController] Initialization complete, loading template config...'); this.log('Initialization complete, loading template config...');
// Load template configuration and start rotation // Load template configuration and start rotation
await this.loadTemplateConfig(); await this.loadTemplateConfig();
console.log('[OverlayController] Template config loaded'); this.log('Template config loaded');
// Emit initialized event // Emit initialized event
this.emit('initialized'); this.emit('initialized');
...@@ -137,11 +137,11 @@ class WebOverlayController { ...@@ -137,11 +137,11 @@ class WebOverlayController {
* Load template configuration from API * Load template configuration from API
*/ */
async loadTemplateConfig() { async loadTemplateConfig() {
console.log('[OverlayController] loadTemplateConfig() called'); this.log('loadTemplateConfig() called');
try { try {
console.log('[OverlayController] Loading template config...'); this.log('Loading template config...');
const config = await this.apiRequest('/template-config'); const config = await this.apiRequest('/template-config');
console.log('[OverlayController] Template config response:', config); this.log('Template config response:', config);
if (config && config.templates && config.templates.length > 0) { if (config && config.templates && config.templates.length > 0) {
this.templateSequence = config.templates; this.templateSequence = config.templates;
...@@ -156,18 +156,16 @@ class WebOverlayController { ...@@ -156,18 +156,16 @@ class WebOverlayController {
} }
} }
console.log(`[OverlayController] Loaded template config: ${this.templateSequence.length} templates, rotating every ${this.rotatingTime}s`); this.log(`Loaded template config: ${this.templateSequence.length} templates, rotating every ${this.rotatingTime}s`);
console.log('[OverlayController] Template sequence:', this.templateSequence.map(t => t.name).join(', ')); this.log('Template sequence:', this.templateSequence.map(t => t.name).join(', '));
// Start template rotation // Start template rotation
this.startTemplateRotation(); this.startTemplateRotation();
} else { } else {
console.log('[OverlayController] No template sequence configured, using default template'); this.log('No template sequence configured, using default template');
console.log('[OverlayController] Config:', config);
} }
} catch (error) { } catch (error) {
console.error('[OverlayController] Failed to load template config:', error); this.log('Failed to load template config:', error.message);
console.error('[OverlayController] Error stack:', error.stack);
} }
} }
...@@ -426,7 +424,7 @@ class WebOverlayController { ...@@ -426,7 +424,7 @@ class WebOverlayController {
clearInterval(this.pollingInterval); clearInterval(this.pollingInterval);
} }
console.log(`[OverlayController] Starting polling with frequency: ${this.pollingFrequency}ms`); this.log(`Starting polling with frequency: ${this.pollingFrequency}ms`);
this.pollingInterval = setInterval(async () => { this.pollingInterval = setInterval(async () => {
try { try {
...@@ -455,16 +453,16 @@ class WebOverlayController { ...@@ -455,16 +453,16 @@ class WebOverlayController {
*/ */
connectWebSocket() { connectWebSocket() {
if (!this.wsUrl) { if (!this.wsUrl) {
console.log('[OverlayController] No WebSocket URL configured, using polling only'); this.log('No WebSocket URL configured, using polling only');
return; return;
} }
try { try {
console.log(`[OverlayController] Connecting to WebSocket: ${this.wsUrl}`); this.log(`Connecting to WebSocket: ${this.wsUrl}`);
this.websocket = new WebSocket(this.wsUrl); this.websocket = new WebSocket(this.wsUrl);
this.websocket.onopen = () => { this.websocket.onopen = () => {
console.log('[OverlayController] WebSocket connected'); this.log('WebSocket connected');
this.wsReconnectAttempts = 0; this.wsReconnectAttempts = 0;
// Send authentication // Send authentication
...@@ -486,7 +484,7 @@ class WebOverlayController { ...@@ -486,7 +484,7 @@ class WebOverlayController {
}; };
this.websocket.onclose = (event) => { this.websocket.onclose = (event) => {
console.log('[OverlayController] WebSocket closed:', event.code, event.reason); this.log('WebSocket closed:', event.code, event.reason);
this.scheduleWebSocketReconnect(); this.scheduleWebSocketReconnect();
}; };
...@@ -505,14 +503,14 @@ class WebOverlayController { ...@@ -505,14 +503,14 @@ class WebOverlayController {
*/ */
scheduleWebSocketReconnect() { scheduleWebSocketReconnect() {
if (this.wsReconnectAttempts >= this.wsMaxReconnectAttempts) { if (this.wsReconnectAttempts >= this.wsMaxReconnectAttempts) {
console.log('[OverlayController] Max WebSocket reconnect attempts reached, using polling only'); this.log('Max WebSocket reconnect attempts reached, using polling only');
return; return;
} }
this.wsReconnectAttempts++; this.wsReconnectAttempts++;
const delay = this.wsReconnectDelay * Math.pow(2, this.wsReconnectAttempts - 1); const delay = this.wsReconnectDelay * Math.pow(2, this.wsReconnectAttempts - 1);
console.log(`[OverlayController] Scheduling WebSocket reconnect in ${delay}ms (attempt ${this.wsReconnectAttempts})`); this.log(`Scheduling WebSocket reconnect in ${delay}ms (attempt ${this.wsReconnectAttempts})`);
setTimeout(() => { setTimeout(() => {
this.connectWebSocket(); this.connectWebSocket();
...@@ -524,7 +522,7 @@ class WebOverlayController { ...@@ -524,7 +522,7 @@ class WebOverlayController {
* @param {Object} data - WebSocket message data * @param {Object} data - WebSocket message data
*/ */
handleWebSocketMessage(data) { handleWebSocketMessage(data) {
console.log('[OverlayController] WebSocket message received:', data.type); this.log('WebSocket message received:', data.type);
switch (data.type) { switch (data.type) {
case 'overlayUpdate': case 'overlayUpdate':
...@@ -551,7 +549,7 @@ class WebOverlayController { ...@@ -551,7 +549,7 @@ class WebOverlayController {
break; break;
default: default:
console.log('[OverlayController] Unknown WebSocket message type:', data.type); this.log('Unknown WebSocket message type:', data.type);
} }
} }
...@@ -572,12 +570,12 @@ class WebOverlayController { ...@@ -572,12 +570,12 @@ class WebOverlayController {
// Handle match video state changes // Handle match video state changes
if (isNowPlayingMatchVideo && !wasPlayingMatchVideo) { if (isNowPlayingMatchVideo && !wasPlayingMatchVideo) {
// Match video just started - stop rotation and load match_video template // Match video just started - stop rotation and load match_video template
console.log('[OverlayController] Match video started - stopping template rotation'); this.log('Match video started - stopping template rotation');
this.stopTemplateRotation(); this.stopTemplateRotation();
this.loadTemplate('match_video'); this.loadTemplate('match_video');
} else if (!isNowPlayingMatchVideo && wasPlayingMatchVideo) { } else if (!isNowPlayingMatchVideo && wasPlayingMatchVideo) {
// Match video just ended - restart rotation with results template first // Match video just ended - restart rotation with results template first
console.log('[OverlayController] Match video ended - restarting template rotation with results'); this.log('Match video ended - restarting template rotation with results');
this.loadTemplate('results'); this.loadTemplate('results');
// Restart rotation after a delay // Restart rotation after a delay
setTimeout(() => { setTimeout(() => {
...@@ -612,14 +610,13 @@ class WebOverlayController { ...@@ -612,14 +610,13 @@ class WebOverlayController {
*/ */
async fetchFixtureData() { async fetchFixtureData() {
try { try {
console.log('[OverlayController] Fetching fixture data from API...'); this.log('Fetching fixture data from API...');
const response = await this.apiRequest('/fixtures'); const response = await this.apiRequest('/fixtures');
console.log('[OverlayController] Fixture data API response:', response); this.log('Fixture data API response:', response);
this.fixtureData = response; this.fixtureData = response;
return response; return response;
} catch (error) { } catch (error) {
console.error('[OverlayController] Failed to fetch fixture data:', error); this.log('Failed to fetch fixture data:', error.message);
console.error('[OverlayController] Error details:', error.message, error.stack);
return []; return [];
} }
} }
...@@ -737,12 +734,10 @@ class WebOverlayController { ...@@ -737,12 +734,10 @@ class WebOverlayController {
const token = this.getAuthToken(); const token = this.getAuthToken();
if (token) { if (token) {
headers['Authorization'] = `Bearer ${token}`; headers['Authorization'] = `Bearer ${token}`;
console.log('[OverlayController] API request to:', endpoint, 'with auth token'); this.log('API request to:', endpoint, 'with auth token');
} else {
console.warn('[OverlayController] API request to:', endpoint, 'WITHOUT auth token - may fail if endpoint requires authentication');
} }
console.log('[OverlayController] Making API request to:', url); this.log('Making API request to:', url);
try { try {
const response = await fetch(url, { const response = await fetch(url, {
...@@ -750,19 +745,19 @@ class WebOverlayController { ...@@ -750,19 +745,19 @@ class WebOverlayController {
headers headers
}); });
console.log('[OverlayController] API response status:', response.status, response.statusText); this.log('API response status:', response.status, response.statusText);
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
console.error('[OverlayController] API error response:', errorText); this.log('API error response:', errorText);
throw new Error(`API request failed: ${response.status} ${response.statusText}`); throw new Error(`API request failed: ${response.status} ${response.statusText}`);
} }
const data = await response.json(); const data = await response.json();
console.log('[OverlayController] API response data:', data); this.log('API response data:', data);
return data; return data;
} catch (error) { } catch (error) {
console.error('[OverlayController] API request error:', error); this.log('API request error:', error.message);
throw error; throw error;
} }
} }
...@@ -775,10 +770,10 @@ class WebOverlayController { ...@@ -775,10 +770,10 @@ class WebOverlayController {
sendMessageToOverlay(type, data) { sendMessageToOverlay(type, data) {
if (this.overlayIframe && this.overlayIframe.contentWindow) { if (this.overlayIframe && this.overlayIframe.contentWindow) {
const message = { type, ...data }; const message = { type, ...data };
console.log('[OverlayController] Sending message to overlay:', type, data); this.log('Sending message to overlay:', type, data);
this.overlayIframe.contentWindow.postMessage(message, '*'); this.overlayIframe.contentWindow.postMessage(message, '*');
} else { } else {
console.warn('[OverlayController] Cannot send message - iframe not ready'); this.log('Cannot send message - iframe not ready');
} }
} }
...@@ -794,16 +789,13 @@ class WebOverlayController { ...@@ -794,16 +789,13 @@ class WebOverlayController {
return; return;
} }
console.log('[OverlayController] Received iframe message:', message.type, 'from origin:', event.origin); this.log('Received iframe message:', message.type, 'from origin:', event.origin);
console.log('[OverlayController] Message source is our iframe:', event.source === this.overlayIframe?.contentWindow);
console.log('[OverlayController] Overlay iframe exists:', !!this.overlayIframe);
console.log('[OverlayController] Overlay iframe contentWindow exists:', !!this.overlayIframe?.contentWindow);
// Handle different message types from iframe // Handle different message types from iframe
switch (message.type) { switch (message.type) {
case 'requestInitialData': case 'requestInitialData':
// Send current overlay data to iframe // Send current overlay data to iframe
console.log('[OverlayController] Processing requestInitialData'); this.log('Processing requestInitialData');
this.sendMessageToOverlay('initialData', { this.sendMessageToOverlay('initialData', {
overlayData: this.overlayData, overlayData: this.overlayData,
timerState: this.timerState, timerState: this.timerState,
...@@ -812,13 +804,13 @@ class WebOverlayController { ...@@ -812,13 +804,13 @@ class WebOverlayController {
break; break;
case 'requestFixtureData': case 'requestFixtureData':
console.log('[OverlayController] Processing requestFixtureData'); this.log('Processing requestFixtureData');
try { try {
const fixtureData = await this.fetchFixtureData(); const fixtureData = await this.fetchFixtureData();
console.log('[OverlayController] Fetched fixture data:', fixtureData ? fixtureData.length + ' fixtures' : 'null'); this.log('Fetched fixture data:', fixtureData ? fixtureData.length + ' fixtures' : 'null');
this.sendMessageToOverlay('fixtureData', { fixtures: fixtureData }); this.sendMessageToOverlay('fixtureData', { fixtures: fixtureData });
} catch (error) { } catch (error) {
console.error('[OverlayController] Error fetching fixture data:', error); this.log('Error fetching fixture data:', error.message);
this.sendMessageToOverlay('fixtureData', { fixtures: [] }); this.sendMessageToOverlay('fixtureData', { fixtures: [] });
} }
break; break;
...@@ -844,12 +836,12 @@ class WebOverlayController { ...@@ -844,12 +836,12 @@ class WebOverlayController {
break; break;
case 'log': case 'log':
// Forward log messages from iframe to console // Forward log messages from iframe to console (only in debug mode)
console.log('[Overlay]', message.message); this.log('[Overlay]', message.message);
break; break;
default: default:
console.log('[OverlayController] Unknown iframe message type:', message.type); this.log('Unknown iframe message type:', message.type);
} }
} }
...@@ -884,7 +876,7 @@ class WebOverlayController { ...@@ -884,7 +876,7 @@ class WebOverlayController {
* Handle video play event * Handle video play event
*/ */
onPlay() { onPlay() {
console.log('[OverlayController] Video playing'); this.log('Video playing');
this.sendMessageToOverlay('videoStateChanged', { this.sendMessageToOverlay('videoStateChanged', {
state: 'playing', state: 'playing',
position: this.videoElement.currentTime, position: this.videoElement.currentTime,
...@@ -896,7 +888,7 @@ class WebOverlayController { ...@@ -896,7 +888,7 @@ class WebOverlayController {
* Handle video pause event * Handle video pause event
*/ */
onPause() { onPause() {
console.log('[OverlayController] Video paused'); this.log('Video paused');
this.sendMessageToOverlay('videoStateChanged', { this.sendMessageToOverlay('videoStateChanged', {
state: 'paused', state: 'paused',
position: this.videoElement.currentTime, position: this.videoElement.currentTime,
...@@ -908,7 +900,7 @@ class WebOverlayController { ...@@ -908,7 +900,7 @@ class WebOverlayController {
* Handle video ended event * Handle video ended event
*/ */
onEnded() { onEnded() {
console.log('[OverlayController] Video ended'); this.log('Video ended');
this.sendMessageToOverlay('videoStateChanged', { this.sendMessageToOverlay('videoStateChanged', {
state: 'ended', state: 'ended',
position: this.videoElement.currentTime, position: this.videoElement.currentTime,
...@@ -920,7 +912,7 @@ class WebOverlayController { ...@@ -920,7 +912,7 @@ class WebOverlayController {
* Handle video loadedmetadata event * Handle video loadedmetadata event
*/ */
onLoadedMetadata() { onLoadedMetadata() {
console.log('[OverlayController] Video metadata loaded'); this.log('Video metadata loaded');
this.sendMessageToOverlay('videoLoaded', { this.sendMessageToOverlay('videoLoaded', {
duration: this.videoElement.duration, duration: this.videoElement.duration,
videoWidth: this.videoElement.videoWidth, videoWidth: this.videoElement.videoWidth,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment