test page

This commit is contained in:
cpu
2025-03-29 04:37:06 +01:00
parent 832f19235f
commit ef96498cab
3 changed files with 354 additions and 55 deletions

View File

@@ -116,8 +116,13 @@ async function subscribeToPush() {
console.log('Notification permission granted.');
// After permission is granted, check for stored credentials or prompt user
// IMPORTANT: Force checking for credentials - even with an existing subscription
// Always allow the user to set/update credentials
let credentials = getBasicAuthCredentials();
const hasExistingCreds = !!credentials;
console.log('Has existing credentials:', hasExistingCreds);
// Ask for credentials every time unless one exists
if (!credentials) {
const confirmAuth = confirm('Do you want to set up credentials for push notifications now?');
if (!confirmAuth) {
@@ -136,6 +141,8 @@ async function subscribeToPush() {
const registration = await navigator.serviceWorker.ready;
let existingSubscription = await registration.pushManager.getSubscription();
let needsResubscribe = !existingSubscription;
console.log('Existing subscription found:', !!existingSubscription);
if (existingSubscription) {
const existingKey = existingSubscription.options?.applicationServerKey;
@@ -154,12 +161,18 @@ async function subscribeToPush() {
if (needsResubscribe) {
console.log('Subscribing for push notifications...');
const applicationServerKey = urlBase64ToUint8Array(getPublicVapidKey());
finalSubscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
});
console.log('New push subscription obtained:', finalSubscription);
pushSubscription = finalSubscription; // Store it
try {
finalSubscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
});
console.log('New push subscription obtained:', finalSubscription);
pushSubscription = finalSubscription; // Store it
} catch (subscribeError) {
console.error('Error subscribing to push:', subscribeError);
alert(`Failed to subscribe: ${subscribeError.message}`);
return;
}
}
if (!finalSubscription) {
@@ -262,22 +275,43 @@ export function handleFlicAction(action, buttonId, timestamp, batteryLevel) {
export function initPushFlic(handlers) {
actionHandlers = handlers; // Store the handlers passed from app.js
// Example: handlers = { SingleClick: handleNextPlayer, Hold: handleTogglePause }
// Attempt to subscribe immediately if permission might already be granted
// Or trigger subscription on a user action (e.g., a "Link Flic Button" button)
// For simplicity, let's try subscribing if SW is ready and permission allows
// Don't auto-subscribe - wait for user action
// This prevents issues with permission/notification prompts appearing unexpectedly
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('[PushFlic] Permission granted, attempting subscription.');
subscribeToPush();
} else {
console.log('[PushFlic] Notification permission not granted.');
// Optionally provide a button for the user to trigger subscription later
}
});
// Check if permission is already granted, but don't automatically subscribe
if (Notification.permission === 'granted') {
console.log('[PushFlic] Permission already granted, but waiting for user action to subscribe.');
// Check if we have valid credentials
const hasCredentials = !!getBasicAuthCredentials();
console.log('[PushFlic] Has stored credentials:', hasCredentials);
} else {
console.log('[PushFlic] Notification permission not granted yet.');
}
});
}
}
// New function to manually trigger the subscription process
export function setupPushNotifications() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
console.log('[PushFlic] Manually triggering push subscription process...');
subscribeToPush();
});
} else {
console.error('[PushFlic] Service workers not supported, cannot subscribe');
alert('Your browser does not support push notifications.');
}
}
// Function to force re-authentication even if credentials exist
export function forceCredentialsPrompt() {
// Remove existing credentials to force new ones
localStorage.removeItem('basicAuthCredentials');
console.log('[PushFlic] Removed stored credentials, will prompt on next subscription attempt');
// Trigger the subscription process again
setupPushNotifications();
}

View File

@@ -16,15 +16,26 @@ export function initFlic() {
pushFlic.initPushFlic(flicActionHandlers);
}
export function handleServiceWorkerMessage(event) {
// Export functions for manually triggering push notifications setup
export function setupPushNotifications() {
pushFlic.setupPushNotifications();
}
export function forceCredentialsPrompt() {
pushFlic.forceCredentialsPrompt();
}
// --- Handle Messages from Service Worker ---
export function flicMessageHandler(event) {
// This function is passed to setupServiceWorker and called when a message arrives from the service worker
console.log('[App] Message received from Service Worker:', event.data);
if (event.data?.type === 'flic-action') {
// Check if this is a Flic action message
if (event.data && event.data.type === 'flic-action') {
const { action, button, timestamp, batteryLevel } = event.data;
if (flicActionHandlers[action]) {
flicActionHandlers[action]();
} else {
pushFlic.handleFlicAction(action, button, timestamp, batteryLevel);
}
// Pass to push-flic service to handle
pushFlic.handleFlicAction(action, button, timestamp, batteryLevel);
}
}
@@ -39,7 +50,7 @@ export function setupServiceWorker(messageHandler) {
// Listen for messages FROM the Service Worker (e.g., Flic actions)
navigator.serviceWorker.addEventListener('message', messageHandler);
// Initialize Flic integration (which will try to subscribe)
// Initialize Flic integration (which will just register handlers now, not auto-subscribe)
initFlic();
})
.catch(error => {