hotel_pi/frontend/src/lib/config.js
2026-04-16 18:19:15 -04:00

110 lines
2.7 KiB
JavaScript

// Configuration management - fetches from control-service API
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';
// Default configuration fallback
const DEFAULT_CONFIG = {
title: 'Guest',
welcomePrefix: 'WELCOME',
welcomeSuffix: 'Family',
useCustomSuffix: false,
use_ip_location: false,
manual_location: '',
idle_timeout_seconds: 300,
plex_enabled: true,
restaurants_enabled: true,
attractions_enabled: true,
brand_color: '#1f2937',
metadata: {},
};
let cachedConfig = null;
let cacheTimestamp = null;
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
/**
* Fetch configuration from control-service settings API
* Returns cached config if available and recent
*/
export async function fetchConfig() {
try {
// Return cached config if still fresh
if (cachedConfig && cacheTimestamp && Date.now() - cacheTimestamp < CACHE_DURATION) {
return cachedConfig;
}
const response = await fetch(`${API_URL}/api/settings`, {
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
console.warn(`Failed to fetch config (HTTP ${response.status}), using defaults`);
return DEFAULT_CONFIG;
}
const settings = await response.json();
if (!settings) {
console.warn('No settings found, using defaults');
return DEFAULT_CONFIG;
}
cachedConfig = { ...DEFAULT_CONFIG, ...settings };
cacheTimestamp = Date.now();
return cachedConfig;
} catch (error) {
console.error('Failed to fetch config:', error);
return DEFAULT_CONFIG;
}
}
/**
* Get the current location string (either from IP or manual)
*/
export async function getLocation() {
const config = await fetchConfig();
if (config.use_ip_location) {
return getLocationFromIP();
}
return config.manual_location || 'Unknown Location';
}
/**
* Get location from IP geolocation API (free service)
* Falls back to manual location if IP geolocation fails
*/
export async function getLocationFromIP() {
try {
const response = await fetch('https://ipapi.co/json/', {
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const location = [data.city, data.region, data.country_code]
.filter(Boolean)
.join(', ');
return location || 'Unknown Location';
} catch (error) {
console.warn('IP geolocation failed:', error);
const config = await fetchConfig();
return config.manual_location || 'Unknown Location';
}
}
/**
* Invalidate cache to force fresh fetch on next call
*/
export function invalidateCache() {
cachedConfig = null;
cacheTimestamp = null;
}