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) {
|
function handleServiceWorkerMessage(event) {
|
||||||
console.log('[App] Message received from Service Worker:', event.data);
|
console.log('[App] Message received from Service Worker:', event.data);
|
||||||
if (event.data?.type === 'flic-action') {
|
if (event.data?.type === 'flic-action') {
|
||||||
const { action, button, timestamp } = event.data;
|
const { action, button, timestamp, batteryLevel } = event.data;
|
||||||
pushFlic.handleFlicAction(action, button, timestamp);
|
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 BACKEND_URL = 'https://webpush.virtonline.eu';
|
||||||
export const FLIC_BUTTON_ID = 'game-button'; // Example ID, might need configuration
|
export const FLIC_BUTTON_ID = 'game-button'; // Example ID, might need configuration
|
||||||
export const LOCAL_STORAGE_KEY = 'gameTimerData';
|
export const LOCAL_STORAGE_KEY = 'gameTimerData';
|
||||||
|
export const FLIC_BATTERY_THRESHOLD = 50; // Battery percentage threshold for low battery warning
|
||||||
|
|
||||||
// Default player settings
|
// Default player settings
|
||||||
export const DEFAULT_PLAYER_TIME_SECONDS = 300; // 5 minutes
|
export const DEFAULT_PLAYER_TIME_SECONDS = 300; // 5 minutes
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
|
# Enable Traefik for this container
|
||||||
traefik.enable=true
|
traefik.enable=true
|
||||||
|
|
||||||
|
# Docker Network
|
||||||
traefik.docker.network=traefik
|
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.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=true
|
||||||
traefik.http.routers.game-timer.tls.certResolver=default
|
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.services.game-timer.loadbalancer.server.port=80
|
||||||
|
|
||||||
traefik.http.routers.game-timer.middlewares=game-timer-auth
|
|
||||||
# Declaring the user list
|
# Declaring the user list
|
||||||
#
|
#
|
||||||
# Note: when used in docker-compose.yml all dollar signs in the hash need to be doubled for escaping.
|
# Note: when used in docker-compose.yml all dollar signs in the hash need to be doubled for escaping.
|
||||||
@@ -17,4 +25,7 @@ traefik.http.routers.game-timer.middlewares=game-timer-auth
|
|||||||
# Also note that dollar signs should NOT be doubled when they are not evaluated (e.g. Ansible docker_container module).
|
# Also note that dollar signs should NOT be doubled when they are not evaluated (e.g. Ansible docker_container module).
|
||||||
# for docker lables use
|
# for docker lables use
|
||||||
# `htpasswd -nb user password`
|
# `htpasswd -nb user password`
|
||||||
traefik.http.middlewares.game-timer-auth.basicauth.users=user:$apr1$rFge2lVe$DpoqxMsxSVJubFLXu4OMr1
|
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
|
// 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 pushSubscription = null; // Keep track locally if needed
|
||||||
let actionHandlers = {}; // Store handlers for different Flic actions
|
let actionHandlers = {}; // Store handlers for different Flic actions
|
||||||
|
let lastBatteryWarningTimestamp = 0; // Track when last battery warning was shown
|
||||||
|
|
||||||
// --- Helper Functions ---
|
// --- Helper Functions ---
|
||||||
|
|
||||||
@@ -10,12 +11,32 @@ let actionHandlers = {}; // Store handlers for different Flic actions
|
|||||||
function getBasicAuthCredentials() {
|
function getBasicAuthCredentials() {
|
||||||
const storedAuth = localStorage.getItem('basicAuthCredentials');
|
const storedAuth = localStorage.getItem('basicAuthCredentials');
|
||||||
if (storedAuth) {
|
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:');
|
const username = prompt('Please enter your username for backend authentication:');
|
||||||
if (!username) return null;
|
if (!username) return null;
|
||||||
const password = prompt('Please enter your password:');
|
const password = prompt('Please enter your password:');
|
||||||
if (!password) return null;
|
if (!password) return null;
|
||||||
|
|
||||||
const credentials = { username, password };
|
const credentials = { username, password };
|
||||||
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
|
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
|
||||||
return credentials;
|
return credentials;
|
||||||
@@ -47,6 +68,31 @@ function arrayBufferToBase64(buffer) {
|
|||||||
return window.btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
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 ---
|
// --- Push Subscription Logic ---
|
||||||
|
|
||||||
async function subscribeToPush() {
|
async function subscribeToPush() {
|
||||||
@@ -59,12 +105,33 @@ async function subscribeToPush() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// First request notification permission
|
||||||
|
console.log('Requesting notification permission...');
|
||||||
const permission = await Notification.requestPermission();
|
const permission = await Notification.requestPermission();
|
||||||
if (permission !== 'granted') {
|
if (permission !== 'granted') {
|
||||||
console.warn('Notification permission denied.');
|
console.warn('Notification permission denied.');
|
||||||
alert('Please enable notifications to link the Flic button.');
|
alert('Please enable notifications to link the Flic button.');
|
||||||
return;
|
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;
|
const registration = await navigator.serviceWorker.ready;
|
||||||
let existingSubscription = await registration.pushManager.getSubscription();
|
let existingSubscription = await registration.pushManager.getSubscription();
|
||||||
@@ -113,8 +180,20 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
|||||||
console.log(`Sending subscription for button "${buttonId}" to backend...`);
|
console.log(`Sending subscription for button "${buttonId}" to backend...`);
|
||||||
const credentials = getBasicAuthCredentials();
|
const credentials = getBasicAuthCredentials();
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
alert('Authentication required to save button link.');
|
// One more chance to enter credentials if needed
|
||||||
return;
|
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' };
|
const headers = { 'Content-Type': 'application/json' };
|
||||||
@@ -122,16 +201,18 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
|||||||
if (authHeader) headers['Authorization'] = authHeader;
|
if (authHeader) headers['Authorization'] = authHeader;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Add support for handling CORS preflight with credentials
|
||||||
const response = await fetch(`${BACKEND_URL}/subscribe`, {
|
const response = await fetch(`${BACKEND_URL}/subscribe`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
|
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) {
|
if (response.ok) {
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
console.log('Subscription sent successfully:', result.message);
|
console.log('Subscription sent successfully:', result.message);
|
||||||
// Maybe show a success message to the user
|
alert('Push notification setup completed successfully!');
|
||||||
} else {
|
} else {
|
||||||
let errorMsg = `Server error: ${response.status}`;
|
let errorMsg = `Server error: ${response.status}`;
|
||||||
if (response.status === 401 || response.status === 403) {
|
if (response.status === 401 || response.status === 403) {
|
||||||
@@ -152,8 +233,13 @@ async function sendSubscriptionToServer(subscription, buttonId) {
|
|||||||
// --- Flic Action Handling ---
|
// --- Flic Action Handling ---
|
||||||
|
|
||||||
// Called by app.js when a message is received from the service worker
|
// Called by app.js when a message is received from the service worker
|
||||||
export function handleFlicAction(action, buttonId, timestamp) {
|
export function handleFlicAction(action, buttonId, timestamp, batteryLevel) {
|
||||||
console.log(`[PushFlic] Received Action: ${action} from Button: ${buttonId} at ${timestamp}`);
|
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
|
// Ignore actions from buttons other than the configured one
|
||||||
if (buttonId !== FLIC_BUTTON_ID) {
|
if (buttonId !== FLIC_BUTTON_ID) {
|
||||||
|
|||||||
14
sw.js
14
sw.js
@@ -75,7 +75,11 @@ self.addEventListener('push', event => {
|
|||||||
let pushData = {
|
let pushData = {
|
||||||
title: 'Flic Action',
|
title: 'Flic Action',
|
||||||
body: 'Button pressed!',
|
body: 'Button pressed!',
|
||||||
data: { action: 'Unknown', button: 'Unknown' } // Default data
|
data: {
|
||||||
|
action: 'Unknown',
|
||||||
|
button: 'Unknown',
|
||||||
|
batteryLevel: undefined
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Attempt to parse data payload ---
|
// --- Attempt to parse data payload ---
|
||||||
@@ -88,10 +92,9 @@ self.addEventListener('push', event => {
|
|||||||
pushData = {
|
pushData = {
|
||||||
title: parsedData.title || pushData.title,
|
title: parsedData.title || pushData.title,
|
||||||
body: parsedData.body || pushData.body,
|
body: parsedData.body || pushData.body,
|
||||||
// IMPORTANT: Extract the action details sent from your backend
|
data: parsedData.data || pushData.data // Expecting { action: 'SingleClick', button: 'game-button', batteryLevel: 75 }
|
||||||
data: parsedData.data || pushData.data // Expecting { action: 'SingleClick', button: '...' }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[ServiceWorker] Error parsing push data:', e);
|
console.error('[ServiceWorker] Error parsing push data:', e);
|
||||||
// Use default notification if parsing fails
|
// Use default notification if parsing fails
|
||||||
@@ -106,7 +109,8 @@ self.addEventListener('push', event => {
|
|||||||
type: 'flic-action', // Custom message type
|
type: 'flic-action', // Custom message type
|
||||||
action: pushData.data.action, // e.g., 'SingleClick', 'DoubleClick', 'Hold'
|
action: pushData.data.action, // e.g., 'SingleClick', 'DoubleClick', 'Hold'
|
||||||
button: pushData.data.button, // e.g., the button name
|
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
|
// 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