Files
game-timer/test.html
2025-03-30 23:46:13 +02:00

499 lines
21 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>Push Notification Debug</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
button {
padding: 10px;
margin: 5px;
cursor: pointer;
}
pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}
.section {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
}
select {
padding: 8px;
margin-right: 10px;
}
input {
padding: 8px;
margin-right: 10px;
}
</style>
</head>
<body>
<h1>Push Notification Debug</h1>
<div class="section">
<h2>LocalStorage Management</h2>
<button id="checkCreds">Check Stored Credentials</button>
<button id="clearCreds">Clear Stored Credentials</button>
<pre id="credsOutput"></pre>
</div>
<div class="section">
<h2>Push Subscription Status</h2>
<button id="checkSub">Check Current Subscription</button>
<button id="unsubscribe">Unsubscribe from Push</button>
<pre id="subOutput"></pre>
</div>
<div class="section">
<h2>Manually Trigger Subscription</h2>
<p>Use these buttons to manually trigger the subscription process:</p>
<button id="setupPush">Setup Push Notifications</button>
<button id="forceCredentials">Force New Credentials Prompt</button>
<pre id="setupOutput"></pre>
</div>
<div class="section">
<h2>Test Server Communication</h2>
<p>Send existing subscription to server (tests authentication):</p>
<input type="text" id="buttonId" placeholder="Button ID (leave empty for default)" style="padding: 8px; width: 250px; margin-bottom: 10px;">
<button id="sendToServer">Send Current Subscription to Server</button>
<pre id="serverOutput"></pre>
</div>
<div class="section">
<h2>Simulate Button Click (Webhook)</h2>
<p>This simulates a button click by sending a request to the webhook endpoint:</p>
<div style="margin-bottom: 10px;">
<select id="actionType">
<option value="SingleClick">SingleClick</option>
<option value="DoubleClick">DoubleClick</option>
<option value="Hold">Hold</option>
</select>
<input type="text" id="webhookButtonName" value="Game-button" placeholder="Button Name">
<input type="number" id="batteryLevel" value="100" min="0" max="100" style="width: 60px;">
<label for="batteryLevel">% Battery</label>
</div>
<button id="simulateClick">Simulate Button Click</button>
<pre id="webhookOutput"></pre>
</div>
<div class="section">
<h2>Service Worker Message Monitor</h2>
<p>Displays messages received from the service worker (client.postMessage):</p>
<div style="margin-bottom: 10px;">
<button id="startMonitoring">Start Monitoring</button>
<button id="clearMessages">Clear Messages</button>
</div>
<pre id="swMessagesOutput" style="max-height: 300px; overflow-y: auto;"></pre>
</div>
<script type="module">
import { setupPushNotifications, forceCredentialsPrompt } from './src/js/services/serviceWorkerManager.js';
import { FLIC_BUTTON_ID } from './src/js/config.js';
// We need direct access to the sendSubscriptionToServer function
// We'll recreate a simplified version here since it's not exported
async function sendSubscriptionToServer(subscription, buttonId) {
const serverOutput = document.getElementById('serverOutput');
serverOutput.textContent = `Sending subscription for button "${buttonId}" to server...`;
try {
// Get stored credentials
const storedAuth = localStorage.getItem('basicAuthCredentials');
let credentials = null;
if (storedAuth) {
try {
credentials = JSON.parse(storedAuth);
if (!credentials.username || !credentials.password) {
throw new Error('Invalid stored credentials');
}
serverOutput.textContent += '\nUsing stored credentials.';
} catch (error) {
serverOutput.textContent += '\nFailed to parse stored credentials.';
}
}
// If no credentials, prompt user
if (!credentials) {
serverOutput.textContent += '\nNo valid credentials found, prompting user...';
const confirmAuth = confirm('Authentication required. Provide credentials now?');
if (!confirmAuth) {
serverOutput.textContent += '\nUser declined to provide credentials.';
return;
}
const username = prompt('Please enter your username:');
if (!username) {
serverOutput.textContent += '\nUsername input cancelled.';
return;
}
const password = prompt('Please enter your password:');
if (!password) {
serverOutput.textContent += '\nPassword input cancelled.';
return;
}
credentials = { username, password };
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
serverOutput.textContent += '\nNew credentials saved.';
}
// Create auth header
const createBasicAuthHeader = (creds) => {
return 'Basic ' + btoa(`${creds.username}:${creds.password}`);
};
// Prepare request
const headers = { 'Content-Type': 'application/json' };
const authHeader = createBasicAuthHeader(credentials);
if (authHeader) headers['Authorization'] = authHeader;
// Get backend URL from config or use a default
let backendUrl;
try {
const configModule = await import('./src/js/config.js');
backendUrl = configModule.BACKEND_URL;
} catch (error) {
backendUrl = prompt('Enter backend URL:', 'https://your-backend-url.com');
if (!backendUrl) return;
}
serverOutput.textContent += `\nSending to: ${backendUrl}/subscribe`;
// Send request
const response = await fetch(`${backendUrl}/subscribe`, {
method: 'POST',
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
headers: headers,
credentials: 'include'
});
if (response.ok) {
const result = await response.json();
serverOutput.textContent += `\nSuccess! Server response: ${result.message || JSON.stringify(result)}`;
} else {
let errorMsg = `Server error: ${response.status}`;
if (response.status === 401 || response.status === 403) {
localStorage.removeItem('basicAuthCredentials');
errorMsg = 'Authentication failed. Credentials cleared.';
} else {
try {
const errorData = await response.json();
errorMsg = errorData.message || errorMsg;
} catch (e) { /* use default */ }
}
serverOutput.textContent += `\nError: ${errorMsg}`;
}
} catch (error) {
serverOutput.textContent += `\nNetwork error: ${error.message}`;
}
}
// Helper function to get stored credentials
async function getStoredCredentials() {
const storedAuth = localStorage.getItem('basicAuthCredentials');
if (!storedAuth) return null;
try {
const credentials = JSON.parse(storedAuth);
if (!credentials.username || !credentials.password) return null;
return credentials;
} catch (error) {
console.error('Failed to parse stored credentials:', error);
return null;
}
}
// Function to simulate a button click using the webhook API
async function simulateButtonClick(action, buttonName, batteryLevel) {
const output = document.getElementById('webhookOutput');
output.textContent = `Simulating ${action} for button ${buttonName}...`;
try {
// Get credentials
const credentials = await getStoredCredentials();
if (!credentials) {
output.textContent += '\nNo credentials found. Please set up credentials first.';
return;
}
// Create basic auth header
const authHeader = 'Basic ' + btoa(`${credentials.username}:${credentials.password}`);
// Create timestamp (current time)
const timestamp = new Date().toISOString();
// Prepare request to backend webhook
let backendUrl;
try {
const configModule = await import('./src/js/config.js');
backendUrl = configModule.BACKEND_URL;
} catch (error) {
output.textContent += '\nFailed to load backend URL.';
return;
}
const webhookUrl = `${backendUrl}/webhook/${action}`;
output.textContent += `\nSending request to: ${webhookUrl}`;
// Headers similar to the curl command
const headers = {
'Authorization': authHeader,
'Button-Name': buttonName,
'Timestamp': timestamp,
'Button-Battery-Level': batteryLevel.toString()
};
// Send GET request to webhook
const response = await fetch(webhookUrl, {
method: 'GET',
headers: headers,
credentials: 'include'
});
if (response.ok) {
let result;
try {
result = await response.json();
output.textContent += `\nSuccess! Response: ${JSON.stringify(result, null, 2)}`;
} catch (e) {
// Text response
result = await response.text();
output.textContent += `\nSuccess! Response: ${result}`;
}
} else {
let errorText;
try {
errorText = await response.text();
} catch (e) {
errorText = `Status ${response.status}`;
}
output.textContent += `\nError: ${errorText}`;
}
} catch (error) {
output.textContent += `\nError: ${error.message}`;
}
}
// Replace with service worker message monitoring
let messageListener = null;
let isMonitoring = false;
// Function to start monitoring for service worker messages
function startMessageMonitoring() {
const output = document.getElementById('swMessagesOutput');
if (isMonitoring) {
output.textContent = 'Already monitoring for messages...';
return;
}
if (!('serviceWorker' in navigator)) {
output.textContent = 'Service Worker not supported in this browser.';
return;
}
output.textContent = 'Started monitoring for messages from service worker...\n';
output.textContent += 'Waiting for push notifications or button clicks...\n';
// Create and register the message listener
messageListener = function(event) {
const now = new Date().toISOString();
const formattedMessage = `[${now}] Message received: \n${JSON.stringify(event.data, null, 2)}\n\n`;
output.textContent += formattedMessage;
// Auto-scroll to the bottom
output.scrollTop = output.scrollHeight;
};
// Add the listener
navigator.serviceWorker.addEventListener('message', messageListener);
isMonitoring = true;
}
// Function to stop monitoring and clear the listener
function stopMessageMonitoring() {
if (messageListener) {
navigator.serviceWorker.removeEventListener('message', messageListener);
messageListener = null;
isMonitoring = false;
}
}
// Function to clear the messages output
function clearMessages() {
const output = document.getElementById('swMessagesOutput');
output.textContent = isMonitoring ?
'Monitoring for messages from service worker...\nWaiting for push notifications or button clicks...\n' :
'Click "Start Monitoring" to begin capturing messages.';
}
// Check credentials
document.getElementById('checkCreds').addEventListener('click', function() {
const creds = localStorage.getItem('basicAuthCredentials');
document.getElementById('credsOutput').textContent =
creds ? `Found: ${creds}` : 'No credentials stored.';
});
// Clear credentials
document.getElementById('clearCreds').addEventListener('click', function() {
localStorage.removeItem('basicAuthCredentials');
document.getElementById('credsOutput').textContent = 'Credentials cleared!';
});
// Check subscription
document.getElementById('checkSub').addEventListener('click', async function() {
const output = document.getElementById('subOutput');
try {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
output.textContent = 'Push notifications not supported in this browser.';
return;
}
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
output.textContent = 'Active subscription found:\n' +
JSON.stringify(subscription, null, 2);
} else {
output.textContent = 'No active push subscription found.';
}
} catch (error) {
output.textContent = 'Error: ' + error.message;
}
});
// Unsubscribe
document.getElementById('unsubscribe').addEventListener('click', async function() {
const output = document.getElementById('subOutput');
try {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
output.textContent = 'Push notifications not supported in this browser.';
return;
}
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
await subscription.unsubscribe();
output.textContent = 'Successfully unsubscribed!';
} else {
output.textContent = 'No active subscription to unsubscribe from.';
}
} catch (error) {
output.textContent = 'Error unsubscribing: ' + error.message;
}
});
// Setup push notifications
document.getElementById('setupPush').addEventListener('click', function() {
const output = document.getElementById('setupOutput');
output.textContent = 'Triggering push notification setup...';
try {
setupPushNotifications();
output.textContent += '\nSetup process initiated. Check console for details.';
} catch (error) {
output.textContent += `\nError: ${error.message}`;
}
});
// Force credentials prompt
document.getElementById('forceCredentials').addEventListener('click', function() {
const output = document.getElementById('setupOutput');
output.textContent = 'Forcing new credentials prompt...';
try {
forceCredentialsPrompt();
output.textContent += '\nCredentials prompt initiated. Check console for details.';
} catch (error) {
output.textContent += `\nError: ${error.message}`;
}
});
// Send subscription to server
document.getElementById('sendToServer').addEventListener('click', async function() {
const output = document.getElementById('serverOutput');
try {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
output.textContent = 'Push notifications not supported in this browser.';
return;
}
// Get current subscription
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (!subscription) {
output.textContent = 'No active subscription found. Please subscribe first.';
return;
}
// Get button ID (use input or default)
let buttonId = document.getElementById('buttonId').value.trim();
if (!buttonId) {
try {
// Try to get from config
buttonId = FLIC_BUTTON_ID;
} catch (e) {
buttonId = 'default-button';
}
}
// Send to server
await sendSubscriptionToServer(subscription, buttonId);
} catch (error) {
output.textContent = `Error: ${error.message}`;
}
});
// Simulate button click
document.getElementById('simulateClick').addEventListener('click', async function() {
const action = document.getElementById('actionType').value;
const buttonName = document.getElementById('webhookButtonName').value || 'Game-button';
const batteryLevel = parseInt(document.getElementById('batteryLevel').value || '100', 10);
await simulateButtonClick(action, buttonName, batteryLevel);
});
// Start monitoring for service worker messages
document.getElementById('startMonitoring').addEventListener('click', function() {
startMessageMonitoring();
});
// Clear messages
document.getElementById('clearMessages').addEventListener('click', function() {
clearMessages();
});
// Start monitoring automatically when page loads
window.addEventListener('load', function() {
// Clear any previous handlers if the page is reloaded
if (messageListener) {
stopMessageMonitoring();
}
// Start monitoring for messages
setTimeout(startMessageMonitoring, 1000); // Short delay to ensure service worker is ready
});
// Cleanup when page is unloaded
window.addEventListener('unload', function() {
stopMessageMonitoring();
});
</script>
</body>
</html>