added message monitoring

This commit is contained in:
cpu
2025-03-29 05:11:14 +01:00
parent ef96498cab
commit 72e1744a22

208
test.html
View File

@@ -26,6 +26,14 @@
border: 1px solid #ddd;
border-radius: 5px;
}
select {
padding: 8px;
margin-right: 10px;
}
input {
padding: 8px;
margin-right: 10px;
}
</style>
</head>
<body>
@@ -61,6 +69,33 @@
<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';
@@ -166,6 +201,144 @@
}
}
// 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 || 'https://webpush.virtonline.eu';
} catch (error) {
backendUrl = 'https://webpush.virtonline.eu';
}
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');
@@ -285,6 +458,41 @@
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>