Compare commits
2 Commits
0414bdb217
...
08632ee711
| Author | SHA1 | Date | |
|---|---|---|---|
| 08632ee711 | |||
| 451a61d357 |
4
app.js
4
app.js
@@ -356,8 +356,8 @@ function setupServiceWorker() {
|
||||
function handleServiceWorkerMessage(event) {
|
||||
console.log('[App] Message received from Service Worker:', event.data);
|
||||
if (event.data?.type === 'flic-action') {
|
||||
const { action, button, timestamp } = event.data;
|
||||
pushFlic.handleFlicAction(action, button, timestamp);
|
||||
const { action, button, timestamp, batteryLevel } = event.data;
|
||||
pushFlic.handleFlicAction(action, button, timestamp, batteryLevel);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ export const PUBLIC_VAPID_KEY = 'BKfRJXjSQmAJ452gLwlK_8scGrW6qMU1mBRp39ONtcQHkSs
|
||||
export const BACKEND_URL = 'https://webpush.virtonline.eu';
|
||||
export const FLIC_BUTTON_ID = 'game-button'; // Example ID, might need configuration
|
||||
export const LOCAL_STORAGE_KEY = 'gameTimerData';
|
||||
export const FLIC_BATTERY_THRESHOLD = 50; // Battery percentage threshold for low battery warning
|
||||
|
||||
// Default player settings
|
||||
export const DEFAULT_PLAYER_TIME_SECONDS = 300; // 5 minutes
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
# Enable Traefik for this container
|
||||
traefik.enable=true
|
||||
|
||||
# Docker Network
|
||||
traefik.docker.network=traefik
|
||||
|
||||
# Route requests based on Host
|
||||
traefik.http.routers.game-timer.rule=Host(`game-timer.virtonline.eu`)
|
||||
traefik.http.routers.game-timer.service=game-timer
|
||||
# Specify the entrypoint ('websecure' for HTTPS)
|
||||
traefik.http.routers.game-timer.entrypoints=web-secure
|
||||
traefik.http.routers.game-timer.tls=true
|
||||
traefik.http.routers.game-timer.tls.certResolver=default
|
||||
traefik.http.routers.game-timer.entrypoints=web-secure
|
||||
# Link the router to the service defined below
|
||||
traefik.http.routers.game-timer.service=game-timer
|
||||
|
||||
# Point the service to the container's port
|
||||
traefik.http.services.game-timer.loadbalancer.server.port=80
|
||||
|
||||
traefik.http.routers.game-timer.middlewares=game-timer-auth
|
||||
# Declaring the user list
|
||||
#
|
||||
# Note: when used in docker-compose.yml all dollar signs in the hash need to be doubled for escaping.
|
||||
@@ -18,3 +26,6 @@ traefik.http.routers.game-timer.middlewares=game-timer-auth
|
||||
# for docker lables use
|
||||
# `htpasswd -nb user password`
|
||||
traefik.http.middlewares.game-timer-auth.basicauth.users=user:$apr1$rFge2lVe$DpoqxMsxSVJubFLXu4OMr1
|
||||
|
||||
# Apply the middleware to the router
|
||||
traefik.http.routers.game-timer.middlewares=game-timer-auth
|
||||
|
||||
28
package.json
Normal file
28
package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "countdown",
|
||||
"version": "1.0.0",
|
||||
"description": "Multi-player chess timer with carousel navigation",
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "docker run -d -p 8080:80 --name game-timer-container game-timer:latest",
|
||||
"stop": "docker stop game-timer-container && docker rm game-timer-container",
|
||||
"build": "docker build -t 'game-timer:latest' .",
|
||||
"rebuild": "npm run stop || true && npm run build && npm run start",
|
||||
"logs": "docker logs game-timer-container",
|
||||
"status": "docker ps | grep game-timer-container",
|
||||
"dev": "cd /usr/share/nginx/html && python -m http.server 8000",
|
||||
"clean": "docker system prune -f"
|
||||
},
|
||||
"keywords": [
|
||||
"timer",
|
||||
"game",
|
||||
"chess",
|
||||
"pwa"
|
||||
],
|
||||
"author": "",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://gitea.virtonline.eu/2HoursProject/game-timer.git"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// pushFlicIntegration.js
|
||||
import { PUBLIC_VAPID_KEY, BACKEND_URL, FLIC_BUTTON_ID, FLIC_ACTIONS } from './config.js';
|
||||
import { PUBLIC_VAPID_KEY, BACKEND_URL, FLIC_BUTTON_ID, FLIC_ACTIONS, FLIC_BATTERY_THRESHOLD } from './config.js';
|
||||
|
||||
let pushSubscription = null; // Keep track locally if needed
|
||||
let actionHandlers = {}; // Store handlers for different Flic actions
|
||||
let lastBatteryWarningTimestamp = 0; // Track when last battery warning was shown
|
||||
|
||||
// --- Helper Functions ---
|
||||
|
||||
@@ -10,12 +11,32 @@ let actionHandlers = {}; // Store handlers for different Flic actions
|
||||
function getBasicAuthCredentials() {
|
||||
const storedAuth = localStorage.getItem('basicAuthCredentials');
|
||||
if (storedAuth) {
|
||||
try { return JSON.parse(storedAuth); } catch (error) { console.error('Failed to parse stored credentials:', error); }
|
||||
try {
|
||||
const credentials = JSON.parse(storedAuth);
|
||||
// Check if the credentials are valid
|
||||
if (credentials.username && credentials.password) {
|
||||
console.log('Using stored basic auth credentials.');
|
||||
return credentials;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse stored credentials:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// No valid stored credentials found
|
||||
// The function will return null and the caller should handle prompting if needed
|
||||
console.log('No valid stored credentials found.');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Prompt the user for credentials after permissions are granted
|
||||
function promptForCredentials() {
|
||||
console.log('Prompting user for auth credentials.');
|
||||
const username = prompt('Please enter your username for backend authentication:');
|
||||
if (!username) return null;
|
||||
const password = prompt('Please enter your password:');
|
||||
if (!password) return null;
|
||||
|
||||
const credentials = { username, password };
|
||||
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
|
||||
return credentials;
|
||||
@@ -47,6 +68,31 @@ function arrayBufferToBase64(buffer) {
|
||||
return window.btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
// Show a popup notification to the user
|
||||
function showBatteryWarning(batteryLevel) {
|
||||
// Only show warning once every 4 hours (to avoid annoying users)
|
||||
const now = Date.now();
|
||||
const fourHoursInMs = 4 * 60 * 60 * 1000;
|
||||
|
||||
if (now - lastBatteryWarningTimestamp < fourHoursInMs) {
|
||||
console.log(`[PushFlic] Battery warning suppressed (shown recently): ${batteryLevel}%`);
|
||||
return;
|
||||
}
|
||||
|
||||
lastBatteryWarningTimestamp = now;
|
||||
|
||||
// Show the notification
|
||||
const message = `Flic button battery is low (${batteryLevel}%). Please replace the battery soon.`;
|
||||
|
||||
// Show browser notification if permission granted
|
||||
if (Notification.permission === 'granted') {
|
||||
new Notification('Flic Button Low Battery', {
|
||||
body: message,
|
||||
icon: '/favicon.ico'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- Push Subscription Logic ---
|
||||
|
||||
async function subscribeToPush() {
|
||||
@@ -59,6 +105,8 @@ async function subscribeToPush() {
|
||||
}
|
||||
|
||||
try {
|
||||
// First request notification permission
|
||||
console.log('Requesting notification permission...');
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
console.warn('Notification permission denied.');
|
||||
@@ -66,6 +114,25 @@ async function subscribeToPush() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Notification permission granted.');
|
||||
|
||||
// After permission is granted, check for stored credentials or prompt user
|
||||
let credentials = getBasicAuthCredentials();
|
||||
if (!credentials) {
|
||||
const confirmAuth = confirm('Do you want to set up credentials for push notifications now?');
|
||||
if (!confirmAuth) {
|
||||
console.log('User declined to provide auth credentials.');
|
||||
return;
|
||||
}
|
||||
|
||||
credentials = promptForCredentials();
|
||||
if (!credentials) {
|
||||
console.log('User canceled credential input.');
|
||||
alert('Authentication required to set up push notifications.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
let existingSubscription = await registration.pushManager.getSubscription();
|
||||
let needsResubscribe = !existingSubscription;
|
||||
@@ -113,8 +180,20 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
||||
console.log(`Sending subscription for button "${buttonId}" to backend...`);
|
||||
const credentials = getBasicAuthCredentials();
|
||||
if (!credentials) {
|
||||
alert('Authentication required to save button link.');
|
||||
return;
|
||||
// One more chance to enter credentials if needed
|
||||
const confirmAuth = confirm('Authentication required to complete setup. Provide credentials now?');
|
||||
if (!confirmAuth) {
|
||||
alert('Authentication required to save button link.');
|
||||
return;
|
||||
}
|
||||
|
||||
const newCredentials = promptForCredentials();
|
||||
if (!newCredentials) {
|
||||
alert('Authentication required to save button link.');
|
||||
return;
|
||||
}
|
||||
|
||||
credentials = newCredentials;
|
||||
}
|
||||
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
@@ -122,16 +201,18 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
||||
if (authHeader) headers['Authorization'] = authHeader;
|
||||
|
||||
try {
|
||||
// Add support for handling CORS preflight with credentials
|
||||
const response = await fetch(`${BACKEND_URL}/subscribe`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
|
||||
headers: headers
|
||||
headers: headers,
|
||||
credentials: 'include' // This ensures credentials are sent with OPTIONS requests too
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
console.log('Subscription sent successfully:', result.message);
|
||||
// Maybe show a success message to the user
|
||||
alert('Push notification setup completed successfully!');
|
||||
} else {
|
||||
let errorMsg = `Server error: ${response.status}`;
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
@@ -152,8 +233,13 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
||||
// --- Flic Action Handling ---
|
||||
|
||||
// Called by app.js when a message is received from the service worker
|
||||
export function handleFlicAction(action, buttonId, timestamp) {
|
||||
console.log(`[PushFlic] Received Action: ${action} from Button: ${buttonId} at ${timestamp}`);
|
||||
export function handleFlicAction(action, buttonId, timestamp, batteryLevel) {
|
||||
console.log(`[PushFlic] Received Action: ${action} from Button: ${buttonId} battery: ${batteryLevel}% at ${timestamp}`);
|
||||
|
||||
// Check if battery is below threshold and show warning if needed
|
||||
if (batteryLevel < FLIC_BATTERY_THRESHOLD) {
|
||||
showBatteryWarning(batteryLevel);
|
||||
}
|
||||
|
||||
// Ignore actions from buttons other than the configured one
|
||||
if (buttonId !== FLIC_BUTTON_ID) {
|
||||
|
||||
12
sw.js
12
sw.js
@@ -75,7 +75,11 @@ self.addEventListener('push', event => {
|
||||
let pushData = {
|
||||
title: 'Flic Action',
|
||||
body: 'Button pressed!',
|
||||
data: { action: 'Unknown', button: 'Unknown' } // Default data
|
||||
data: {
|
||||
action: 'Unknown',
|
||||
button: 'Unknown',
|
||||
batteryLevel: undefined
|
||||
}
|
||||
};
|
||||
|
||||
// --- Attempt to parse data payload ---
|
||||
@@ -88,8 +92,7 @@ self.addEventListener('push', event => {
|
||||
pushData = {
|
||||
title: parsedData.title || pushData.title,
|
||||
body: parsedData.body || pushData.body,
|
||||
// IMPORTANT: Extract the action details sent from your backend
|
||||
data: parsedData.data || pushData.data // Expecting { action: 'SingleClick', button: '...' }
|
||||
data: parsedData.data || pushData.data // Expecting { action: 'SingleClick', button: 'game-button', batteryLevel: 75 }
|
||||
};
|
||||
|
||||
} catch (e) {
|
||||
@@ -106,7 +109,8 @@ self.addEventListener('push', event => {
|
||||
type: 'flic-action', // Custom message type
|
||||
action: pushData.data.action, // e.g., 'SingleClick', 'DoubleClick', 'Hold'
|
||||
button: pushData.data.button, // e.g., the button name
|
||||
timestamp: pushData.data.timestamp // e.g., the timestamp of the action
|
||||
timestamp: pushData.data.timestamp, // e.g., the timestamp of the action
|
||||
batteryLevel: pushData.data.batteryLevel // e.g., the battery level percentage
|
||||
};
|
||||
|
||||
// Send message to all open PWA windows controlled by this SW
|
||||
|
||||
30
virt-game-timer.service
Normal file
30
virt-game-timer.service
Normal file
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=virt-game-timer (virt-game-timer)
|
||||
Requires=docker.service
|
||||
After=docker.service
|
||||
DefaultDependencies=no
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment="HOME=/root"
|
||||
ExecStartPre=-/usr/bin/env sh -c '/usr/bin/env docker kill virt-game-timer 2>/dev/null || true'
|
||||
ExecStartPre=-/usr/bin/env sh -c '/usr/bin/env docker rm virt-game-timer 2>/dev/null || true'
|
||||
|
||||
ExecStart=/usr/bin/env docker run \
|
||||
--rm \
|
||||
--name=virt-game-timer \
|
||||
--log-driver=none \
|
||||
--network=traefik \
|
||||
--label-file=/virt/game-timer/labels \
|
||||
--mount type=bind,src=/etc/localtime,dst=/etc/localtime,ro \
|
||||
game-timer:latest
|
||||
|
||||
ExecStop=-/usr/bin/env sh -c '/usr/bin/env docker kill virt-game-timer 2>/dev/null || true'
|
||||
ExecStop=-/usr/bin/env sh -c '/usr/bin/env docker rm virt-game-timer 2>/dev/null || true'
|
||||
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
SyslogIdentifier=virt-game-timer
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in New Issue
Block a user