Compare commits
4
Commits
2a5b1736b8
...
d25343000f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d25343000f | ||
|
|
8ac1937784 | ||
|
|
2ff6c05a45 | ||
|
|
4894e07469 |
@@ -0,0 +1,98 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// GET current disk settings + actual disk usage
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const settings = {
|
||||
healthCheckInterval: parseInt(process.env.HEALTH_CHECK_INTERVAL || '30000'),
|
||||
healthMaxEntries: parseInt(process.env.HEALTH_MAX_ENTRIES || '500'),
|
||||
healthRetentionDays: parseInt(process.env.HEALTH_HISTORY_RETENTION || '14'),
|
||||
statsMaxEntries: parseInt(process.env.CONTAINER_STATS_MAX_ENTRIES || '500'),
|
||||
auditMaxEntries: parseInt(process.env.AUDIT_MAX_ENTRIES || '1000'),
|
||||
backupMaxStorageBytes: parseInt(process.env.BACKUP_MAX_STORAGE_BYTES || '0'),
|
||||
};
|
||||
|
||||
// Get actual disk usage
|
||||
let diskUsage = { total: 0, used: 0, free: 0, dataDirSize: 0 };
|
||||
try {
|
||||
const { execSync } = require('child_process');
|
||||
const dfOut = execSync("df -B1 /opt/dashcaddy/dashcaddy-api/data 2>/dev/null || df -B1 / 2>/dev/null").toString().trim().split('\n');
|
||||
if (dfOut.length > 1) {
|
||||
const parts = dfOut[1].split(/\s+/);
|
||||
diskUsage.total = parseInt(parts[1]) || 0;
|
||||
diskUsage.used = parseInt(parts[2]) || 0;
|
||||
diskUsage.free = parseInt(parts[3]) || 0;
|
||||
}
|
||||
const duOut = execSync("du -sb /opt/dashcaddy/dashcaddy-api/data 2>/dev/null || echo 0").toString().trim().split(/\s+/);
|
||||
diskUsage.dataDirSize = parseInt(duOut[0]) || 0;
|
||||
} catch {}
|
||||
|
||||
// Load persisted settings
|
||||
const settingsFile = path.join(path.dirname(require('../config/paths').configFile), 'disk-settings.json');
|
||||
let persisted = {};
|
||||
try { persisted = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); } catch {}
|
||||
|
||||
res.json({ success: true, current: { ...settings, ...persisted }, diskUsage });
|
||||
} catch (e) {
|
||||
res.status(500).json({ success: false, error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST update settings
|
||||
router.post('/', (req, res) => {
|
||||
try {
|
||||
const { healthInterval, healthMaxEntries, healthRetentionDays, statsMaxEntries, auditMaxEntries } = req.body;
|
||||
const updates = {};
|
||||
|
||||
if (healthInterval !== undefined) { updates.healthCheckInterval = parseInt(healthInterval); process.env.HEALTH_CHECK_INTERVAL = String(healthInterval); }
|
||||
if (healthMaxEntries !== undefined) { updates.healthMaxEntries = parseInt(healthMaxEntries); process.env.HEALTH_MAX_ENTRIES = String(healthMaxEntries); }
|
||||
if (healthRetentionDays !== undefined) { updates.healthRetentionDays = parseInt(healthRetentionDays); process.env.HEALTH_HISTORY_RETENTION = String(healthRetentionDays); }
|
||||
if (statsMaxEntries !== undefined) { updates.statsMaxEntries = parseInt(statsMaxEntries); process.env.CONTAINER_STATS_MAX_ENTRIES = String(statsMaxEntries); }
|
||||
if (auditMaxEntries !== undefined) { updates.auditMaxEntries = parseInt(auditMaxEntries); process.env.AUDIT_MAX_ENTRIES = String(auditMaxEntries); }
|
||||
|
||||
// Persist to file
|
||||
const paths = require('../config/paths');
|
||||
const settingsFile = path.join(path.dirname(paths.configFile), 'disk-settings.json');
|
||||
let existing = {};
|
||||
try { existing = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); } catch {}
|
||||
fs.writeFileSync(settingsFile, JSON.stringify({ ...existing, ...updates }, null, 2));
|
||||
|
||||
res.json({ success: true, updated: updates, message: 'Settings saved. Some changes apply on next container restart.' });
|
||||
} catch (e) {
|
||||
res.status(500).json({ success: false, error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST trigger immediate cleanup
|
||||
router.post('/cleanup', async (req, res) => {
|
||||
try {
|
||||
const results = { cleaned: {} };
|
||||
|
||||
// Clean health history
|
||||
try {
|
||||
const healthChecker = require('../monitoring/health-checker');
|
||||
if (healthChecker.instance && healthChecker.instance.cleanupHistory) {
|
||||
healthChecker.instance.cleanupHistory();
|
||||
results.cleaned.healthHistory = 'Cleaned old entries';
|
||||
}
|
||||
} catch (e) { results.cleaned.healthHistory = 'Skipped: ' + e.message; }
|
||||
|
||||
// Clean container stats
|
||||
try {
|
||||
const resourceMonitor = require('../managers/resource-monitor');
|
||||
if (resourceMonitor.instance && resourceMonitor.instance.cleanupOldStats) {
|
||||
resourceMonitor.instance.cleanupOldStats();
|
||||
results.cleaned.containerStats = 'Cleaned old entries';
|
||||
}
|
||||
} catch (e) { results.cleaned.containerStats = 'Skipped: ' + e.message; }
|
||||
|
||||
res.json({ success: true, results });
|
||||
} catch (e) {
|
||||
res.status(500).json({ success: false, error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -28,6 +28,7 @@ const auditLogger = require('./security/audit-logger');
|
||||
const portLockManager = require('./managers/port-lock-manager');
|
||||
const resourceMonitor = require('./managers/resource-monitor');
|
||||
const backupManager = require('./utilities/backup-manager');
|
||||
require("./utilities/nesting-guard")();
|
||||
const healthChecker = require('./monitoring/health-checker');
|
||||
const updateManager = require('./managers/update-manager');
|
||||
const selfUpdater = require('./docker/self-updater');
|
||||
@@ -93,6 +94,7 @@ const eventsRoutes = require('../routes/events');
|
||||
const workflowsRoutes = require('../routes/workflows');
|
||||
const dependenciesRoutes = require('../routes/dependencies');
|
||||
const securityRoutes = require('../routes/security');
|
||||
const diskSettingsRoutes = require('../routes/disk-settings');
|
||||
const logInsightsRoutes = require('../routes/log-insights');
|
||||
const billingRoutes = require('../routes/billing');
|
||||
const DependencyManager = require('./managers/dependency-manager');
|
||||
@@ -756,6 +758,7 @@ async function createApp() {
|
||||
}));
|
||||
|
||||
// Log Insights — plain English activity summary + safe log disposal
|
||||
apiRouter.use('/disk-settings', diskSettingsRoutes);
|
||||
apiRouter.use(logInsightsRoutes({
|
||||
asyncHandler: ctx.asyncHandler,
|
||||
ok: ctx.ok,
|
||||
|
||||
@@ -14,7 +14,7 @@ const KNOWN_KEYS = [
|
||||
'configurationType', 'defaults', 'customLogo', 'customFavicon',
|
||||
'dashboardTitle', 'tailscale', 'license', 'skipped',
|
||||
'routingMode', 'domain', 'email', 'defaultIP', 'pylon',
|
||||
'customLogoDark', 'customLogoLight'
|
||||
'customLogoDark', 'customLogoLight', 'language'
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
+512
-233
@@ -1,264 +1,543 @@
|
||||
/**
|
||||
* DC-077: Internationalization (i18n) framework for DashCaddy
|
||||
* DashCaddy Internationalization (i18n) — 31 languages
|
||||
*
|
||||
* Lightweight translation system for the dashboard frontend and API responses.
|
||||
* Supports multiple languages via JSON translation files loaded on demand.
|
||||
* Translations for dashboard UI and API error messages.
|
||||
* Languages: Arabic, Bengali, Chinese, Czech, Danish, Dutch, English, Finnish,
|
||||
* French, German, Greek, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean,
|
||||
* Malay, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Spanish,
|
||||
* Swedish, Thai, Turkish, Ukrainian, Urdu, Vietnamese.
|
||||
*
|
||||
* Languages are stored in /assets/i18n/{lang}.json
|
||||
* Default language is 'en' (English).
|
||||
*
|
||||
* Usage in frontend JS:
|
||||
* const { t, setLanguage, getLanguage } = window.DCI18n;
|
||||
* document.querySelector('.title').textContent = t('dashboard.title');
|
||||
*
|
||||
* Usage in API responses:
|
||||
* const i18n = require('./i18n');
|
||||
* const msg = i18n.t('error.container_not_found', req.lang || 'en');
|
||||
* No Hebrew — per project policy.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Built-in translations (loaded synchronously at startup)
|
||||
const TRANSLATIONS = {
|
||||
en: {
|
||||
'dashboard.title': 'Dashboard',
|
||||
'dashboard.services': 'Services',
|
||||
'dashboard.containers': 'Containers',
|
||||
'dashboard.health': 'Health',
|
||||
'dashboard.settings': 'Settings',
|
||||
'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Monitoring',
|
||||
'dashboard.security': 'Security',
|
||||
|
||||
'service.status.healthy': 'Healthy',
|
||||
'service.status.degraded': 'Degraded',
|
||||
'service.status.down': 'Down',
|
||||
'service.status.unknown': 'Unknown',
|
||||
'service.status.pending': 'Pending',
|
||||
|
||||
'action.start': 'Start',
|
||||
'action.stop': 'Stop',
|
||||
'action.restart': 'Restart',
|
||||
'action.delete': 'Delete',
|
||||
'action.update': 'Update',
|
||||
'action.deploy': 'Deploy',
|
||||
'action.save': 'Save',
|
||||
'action.cancel': 'Cancel',
|
||||
en: { // 🇬🇧 English
|
||||
'dashboard.title': 'Dashboard', 'dashboard.services': 'Services', 'dashboard.containers': 'Containers',
|
||||
'dashboard.health': 'Health', 'dashboard.settings': 'Settings', 'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Monitoring', 'dashboard.security': 'Security',
|
||||
'service.status.healthy': 'Healthy', 'service.status.degraded': 'Degraded', 'service.status.down': 'Down',
|
||||
'service.status.unknown': 'Unknown', 'service.status.pending': 'Pending',
|
||||
'action.start': 'Start', 'action.stop': 'Stop', 'action.restart': 'Restart', 'action.delete': 'Delete',
|
||||
'action.update': 'Update', 'action.deploy': 'Deploy', 'action.save': 'Save', 'action.cancel': 'Cancel',
|
||||
'action.confirm': 'Confirm',
|
||||
|
||||
'error.not_found': 'Resource not found',
|
||||
'error.unauthorized': 'Unauthorized',
|
||||
'error.forbidden': 'Forbidden',
|
||||
'error.rate_limited': 'Too many requests',
|
||||
'error.internal': 'Internal server error',
|
||||
'error.container_not_found': 'Container not found',
|
||||
'error.service_not_found': 'Service not found',
|
||||
'error.invalid_input': 'Invalid input',
|
||||
'error.docker_unreachable': 'Docker daemon is not reachable',
|
||||
'error.not_found': 'Resource not found', 'error.unauthorized': 'Unauthorized', 'error.forbidden': 'Forbidden',
|
||||
'error.rate_limited': 'Too many requests', 'error.internal': 'Internal server error',
|
||||
'error.container_not_found': 'Container not found', 'error.service_not_found': 'Service not found',
|
||||
'error.invalid_input': 'Invalid input', 'error.docker_unreachable': 'Docker daemon is not reachable',
|
||||
'error.disk_full': 'Disk space is critically low',
|
||||
},
|
||||
|
||||
es: {
|
||||
'dashboard.title': 'Panel de control',
|
||||
'dashboard.services': 'Servicios',
|
||||
'dashboard.containers': 'Contenedores',
|
||||
'dashboard.health': 'Salud',
|
||||
'dashboard.settings': 'Configuración',
|
||||
'dashboard.backups': 'Copias de seguridad',
|
||||
'dashboard.monitoring': 'Monitoreo',
|
||||
'dashboard.security': 'Seguridad',
|
||||
|
||||
'service.status.healthy': 'Saludable',
|
||||
'service.status.degraded': 'Degradado',
|
||||
'service.status.down': 'Caído',
|
||||
'service.status.unknown': 'Desconocido',
|
||||
'service.status.pending': 'Pendiente',
|
||||
|
||||
'action.start': 'Iniciar',
|
||||
'action.stop': 'Detener',
|
||||
'action.restart': 'Reiniciar',
|
||||
'action.delete': 'Eliminar',
|
||||
'action.update': 'Actualizar',
|
||||
'action.deploy': 'Desplegar',
|
||||
'action.save': 'Guardar',
|
||||
'action.cancel': 'Cancelar',
|
||||
'action.confirm': 'Confirmar',
|
||||
|
||||
'error.not_found': 'Recurso no encontrado',
|
||||
'error.unauthorized': 'No autorizado',
|
||||
'error.forbidden': 'Prohibido',
|
||||
'error.rate_limited': 'Demasiadas solicitudes',
|
||||
'error.internal': 'Error interno del servidor',
|
||||
'error.container_not_found': 'Contenedor no encontrado',
|
||||
'error.service_not_found': 'Servicio no encontrado',
|
||||
'error.invalid_input': 'Entrada inválida',
|
||||
'error.docker_unreachable': 'El demonio de Docker no es accesible',
|
||||
'error.disk_full': 'Espacio en disco críticamente bajo',
|
||||
ar: { // 🇸🇦 العربية
|
||||
'dashboard.title': 'لوحة التحكم', 'dashboard.services': 'الخدمات', 'dashboard.containers': 'الحاويات',
|
||||
'dashboard.health': 'الصحة', 'dashboard.settings': 'الإعدادات', 'dashboard.backups': 'النسخ الاحتياطية',
|
||||
'dashboard.monitoring': 'المراقبة', 'dashboard.security': 'الأمان',
|
||||
'service.status.healthy': 'سليم', 'service.status.degraded': 'متدهور', 'service.status.down': 'متوقف',
|
||||
'service.status.unknown': 'غير معروف', 'service.status.pending': 'قيد الانتظار',
|
||||
'action.start': 'تشغيل', 'action.stop': 'إيقاف', 'action.restart': 'إعادة تشغيل', 'action.delete': 'حذف',
|
||||
'action.update': 'تحديث', 'action.deploy': 'نشر', 'action.save': 'حفظ', 'action.cancel': 'إلغاء',
|
||||
'action.confirm': 'تأكيد',
|
||||
'error.not_found': 'المورد غير موجود', 'error.unauthorized': 'غير مصرح', 'error.forbidden': 'محظور',
|
||||
'error.rate_limited': 'طلبات كثيرة جداً', 'error.internal': 'خطأ داخلي في الخادم',
|
||||
'error.container_not_found': 'الحاوية غير موجودة', 'error.service_not_found': 'الخدمة غير موجودة',
|
||||
'error.invalid_input': 'إدخال غير صالح', 'error.docker_unreachable': 'لا يمكن الوصول إلى Docker',
|
||||
'error.disk_full': 'مساحة القرص منخفضة بشكل حرج',
|
||||
},
|
||||
|
||||
fr: {
|
||||
'dashboard.title': 'Tableau de bord',
|
||||
'dashboard.services': 'Services',
|
||||
'dashboard.containers': 'Conteneurs',
|
||||
'dashboard.health': 'Santé',
|
||||
'dashboard.settings': 'Paramètres',
|
||||
'dashboard.backups': 'Sauvegardes',
|
||||
'dashboard.monitoring': 'Surveillance',
|
||||
'dashboard.security': 'Sécurité',
|
||||
|
||||
'service.status.healthy': 'Sain',
|
||||
'service.status.degraded': 'Dégradé',
|
||||
'service.status.down': 'Hors ligne',
|
||||
'service.status.unknown': 'Inconnu',
|
||||
'service.status.pending': 'En attente',
|
||||
|
||||
'action.start': 'Démarrer',
|
||||
'action.stop': 'Arrêter',
|
||||
'action.restart': 'Redémarrer',
|
||||
'action.delete': 'Supprimer',
|
||||
'action.update': 'Mettre à jour',
|
||||
'action.deploy': 'Déployer',
|
||||
'action.save': 'Enregistrer',
|
||||
'action.cancel': 'Annuler',
|
||||
'action.confirm': 'Confirmer',
|
||||
|
||||
'error.not_found': 'Ressource introuvable',
|
||||
'error.unauthorized': 'Non autorisé',
|
||||
'error.forbidden': 'Interdit',
|
||||
'error.rate_limited': 'Trop de requêtes',
|
||||
'error.internal': 'Erreur interne du serveur',
|
||||
'error.container_not_found': 'Conteneur introuvable',
|
||||
'error.service_not_found': 'Service introuvable',
|
||||
'error.invalid_input': 'Entrée invalide',
|
||||
'error.docker_unreachable': 'Le démon Docker est injoignable',
|
||||
'error.disk_full': 'Espace disque critique',
|
||||
bn: { // 🇧🇩 বাংলা
|
||||
'dashboard.title': 'ড্যাশবোর্ড', 'dashboard.services': 'পরিষেবা', 'dashboard.containers': 'কন্টেইনার',
|
||||
'dashboard.health': 'স্বাস্থ্য', 'dashboard.settings': 'সেটিংস', 'dashboard.backups': 'ব্যাকআপ',
|
||||
'dashboard.monitoring': 'নিরীক্ষণ', 'dashboard.security': 'নিরাপত্তা',
|
||||
'service.status.healthy': 'সুস্থ', 'service.status.degraded': 'অবনমিত', 'service.status.down': 'বন্ধ',
|
||||
'service.status.unknown': 'অজানা', 'service.status.pending': 'মুলতুবি',
|
||||
'action.start': 'শুরু', 'action.stop': 'বন্ধ', 'action.restart': 'পুনরায় চালু', 'action.delete': 'মুছুন',
|
||||
'action.update': 'আপডেট', 'action.deploy': 'স্থাপন', 'action.save': 'সংরক্ষণ', 'action.cancel': 'বাতিল',
|
||||
'action.confirm': 'নিশ্চিত করুন',
|
||||
'error.not_found': 'সম্পদ পাওয়া যায়নি', 'error.unauthorized': 'অননুমোদিত', 'error.forbidden': 'নিষিদ্ধ',
|
||||
'error.rate_limited': 'অনেক বেশি অনুরোধ', 'error.internal': 'অভ্যন্তরীণ সার্ভার ত্রুটি',
|
||||
'error.container_not_found': 'কন্টেইনার পাওয়া যায়নি', 'error.service_not_found': 'পরিষেবা পাওয়া যায়নি',
|
||||
'error.invalid_input': 'অবৈধ ইনপুট', 'error.docker_unreachable': 'Docker ডেমনে পৌঁছানো যাচ্ছে না',
|
||||
'error.disk_full': 'ডিস্ক স্থান সংকটজনকভাবে কম',
|
||||
},
|
||||
|
||||
de: {
|
||||
'dashboard.title': 'Dashboard',
|
||||
'dashboard.services': 'Dienste',
|
||||
'dashboard.containers': 'Container',
|
||||
'dashboard.health': 'Zustand',
|
||||
'dashboard.settings': 'Einstellungen',
|
||||
'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Überwachung',
|
||||
'dashboard.security': 'Sicherheit',
|
||||
|
||||
'service.status.healthy': 'Gesund',
|
||||
'service.status.degraded': 'Beeinträchtigt',
|
||||
'service.status.down': 'Ausgefallen',
|
||||
'service.status.unknown': 'Unbekannt',
|
||||
'service.status.pending': 'Ausstehend',
|
||||
|
||||
'action.start': 'Starten',
|
||||
'action.stop': 'Stopp',
|
||||
'action.restart': 'Neustart',
|
||||
'action.delete': 'Löschen',
|
||||
'action.update': 'Aktualisieren',
|
||||
'action.deploy': 'Bereitstellen',
|
||||
'action.save': 'Speichern',
|
||||
'action.cancel': 'Abbrechen',
|
||||
cs: { // 🇨🇿 Čeština
|
||||
'dashboard.title': 'Nástěnka', 'dashboard.services': 'Služby', 'dashboard.containers': 'Kontejnery',
|
||||
'dashboard.health': 'Stav', 'dashboard.settings': 'Nastavení', 'dashboard.backups': 'Zálohy',
|
||||
'dashboard.monitoring': 'Sledování', 'dashboard.security': 'Zabezpečení',
|
||||
'service.status.healthy': 'Zdravý', 'service.status.degraded': 'Zhoršený', 'service.status.down': 'Nedostupný',
|
||||
'service.status.unknown': 'Neznámý', 'service.status.pending': 'Čeká',
|
||||
'action.start': 'Spustit', 'action.stop': 'Zastavit', 'action.restart': 'Restartovat', 'action.delete': 'Smazat',
|
||||
'action.update': 'Aktualizovat', 'action.deploy': 'Nasadit', 'action.save': 'Uložit', 'action.cancel': 'Zrušit',
|
||||
'action.confirm': 'Potvrdit',
|
||||
'error.not_found': 'Zdroj nenalezen', 'error.unauthorized': 'Neoprávněno', 'error.forbidden': 'Zakázáno',
|
||||
'error.rate_limited': 'Příliš mnoho požadavků', 'error.internal': 'Interní chyba serveru',
|
||||
'error.container_not_found': 'Kontejner nenalezen', 'error.service_not_found': 'Služba nenalezena',
|
||||
'error.invalid_input': 'Neplatný vstup', 'error.docker_unreachable': 'Docker daemon není dostupný',
|
||||
'error.disk_full': 'Místo na disku je kriticky nízké',
|
||||
},
|
||||
da: { // 🇩🇰 Dansk
|
||||
'dashboard.title': 'Instrumentbræt', 'dashboard.services': 'Tjenester', 'dashboard.containers': 'Containere',
|
||||
'dashboard.health': 'Sundhed', 'dashboard.settings': 'Indstillinger', 'dashboard.backups': 'Sikkerhedskopier',
|
||||
'dashboard.monitoring': 'Overvågning', 'dashboard.security': 'Sikkerhed',
|
||||
'service.status.healthy': 'Sund', 'service.status.degraded': 'Forringet', 'service.status.down': 'Nede',
|
||||
'service.status.unknown': 'Ukendt', 'service.status.pending': 'Afventer',
|
||||
'action.start': 'Start', 'action.stop': 'Stop', 'action.restart': 'Genstart', 'action.delete': 'Slet',
|
||||
'action.update': 'Opdater', 'action.deploy': 'Udrul', 'action.save': 'Gem', 'action.cancel': 'Annuller',
|
||||
'action.confirm': 'Bekræft',
|
||||
'error.not_found': 'Ressource ikke fundet', 'error.unauthorized': 'Ikke autoriseret', 'error.forbidden': 'Forbudt',
|
||||
'error.rate_limited': 'For mange anmodninger', 'error.internal': 'Intern serverfejl',
|
||||
'error.container_not_found': 'Container ikke fundet', 'error.service_not_found': 'Tjeneste ikke fundet',
|
||||
'error.invalid_input': 'Ugyldigt input', 'error.docker_unreachable': 'Docker-daemon er ikke tilgængelig',
|
||||
'error.disk_full': 'Diskpladsen er kritisk lav',
|
||||
},
|
||||
de: { // 🇩🇪 Deutsch
|
||||
'dashboard.title': 'Dashboard', 'dashboard.services': 'Dienste', 'dashboard.containers': 'Container',
|
||||
'dashboard.health': 'Zustand', 'dashboard.settings': 'Einstellungen', 'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Überwachung', 'dashboard.security': 'Sicherheit',
|
||||
'service.status.healthy': 'Gesund', 'service.status.degraded': 'Beeinträchtigt', 'service.status.down': 'Ausgefallen',
|
||||
'service.status.unknown': 'Unbekannt', 'service.status.pending': 'Ausstehend',
|
||||
'action.start': 'Starten', 'action.stop': 'Stopp', 'action.restart': 'Neustart', 'action.delete': 'Löschen',
|
||||
'action.update': 'Aktualisieren', 'action.deploy': 'Bereitstellen', 'action.save': 'Speichern', 'action.cancel': 'Abbrechen',
|
||||
'action.confirm': 'Bestätigen',
|
||||
|
||||
'error.not_found': 'Ressource nicht gefunden',
|
||||
'error.unauthorized': 'Nicht autorisiert',
|
||||
'error.forbidden': 'Verboten',
|
||||
'error.rate_limited': 'Zu viele Anfragen',
|
||||
'error.internal': 'Interner Serverfehler',
|
||||
'error.container_not_found': 'Container nicht gefunden',
|
||||
'error.service_not_found': 'Dienst nicht gefunden',
|
||||
'error.invalid_input': 'Ungültige Eingabe',
|
||||
'error.docker_unreachable': 'Docker-Daemon ist nicht erreichbar',
|
||||
'error.not_found': 'Ressource nicht gefunden', 'error.unauthorized': 'Nicht autorisiert', 'error.forbidden': 'Verboten',
|
||||
'error.rate_limited': 'Zu viele Anfragen', 'error.internal': 'Interner Serverfehler',
|
||||
'error.container_not_found': 'Container nicht gefunden', 'error.service_not_found': 'Dienst nicht gefunden',
|
||||
'error.invalid_input': 'Ungültige Eingabe', 'error.docker_unreachable': 'Docker-Daemon ist nicht erreichbar',
|
||||
'error.disk_full': 'Speicherplatz kritisch niedrig',
|
||||
},
|
||||
|
||||
ar: {
|
||||
'dashboard.title': 'لوحة التحكم',
|
||||
'dashboard.services': 'الخدمات',
|
||||
'dashboard.containers': 'الحاويات',
|
||||
'dashboard.health': 'الصحة',
|
||||
'dashboard.settings': 'الإعدادات',
|
||||
'dashboard.backups': 'النسخ الاحتياطية',
|
||||
'dashboard.monitoring': 'المراقبة',
|
||||
'dashboard.security': 'الأمان',
|
||||
|
||||
'service.status.healthy': 'سليم',
|
||||
'service.status.degraded': 'متدهور',
|
||||
'service.status.down': 'متوقف',
|
||||
'service.status.unknown': 'غير معروف',
|
||||
'service.status.pending': 'قيد الانتظار',
|
||||
|
||||
'action.start': 'تشغيل',
|
||||
'action.stop': 'إيقاف',
|
||||
'action.restart': 'إعادة تشغيل',
|
||||
'action.delete': 'حذف',
|
||||
'action.update': 'تحديث',
|
||||
'action.deploy': 'نشر',
|
||||
'action.save': 'حفظ',
|
||||
'action.cancel': 'إلغاء',
|
||||
'action.confirm': 'تأكيد',
|
||||
|
||||
'error.not_found': 'المورد غير موجود',
|
||||
'error.unauthorized': 'غير مصرح',
|
||||
'error.forbidden': 'محظور',
|
||||
'error.rate_limited': 'طلبات كثيرة جداً',
|
||||
'error.internal': 'خطأ داخلي في الخادم',
|
||||
'error.container_not_found': 'الحاوية غير موجودة',
|
||||
'error.service_not_found': 'الخدمة غير موجودة',
|
||||
'error.invalid_input': 'إدخال غير صالح',
|
||||
'error.docker_unreachable': 'لا يمكن الوصول إلى Docker',
|
||||
'error.disk_full': 'مساحة القرص منخفضة بشكل حرج',
|
||||
el: { // 🇬🇷 Ελληνικά
|
||||
'dashboard.title': 'Πίνακας ελέγχου', 'dashboard.services': 'Υπηρεσίες', 'dashboard.containers': 'Κοντέινερ',
|
||||
'dashboard.health': 'Υγεία', 'dashboard.settings': 'Ρυθμίσεις', 'dashboard.backups': 'Αντίγραφα ασφαλείας',
|
||||
'dashboard.monitoring': 'Παρακολούθηση', 'dashboard.security': 'Ασφάλεια',
|
||||
'service.status.healthy': 'Υγιής', 'service.status.degraded': 'Υποβαθμισμένος', 'service.status.down': 'Κάτω',
|
||||
'service.status.unknown': 'Άγνωστος', 'service.status.pending': 'Εκκρεμής',
|
||||
'action.start': 'Έναρξη', 'action.stop': 'Διακοπή', 'action.restart': 'Επανεκκίνηση', 'action.delete': 'Διαγραφή',
|
||||
'action.update': 'Ενημέρωση', 'action.deploy': 'Ανάπτυξη', 'action.save': 'Αποθήκευση', 'action.cancel': 'Ακύρωση',
|
||||
'action.confirm': 'Επιβεβαίωση',
|
||||
'error.not_found': 'Ο πόρος δεν βρέθηκε', 'error.unauthorized': 'Μη εξουσιοδοτημένος', 'error.forbidden': 'Απαγορευμένο',
|
||||
'error.rate_limited': 'Πάρα πολλά αιτήματα', 'error.internal': 'Εσωτερικό σφάλμα διακομιστή',
|
||||
'error.container_not_found': 'Το κοντέινερ δεν βρέθηκε', 'error.service_not_found': 'Η υπηρεσία δεν βρέθηκε',
|
||||
'error.invalid_input': 'Μη έγκυρη είσοδος', 'error.docker_unreachable': 'Ο δαίμονας Docker δεν είναι προσβάσιμος',
|
||||
'error.disk_full': 'Ο χώρος δίσκου είναι κρίσιμα χαμηλός',
|
||||
},
|
||||
es: { // 🇪🇸 Español
|
||||
'dashboard.title': 'Panel de control', 'dashboard.services': 'Servicios', 'dashboard.containers': 'Contenedores',
|
||||
'dashboard.health': 'Salud', 'dashboard.settings': 'Configuración', 'dashboard.backups': 'Copias de seguridad',
|
||||
'dashboard.monitoring': 'Monitoreo', 'dashboard.security': 'Seguridad',
|
||||
'service.status.healthy': 'Saludable', 'service.status.degraded': 'Degradado', 'service.status.down': 'Caído',
|
||||
'service.status.unknown': 'Desconocido', 'service.status.pending': 'Pendiente',
|
||||
'action.start': 'Iniciar', 'action.stop': 'Detener', 'action.restart': 'Reiniciar', 'action.delete': 'Eliminar',
|
||||
'action.update': 'Actualizar', 'action.deploy': 'Desplegar', 'action.save': 'Guardar', 'action.cancel': 'Cancelar',
|
||||
'action.confirm': 'Confirmar',
|
||||
'error.not_found': 'Recurso no encontrado', 'error.unauthorized': 'No autorizado', 'error.forbidden': 'Prohibido',
|
||||
'error.rate_limited': 'Demasiadas solicitudes', 'error.internal': 'Error interno del servidor',
|
||||
'error.container_not_found': 'Contenedor no encontrado', 'error.service_not_found': 'Servicio no encontrado',
|
||||
'error.invalid_input': 'Entrada inválida', 'error.docker_unreachable': 'El demonio de Docker no es accesible',
|
||||
'error.disk_full': 'Espacio en disco críticamente bajo',
|
||||
},
|
||||
fa: { // 🇮🇷 فارسی
|
||||
'dashboard.title': 'داشبورد', 'dashboard.services': 'سرویسها', 'dashboard.containers': 'کانتینرها',
|
||||
'dashboard.health': 'سلامت', 'dashboard.settings': 'تنظیمات', 'dashboard.backups': 'پشتیبانگیری',
|
||||
'dashboard.monitoring': 'نظارت', 'dashboard.security': 'امنیت',
|
||||
'service.status.healthy': 'سالم', 'service.status.degraded': 'تنزلیافته', 'service.status.down': 'خراب',
|
||||
'service.status.unknown': 'نامشخص', 'service.status.pending': 'در انتظار',
|
||||
'action.start': 'شروع', 'action.stop': 'توقف', 'action.restart': 'راهاندازی مجدد', 'action.delete': 'حذف',
|
||||
'action.update': 'بهروزرسانی', 'action.deploy': 'استقرار', 'action.save': 'ذخیره', 'action.cancel': 'لغو',
|
||||
'action.confirm': 'تأیید',
|
||||
'error.not_found': 'منبع یافت نشد', 'error.unauthorized': 'غیرمجاز', 'error.forbidden': 'ممنوع',
|
||||
'error.rate_limited': 'درخواستهای بیش از حد', 'error.internal': 'خطای داخلی سرور',
|
||||
'error.container_not_found': 'کانتینر یافت نشد', 'error.service_not_found': 'سرویس یافت نشد',
|
||||
'error.invalid_input': 'ورودی نامعتبر', 'error.docker_unreachable': 'دسترسی به Docker daemon ممکن نیست',
|
||||
'error.disk_full': 'فضای دیسک بهطور بحرانی کم است',
|
||||
},
|
||||
fi: { // 🇫🇮 Suomi
|
||||
'dashboard.title': 'Ohjauspaneeli', 'dashboard.services': 'Palvelut', 'dashboard.containers': 'Kontainerit',
|
||||
'dashboard.health': 'Terveys', 'dashboard.settings': 'Asetukset', 'dashboard.backups': 'Varmuuskopiot',
|
||||
'dashboard.monitoring': 'Valvonta', 'dashboard.security': 'Turvallisuus',
|
||||
'service.status.healthy': 'Terve', 'service.status.degraded': 'Heikentynyt', 'service.status.down': 'Alhaalla',
|
||||
'service.status.unknown': 'Tuntematon', 'service.status.pending': 'Odottaa',
|
||||
'action.start': 'Käynnistä', 'action.stop': 'Pysäytä', 'action.restart': 'Käynnistä uudelleen', 'action.delete': 'Poista',
|
||||
'action.update': 'Päivitä', 'action.deploy': 'Käyttöönotto', 'action.save': 'Tallenna', 'action.cancel': 'Peruuta',
|
||||
'action.confirm': 'Vahvista',
|
||||
'error.not_found': 'Resurssia ei löytynyt', 'error.unauthorized': 'Ei valtuutettu', 'error.forbidden': 'Kielletty',
|
||||
'error.rate_limited': 'Liian monta pyyntöä', 'error.internal': 'Sisäinen palvelinvirhe',
|
||||
'error.container_not_found': 'Kontaineria ei löytynyt', 'error.service_not_found': 'Palvelua ei löytynyt',
|
||||
'error.invalid_input': 'Virheellinen syöte', 'error.docker_unreachable': 'Docker-daemoniin ei saada yhteyttä',
|
||||
'error.disk_full': 'Levytila on kriittisesti vähissä',
|
||||
},
|
||||
fr: { // 🇫🇷 Français
|
||||
'dashboard.title': 'Tableau de bord', 'dashboard.services': 'Services', 'dashboard.containers': 'Conteneurs',
|
||||
'dashboard.health': 'Santé', 'dashboard.settings': 'Paramètres', 'dashboard.backups': 'Sauvegardes',
|
||||
'dashboard.monitoring': 'Surveillance', 'dashboard.security': 'Sécurité',
|
||||
'service.status.healthy': 'Sain', 'service.status.degraded': 'Dégradé', 'service.status.down': 'Hors ligne',
|
||||
'service.status.unknown': 'Inconnu', 'service.status.pending': 'En attente',
|
||||
'action.start': 'Démarrer', 'action.stop': 'Arrêter', 'action.restart': 'Redémarrer', 'action.delete': 'Supprimer',
|
||||
'action.update': 'Mettre à jour', 'action.deploy': 'Déployer', 'action.save': 'Enregistrer', 'action.cancel': 'Annuler',
|
||||
'action.confirm': 'Confirmer',
|
||||
'error.not_found': 'Ressource introuvable', 'error.unauthorized': 'Non autorisé', 'error.forbidden': 'Interdit',
|
||||
'error.rate_limited': 'Trop de requêtes', 'error.internal': 'Erreur interne du serveur',
|
||||
'error.container_not_found': 'Conteneur introuvable', 'error.service_not_found': 'Service introuvable',
|
||||
'error.invalid_input': 'Entrée invalide', 'error.docker_unreachable': 'Le démon Docker est injoignable',
|
||||
'error.disk_full': 'Espace disque critique',
|
||||
},
|
||||
hi: { // 🇮🇳 हिन्दी
|
||||
'dashboard.title': 'डैशबोर्ड', 'dashboard.services': 'सेवाएं', 'dashboard.containers': 'कंटेनर',
|
||||
'dashboard.health': 'स्वास्थ्य', 'dashboard.settings': 'सेटिंग्स', 'dashboard.backups': 'बैकअप',
|
||||
'dashboard.monitoring': 'निगरानी', 'dashboard.security': 'सुरक्षा',
|
||||
'service.status.healthy': 'स्वस्थ', 'service.status.degraded': 'क्षतिग्रस्त', 'service.status.down': 'बंद',
|
||||
'service.status.unknown': 'अज्ञात', 'service.status.pending': 'लंबित',
|
||||
'action.start': 'शुरू करें', 'action.stop': 'रोकें', 'action.restart': 'पुनर्प्रारंभ', 'action.delete': 'हटाएं',
|
||||
'action.update': 'अपडेट', 'action.deploy': 'तैनात', 'action.save': 'सहेजें', 'action.cancel': 'रद्द करें',
|
||||
'action.confirm': 'पुष्टि करें',
|
||||
'error.not_found': 'संसाधन नहीं मिला', 'error.unauthorized': 'अनधिकृत', 'error.forbidden': 'निषिद्ध',
|
||||
'error.rate_limited': 'बहुत अधिक अनुरोध', 'error.internal': 'आंतरिक सर्वर त्रुटि',
|
||||
'error.container_not_found': 'कंटेनर नहीं मिला', 'error.service_not_found': 'सेवा नहीं मिली',
|
||||
'error.invalid_input': 'अमान्य इनपुट', 'error.docker_unreachable': 'Docker डेमन तक नहीं पहुंच सकते',
|
||||
'error.disk_full': 'डिस्क स्थान गंभीर रूप से कम है',
|
||||
},
|
||||
hu: { // 🇭🇺 Magyar
|
||||
'dashboard.title': 'Vezérlőpult', 'dashboard.services': 'Szolgáltatások', 'dashboard.containers': 'Konténerek',
|
||||
'dashboard.health': 'Állapot', 'dashboard.settings': 'Beállítások', 'dashboard.backups': 'Biztonsági mentések',
|
||||
'dashboard.monitoring': 'Figyelés', 'dashboard.security': 'Biztonság',
|
||||
'service.status.healthy': 'Egészséges', 'service.status.degraded': 'Csökkentett', 'service.status.down': 'Leállt',
|
||||
'service.status.unknown': 'Ismeretlen', 'service.status.pending': 'Függőben',
|
||||
'action.start': 'Indítás', 'action.stop': 'Leállítás', 'action.restart': 'Újraindítás', 'action.delete': 'Törlés',
|
||||
'action.update': 'Frissítés', 'action.deploy': 'Telepítés', 'action.save': 'Mentés', 'action.cancel': 'Mégse',
|
||||
'action.confirm': 'Megerősítés',
|
||||
'error.not_found': 'Az erőforrás nem található', 'error.unauthorized': 'Nem engedélyezett', 'error.forbidden': 'Tiltott',
|
||||
'error.rate_limited': 'Túl sok kérés', 'error.internal': 'Belső kiszolgálóhiba',
|
||||
'error.container_not_found': 'A konténer nem található', 'error.service_not_found': 'A szolgáltatás nem található',
|
||||
'error.invalid_input': 'Érvénytelen bemenet', 'error.docker_unreachable': 'A Docker démon nem érhető el',
|
||||
'error.disk_full': 'A lemezterület kritikusan alacsony',
|
||||
},
|
||||
id: { // 🇮🇩 Indonesia
|
||||
'dashboard.title': 'Dasbor', 'dashboard.services': 'Layanan', 'dashboard.containers': 'Kontainer',
|
||||
'dashboard.health': 'Kesehatan', 'dashboard.settings': 'Pengaturan', 'dashboard.backups': 'Pencadangan',
|
||||
'dashboard.monitoring': 'Pemantauan', 'dashboard.security': 'Keamanan',
|
||||
'service.status.healthy': 'Sehat', 'service.status.degraded': 'Terkikis', 'service.status.down': 'Mati',
|
||||
'service.status.unknown': 'Tidak diketahui', 'service.status.pending': 'Tertunda',
|
||||
'action.start': 'Mulai', 'action.stop': 'Berhenti', 'action.restart': 'Mulai ulang', 'action.delete': 'Hapus',
|
||||
'action.update': 'Perbarui', 'action.deploy': 'Sebarkan', 'action.save': 'Simpan', 'action.cancel': 'Batal',
|
||||
'action.confirm': 'Konfirmasi',
|
||||
'error.not_found': 'Sumber daya tidak ditemukan', 'error.unauthorized': 'Tidak berwenang', 'error.forbidden': 'Dilarang',
|
||||
'error.rate_limited': 'Terlalu banyak permintaan', 'error.internal': 'Kesalahan server internal',
|
||||
'error.container_not_found': 'Kontainer tidak ditemukan', 'error.service_not_found': 'Layanan tidak ditemukan',
|
||||
'error.invalid_input': 'Input tidak valid', 'error.docker_unreachable': 'Daemon Docker tidak dapat dijangkau',
|
||||
'error.disk_full': 'Ruang disk sangat rendah',
|
||||
},
|
||||
it: { // 🇮🇹 Italiano
|
||||
'dashboard.title': 'Cruscotto', 'dashboard.services': 'Servizi', 'dashboard.containers': 'Contenitori',
|
||||
'dashboard.health': 'Salute', 'dashboard.settings': 'Impostazioni', 'dashboard.backups': 'Backup',
|
||||
'dashboard.monitoring': 'Monitoraggio', 'dashboard.security': 'Sicurezza',
|
||||
'service.status.healthy': 'Salutare', 'service.status.degraded': 'Danneggiato', 'service.status.down': 'Inattivo',
|
||||
'service.status.unknown': 'Sconosciuto', 'service.status.pending': 'In attesa',
|
||||
'action.start': 'Avvia', 'action.stop': 'Ferma', 'action.restart': 'Riavvia', 'action.delete': 'Elimina',
|
||||
'action.update': 'Aggiorna', 'action.deploy': 'Distribuisci', 'action.save': 'Salva', 'action.cancel': 'Annulla',
|
||||
'action.confirm': 'Conferma',
|
||||
'error.not_found': 'Risorsa non trovata', 'error.unauthorized': 'Non autorizzato', 'error.forbidden': 'Vietato',
|
||||
'error.rate_limited': 'Troppe richieste', 'error.internal': 'Errore interno del server',
|
||||
'error.container_not_found': 'Contenitore non trovato', 'error.service_not_found': 'Servizio non trovato',
|
||||
'error.invalid_input': 'Input non valido', 'error.docker_unreachable': 'Il daemon Docker non è raggiungibile',
|
||||
'error.disk_full': 'Spazio su disco criticamente basso',
|
||||
},
|
||||
ja: { // 🇯🇵 日本語
|
||||
'dashboard.title': 'ダッシュボード', 'dashboard.services': 'サービス', 'dashboard.containers': 'コンテナ',
|
||||
'dashboard.health': 'ヘルス', 'dashboard.settings': '設定', 'dashboard.backups': 'バックアップ',
|
||||
'dashboard.monitoring': '監視', 'dashboard.security': 'セキュリティ',
|
||||
'service.status.healthy': '正常', 'service.status.degraded': '低下', 'service.status.down': '停止',
|
||||
'service.status.unknown': '不明', 'service.status.pending': '保留中',
|
||||
'action.start': '開始', 'action.stop': '停止', 'action.restart': '再起動', 'action.delete': '削除',
|
||||
'action.update': '更新', 'action.deploy': 'デプロイ', 'action.save': '保存', 'action.cancel': 'キャンセル',
|
||||
'action.confirm': '確認',
|
||||
'error.not_found': 'リソースが見つかりません', 'error.unauthorized': '認証されていません', 'error.forbidden': '禁止されています',
|
||||
'error.rate_limited': 'リクエストが多すぎます', 'error.internal': '内部サーバーエラー',
|
||||
'error.container_not_found': 'コンテナが見つかりません', 'error.service_not_found': 'サービスが見つかりません',
|
||||
'error.invalid_input': '無効な入力', 'error.docker_unreachable': 'Dockerデーモンに接続できません',
|
||||
'error.disk_full': 'ディスク容量が致命的に不足しています',
|
||||
},
|
||||
ko: { // 🇰🇷 한국어
|
||||
'dashboard.title': '대시보드', 'dashboard.services': '서비스', 'dashboard.containers': '컨테이너',
|
||||
'dashboard.health': '상태', 'dashboard.settings': '설정', 'dashboard.backups': '백업',
|
||||
'dashboard.monitoring': '모니터링', 'dashboard.security': '보안',
|
||||
'service.status.healthy': '정상', 'service.status.degraded': '성능 저하', 'service.status.down': '중단',
|
||||
'service.status.unknown': '알 수 없음', 'service.status.pending': '대기 중',
|
||||
'action.start': '시작', 'action.stop': '중지', 'action.restart': '재시작', 'action.delete': '삭제',
|
||||
'action.update': '업데이트', 'action.deploy': '배포', 'action.save': '저장', 'action.cancel': '취소',
|
||||
'action.confirm': '확인',
|
||||
'error.not_found': '리소스를 찾을 수 없습니다', 'error.unauthorized': '인증되지 않음', 'error.forbidden': '금지됨',
|
||||
'error.rate_limited': '요청이 너무 많습니다', 'error.internal': '내부 서버 오류',
|
||||
'error.container_not_found': '컨테이너를 찾을 수 없습니다', 'error.service_not_found': '서비스를 찾을 수 없습니다',
|
||||
'error.invalid_input': '잘못된 입력', 'error.docker_unreachable': 'Docker 데몬에 연결할 수 없습니다',
|
||||
'error.disk_full': '디스크 공간이 심각하게 부족합니다',
|
||||
},
|
||||
ms: { // 🇲🇾 Melayu
|
||||
'dashboard.title': 'Papan pemuka', 'dashboard.services': 'Perkhidmatan', 'dashboard.containers': 'Bekas',
|
||||
'dashboard.health': 'Kesihatan', 'dashboard.settings': 'Tetapan', 'dashboard.backups': 'Sandaran',
|
||||
'dashboard.monitoring': 'Pemantauan', 'dashboard.security': 'Keselamatan',
|
||||
'service.status.healthy': 'Sihat', 'service.status.degraded': 'Merosot', 'service.status.down': 'Tergendala',
|
||||
'service.status.unknown': 'Tidak diketahui', 'service.status.pending': 'Belum selesai',
|
||||
'action.start': 'Mula', 'action.stop': 'Berhenti', 'action.restart': 'Mulakan semula', 'action.delete': 'Padam',
|
||||
'action.update': 'Kemas kini', 'action.deploy': 'Lancarkan', 'action.save': 'Simpan', 'action.cancel': 'Batal',
|
||||
'action.confirm': 'Sahkan',
|
||||
'error.not_found': 'Sumber tidak dijumpai', 'error.unauthorized': 'Tidak dibenarkan', 'error.forbidden': 'Dilarang',
|
||||
'error.rate_limited': 'Terlalu banyak permintaan', 'error.internal': 'Ralat pelayan dalaman',
|
||||
'error.container_not_found': 'Bekas tidak dijumpai', 'error.service_not_found': 'Perkhidmatan tidak dijumpai',
|
||||
'error.invalid_input': 'Input tidak sah', 'error.docker_unreachable': 'Docker daemon tidak dapat dijangkau',
|
||||
'error.disk_full': 'Ruang cakera sangat kritikal',
|
||||
},
|
||||
nl: { // 🇳🇱 Nederlands
|
||||
'dashboard.title': 'Dashboard', 'dashboard.services': 'Diensten', 'dashboard.containers': 'Containers',
|
||||
'dashboard.health': 'Status', 'dashboard.settings': 'Instellingen', 'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Bewaking', 'dashboard.security': 'Beveiliging',
|
||||
'service.status.healthy': 'Gezond', 'service.status.degraded': 'Achteruitgegaan', 'service.status.down': 'Offline',
|
||||
'service.status.unknown': 'Onbekend', 'service.status.pending': 'In afwachting',
|
||||
'action.start': 'Starten', 'action.stop': 'Stoppen', 'action.restart': 'Herstarten', 'action.delete': 'Verwijderen',
|
||||
'action.update': 'Bijwerken', 'action.deploy': 'Uitrollen', 'action.save': 'Opslaan', 'action.cancel': 'Annuleren',
|
||||
'action.confirm': 'Bevestigen',
|
||||
'error.not_found': 'Bron niet gevonden', 'error.unauthorized': 'Niet geautoriseerd', 'error.forbidden': 'Verboden',
|
||||
'error.rate_limited': 'Te veel verzoeken', 'error.internal': 'Interne serverfout',
|
||||
'error.container_not_found': 'Container niet gevonden', 'error.service_not_found': 'Dienst niet gevonden',
|
||||
'error.invalid_input': 'Ongeldige invoer', 'error.docker_unreachable': 'Docker-daemon is niet bereikbaar',
|
||||
'error.disk_full': 'Schijfruimte kritiek laag',
|
||||
},
|
||||
no: { // 🇳🇴 Norsk
|
||||
'dashboard.title': 'Kontrollpanel', 'dashboard.services': 'Tjenester', 'dashboard.containers': 'Beholdere',
|
||||
'dashboard.health': 'Helse', 'dashboard.settings': 'Innstillinger', 'dashboard.backups': 'Sikkerhetskopier',
|
||||
'dashboard.monitoring': 'Overvåking', 'dashboard.security': 'Sikkerhet',
|
||||
'service.status.healthy': 'Sunn', 'service.status.degraded': 'Forringet', 'service.status.down': 'Nede',
|
||||
'service.status.unknown': 'Ukjent', 'service.status.pending': 'Venter',
|
||||
'action.start': 'Start', 'action.stop': 'Stopp', 'action.restart': 'Omstart', 'action.delete': 'Slett',
|
||||
'action.update': 'Oppdater', 'action.deploy': 'Rull ut', 'action.save': 'Lagre', 'action.cancel': 'Avbryt',
|
||||
'action.confirm': 'Bekreft',
|
||||
'error.not_found': 'Ressurs ikke funnet', 'error.unauthorized': 'Ikke autorisert', 'error.forbidden': 'Forbudt',
|
||||
'error.rate_limited': 'For mange forespørsler', 'error.internal': 'Intern serverfeil',
|
||||
'error.container_not_found': 'Beholder ikke funnet', 'error.service_not_found': 'Tjeneste ikke funnet',
|
||||
'error.invalid_input': 'Ugyldig inndata', 'error.docker_unreachable': 'Docker-daemon er ikke tilgjengelig',
|
||||
'error.disk_full': 'Diskplassen er kritisk lav',
|
||||
},
|
||||
pl: { // 🇵🇱 Polski
|
||||
'dashboard.title': 'Panel', 'dashboard.services': 'Usługi', 'dashboard.containers': 'Kontenery',
|
||||
'dashboard.health': 'Zdrowie', 'dashboard.settings': 'Ustawienia', 'dashboard.backups': 'Kopie zapasowe',
|
||||
'dashboard.monitoring': 'Monitorowanie', 'dashboard.security': 'Bezpieczeństwo',
|
||||
'service.status.healthy': 'Zdrowy', 'service.status.degraded': 'Naruszony', 'service.status.down': 'Nie działa',
|
||||
'service.status.unknown': 'Nieznany', 'service.status.pending': 'Oczekuje',
|
||||
'action.start': 'Uruchom', 'action.stop': 'Zatrzymaj', 'action.restart': 'Uruchom ponownie', 'action.delete': 'Usuń',
|
||||
'action.update': 'Aktualizuj', 'action.deploy': 'Wdróż', 'action.save': 'Zapisz', 'action.cancel': 'Anuluj',
|
||||
'action.confirm': 'Potwierdź',
|
||||
'error.not_found': 'Nie znaleziono zasobu', 'error.unauthorized': 'Brak autoryzacji', 'error.forbidden': 'Zabronione',
|
||||
'error.rate_limited': 'Zbyt wiele żądań', 'error.internal': 'Wewnętrzny błąd serwera',
|
||||
'error.container_not_found': 'Nie znaleziono kontenera', 'error.service_not_found': 'Nie znaleziono usługi',
|
||||
'error.invalid_input': 'Nieprawidłowe dane wejściowe', 'error.docker_unreachable': 'Daemon Docker jest niedostępny',
|
||||
'error.disk_full': 'Krytycznie mało miejsca na dysku',
|
||||
},
|
||||
pt: { // 🇵🇹 Português
|
||||
'dashboard.title': 'Painel', 'dashboard.services': 'Serviços', 'dashboard.containers': 'Contêineres',
|
||||
'dashboard.health': 'Saúde', 'dashboard.settings': 'Configurações', 'dashboard.backups': 'Backups',
|
||||
'dashboard.monitoring': 'Monitoramento', 'dashboard.security': 'Segurança',
|
||||
'service.status.healthy': 'Saudável', 'service.status.degraded': 'Degradado', 'service.status.down': 'Inativo',
|
||||
'service.status.unknown': 'Desconhecido', 'service.status.pending': 'Pendente',
|
||||
'action.start': 'Iniciar', 'action.stop': 'Parar', 'action.restart': 'Reiniciar', 'action.delete': 'Excluir',
|
||||
'action.update': 'Atualizar', 'action.deploy': 'Implantar', 'action.save': 'Salvar', 'action.cancel': 'Cancelar',
|
||||
'action.confirm': 'Confirmar',
|
||||
'error.not_found': 'Recurso não encontrado', 'error.unauthorized': 'Não autorizado', 'error.forbidden': 'Proibido',
|
||||
'error.rate_limited': 'Muitas solicitações', 'error.internal': 'Erro interno do servidor',
|
||||
'error.container_not_found': 'Contêiner não encontrado', 'error.service_not_found': 'Serviço não encontrado',
|
||||
'error.invalid_input': 'Entrada inválida', 'error.docker_unreachable': 'Daemon do Docker inacessível',
|
||||
'error.disk_full': 'Espaço em disco criticamente baixo',
|
||||
},
|
||||
ro: { // 🇷🇴 Română
|
||||
'dashboard.title': 'Tablou de bord', 'dashboard.services': 'Servicii', 'dashboard.containers': 'Containere',
|
||||
'dashboard.health': 'Stare', 'dashboard.settings': 'Setări', 'dashboard.backups': 'Copii de rezervă',
|
||||
'dashboard.monitoring': 'Monitorizare', 'dashboard.security': 'Securitate',
|
||||
'service.status.healthy': 'Sănătos', 'service.status.degraded': 'Degradat', 'service.status.down': 'Oprit',
|
||||
'service.status.unknown': 'Necunoscut', 'service.status.pending': 'În așteptare',
|
||||
'action.start': 'Pornește', 'action.stop': 'Oprește', 'action.restart': 'Repornește', 'action.delete': 'Șterge',
|
||||
'action.update': 'Actualizează', 'action.deploy': 'Lansează', 'action.save': 'Salvează', 'action.cancel': 'Anulează',
|
||||
'action.confirm': 'Confirmă',
|
||||
'error.not_found': 'Resursă negăsită', 'error.unauthorized': 'Neautorizat', 'error.forbidden': 'Interzis',
|
||||
'error.rate_limited': 'Prea multe cereri', 'error.internal': 'Eroare internă a serverului',
|
||||
'error.container_not_found': 'Container negăsit', 'error.service_not_found': 'Serviciu negăsit',
|
||||
'error.invalid_input': 'Intrare invalidă', 'error.docker_unreachable': 'Daemonul Docker nu poate fi contactat',
|
||||
'error.disk_full': 'Spațiul pe disc este critic de scăzut',
|
||||
},
|
||||
ru: { // 🇷🇺 Русский
|
||||
'dashboard.title': 'Панель управления', 'dashboard.services': 'Сервисы', 'dashboard.containers': 'Контейнеры',
|
||||
'dashboard.health': 'Здоровье', 'dashboard.settings': 'Настройки', 'dashboard.backups': 'Резервные копии',
|
||||
'dashboard.monitoring': 'Мониторинг', 'dashboard.security': 'Безопасность',
|
||||
'service.status.healthy': 'Здоров', 'service.status.degraded': 'Деградирован', 'service.status.down': 'Не работает',
|
||||
'service.status.unknown': 'Неизвестно', 'service.status.pending': 'Ожидание',
|
||||
'action.start': 'Запустить', 'action.stop': 'Остановить', 'action.restart': 'Перезапустить', 'action.delete': 'Удалить',
|
||||
'action.update': 'Обновить', 'action.deploy': 'Развернуть', 'action.save': 'Сохранить', 'action.cancel': 'Отмена',
|
||||
'action.confirm': 'Подтвердить',
|
||||
'error.not_found': 'Ресурс не найден', 'error.unauthorized': 'Не авторизован', 'error.forbidden': 'Запрещено',
|
||||
'error.rate_limited': 'Слишком много запросов', 'error.internal': 'Внутренняя ошибка сервера',
|
||||
'error.container_not_found': 'Контейнер не найден', 'error.service_not_found': 'Сервис не найден',
|
||||
'error.invalid_input': 'Неверный ввод', 'error.docker_unreachable': 'Docker недоступен',
|
||||
'error.disk_full': 'Критически мало места на диске',
|
||||
},
|
||||
sv: { // 🇸🇪 Svenska
|
||||
'dashboard.title': 'Instrumentpanel', 'dashboard.services': 'Tjänster', 'dashboard.containers': 'Behållare',
|
||||
'dashboard.health': 'Hälsa', 'dashboard.settings': 'Inställningar', 'dashboard.backups': 'Säkerhetskopior',
|
||||
'dashboard.monitoring': 'Övervakning', 'dashboard.security': 'Säkerhet',
|
||||
'service.status.healthy': 'Frisk', 'service.status.degraded': 'Nedsatt', 'service.status.down': 'Nere',
|
||||
'service.status.unknown': 'Okänd', 'service.status.pending': 'Väntar',
|
||||
'action.start': 'Starta', 'action.stop': 'Stoppa', 'action.restart': 'Starta om', 'action.delete': 'Ta bort',
|
||||
'action.update': 'Uppdatera', 'action.deploy': 'Distribuera', 'action.save': 'Spara', 'action.cancel': 'Avbryt',
|
||||
'action.confirm': 'Bekräfta',
|
||||
'error.not_found': 'Resurs hittades inte', 'error.unauthorized': 'Obehörig', 'error.forbidden': 'Förbjuden',
|
||||
'error.rate_limited': 'För många förfrågningar', 'error.internal': 'Internt serverfel',
|
||||
'error.container_not_found': 'Behållare hittades inte', 'error.service_not_found': 'Tjänst hittades inte',
|
||||
'error.invalid_input': 'Ogiltig inmatning', 'error.docker_unreachable': 'Docker-daemon kan inte nås',
|
||||
'error.disk_full': 'Diskutrymmet är kritiskt lågt',
|
||||
},
|
||||
th: { // 🇹🇭 ไทย
|
||||
'dashboard.title': 'แดชบอร์ด', 'dashboard.services': 'บริการ', 'dashboard.containers': 'คอนเทนเนอร์',
|
||||
'dashboard.health': 'สถานะ', 'dashboard.settings': 'การตั้งค่า', 'dashboard.backups': 'การสำรองข้อมูล',
|
||||
'dashboard.monitoring': 'การตรวจสอบ', 'dashboard.security': 'ความปลอดภัย',
|
||||
'service.status.healthy': 'ปกติ', 'service.status.degraded': 'เสื่อม', 'service.status.down': 'ล่ม',
|
||||
'service.status.unknown': 'ไม่ทราบ', 'service.status.pending': 'รอดำเนินการ',
|
||||
'action.start': 'เริ่ม', 'action.stop': 'หยุด', 'action.restart': 'รีสตาร์ท', 'action.delete': 'ลบ',
|
||||
'action.update': 'อัปเดต', 'action.deploy': 'ปรับใช้', 'action.save': 'บันทึก', 'action.cancel': 'ยกเลิก',
|
||||
'action.confirm': 'ยืนยัน',
|
||||
'error.not_found': 'ไม่พบทรัพยากร', 'error.unauthorized': 'ไม่ได้รับอนุญาต', 'error.forbidden': 'ห้าม',
|
||||
'error.rate_limited': 'คำขอมากเกินไป', 'error.internal': 'ข้อผิดพลาดภายในเซิร์ฟเวอร์',
|
||||
'error.container_not_found': 'ไม่พบคอนเทนเนอร์', 'error.service_not_found': 'ไม่พบบริการ',
|
||||
'error.invalid_input': 'อินพุตไม่ถูกต้อง', 'error.docker_unreachable': 'ไม่สามารถเข้าถึง Docker daemon ได้',
|
||||
'error.disk_full': 'พื้นที่ดิสก์เหลือน้อยวิกฤต',
|
||||
},
|
||||
tr: { // 🇹🇷 Türkçe
|
||||
'dashboard.title': 'Kontrol Paneli', 'dashboard.services': 'Hizmetler', 'dashboard.containers': 'Konteynerler',
|
||||
'dashboard.health': 'Sağlık', 'dashboard.settings': 'Ayarlar', 'dashboard.backups': 'Yedekler',
|
||||
'dashboard.monitoring': 'İzleme', 'dashboard.security': 'Güvenlik',
|
||||
'service.status.healthy': 'Sağlıklı', 'service.status.degraded': 'Bozulmuş', 'service.status.down': 'Çalışmıyor',
|
||||
'service.status.unknown': 'Bilinmiyor', 'service.status.pending': 'Beklemede',
|
||||
'action.start': 'Başlat', 'action.stop': 'Durdur', 'action.restart': 'Yeniden Başlat', 'action.delete': 'Sil',
|
||||
'action.update': 'Güncelle', 'action.deploy': 'Dağıt', 'action.save': 'Kaydet', 'action.cancel': 'İptal',
|
||||
'action.confirm': 'Onayla',
|
||||
'error.not_found': 'Kaynak bulunamadı', 'error.unauthorized': 'Yetkisiz', 'error.forbidden': 'Yasak',
|
||||
'error.rate_limited': 'Çok fazla istek', 'error.internal': 'Dahili sunucu hatası',
|
||||
'error.container_not_found': 'Konteyner bulunamadı', 'error.service_not_found': 'Hizmet bulunamadı',
|
||||
'error.invalid_input': 'Geçersiz giriş', 'error.docker_unreachable': 'Docker daemonuna ulaşılamıyor',
|
||||
'error.disk_full': 'Disk alanı kritik düzeyde düşük',
|
||||
},
|
||||
uk: { // 🇺🇦 Українська
|
||||
'dashboard.title': 'Панель керування', 'dashboard.services': 'Сервіси', 'dashboard.containers': 'Контейнери',
|
||||
'dashboard.health': "Здоров'я", 'dashboard.settings': 'Налаштування', 'dashboard.backups': 'Резервні копії',
|
||||
'dashboard.monitoring': 'Моніторинг', 'dashboard.security': 'Безпека',
|
||||
'service.status.healthy': 'Здоровий', 'service.status.degraded': 'Деградований', 'service.status.down': 'Не працює',
|
||||
'service.status.unknown': 'Невідомо', 'service.status.pending': 'Очікування',
|
||||
'action.start': 'Запустити', 'action.stop': 'Зупинити', 'action.restart': 'Перезапустити', 'action.delete': 'Видалити',
|
||||
'action.update': 'Оновити', 'action.deploy': 'Розгорнути', 'action.save': 'Зберегти', 'action.cancel': 'Скасувати',
|
||||
'action.confirm': 'Підтвердити',
|
||||
'error.not_found': 'Ресурс не знайдено', 'error.unauthorized': 'Не авторизовано', 'error.forbidden': 'Заборонено',
|
||||
'error.rate_limited': 'Занадто багато запитів', 'error.internal': 'Внутрішня помилка сервера',
|
||||
'error.container_not_found': 'Контейнер не знайдено', 'error.service_not_found': 'Сервіс не знайдено',
|
||||
'error.invalid_input': 'Невірне введення', 'error.docker_unreachable': 'Docker недоступний',
|
||||
'error.disk_full': 'Критично мало місця на диску',
|
||||
},
|
||||
ur: { // 🇵🇰 اردو
|
||||
'dashboard.title': 'ڈیش بورڈ', 'dashboard.services': 'خدمات', 'dashboard.containers': 'کنٹینرز',
|
||||
'dashboard.health': 'صحت', 'dashboard.settings': 'ترتیبات', 'dashboard.backups': 'بیک اپ',
|
||||
'dashboard.monitoring': 'نگرانی', 'dashboard.security': 'تحفظ',
|
||||
'service.status.healthy': 'صحت مند', 'service.status.degraded': 'خراب', 'service.status.down': 'بند',
|
||||
'service.status.unknown': 'نامعلوم', 'service.status.pending': 'زیر التواء',
|
||||
'action.start': 'شروع', 'action.stop': 'روک', 'action.restart': 'دوبارہ شروع', 'action.delete': 'حذف',
|
||||
'action.update': 'اپڈیٹ', 'action.deploy': 'تعینات', 'action.save': 'محفوظ', 'action.cancel': 'منسوخ',
|
||||
'action.confirm': 'تصدیق',
|
||||
'error.not_found': 'وسائل نہیں ملے', 'error.unauthorized': 'غیر مجاز', 'error.forbidden': 'ممنوع',
|
||||
'error.rate_limited': 'بہت زیادہ درخواستیں', 'error.internal': 'اندرونی سرور نقص',
|
||||
'error.container_not_found': 'کنٹینر نہیں ملا', 'error.service_not_found': 'سروس نہیں ملی',
|
||||
'error.invalid_input': 'غلط ان پٹ', 'error.docker_unreachable': 'Docker ڈیمن تک رسائی نہیں',
|
||||
'error.disk_full': 'ڈسک کی جگہ نہایت کم ہے',
|
||||
},
|
||||
vi: { // 🇻🇳 Tiếng Việt
|
||||
'dashboard.title': 'Bảng điều khiển', 'dashboard.services': 'Dịch vụ', 'dashboard.containers': 'Bộ chứa',
|
||||
'dashboard.health': 'Tình trạng', 'dashboard.settings': 'Cài đặt', 'dashboard.backups': 'Sao lưu',
|
||||
'dashboard.monitoring': 'Giám sát', 'dashboard.security': 'Bảo mật',
|
||||
'service.status.healthy': 'Khỏe mạnh', 'service.status.degraded': 'Giảm', 'service.status.down': 'Ngừng',
|
||||
'service.status.unknown': 'Không xác định', 'service.status.pending': 'Đang chờ',
|
||||
'action.start': 'Bắt đầu', 'action.stop': 'Dừng', 'action.restart': 'Khởi động lại', 'action.delete': 'Xóa',
|
||||
'action.update': 'Cập nhật', 'action.deploy': 'Triển khai', 'action.save': 'Lưu', 'action.cancel': 'Hủy',
|
||||
'action.confirm': 'Xác nhận',
|
||||
'error.not_found': 'Không tìm thấy tài nguyên', 'error.unauthorized': 'Không được phép', 'error.forbidden': 'Bị cấm',
|
||||
'error.rate_limited': 'Quá nhiều yêu cầu', 'error.internal': 'Lỗi máy chủ nội bộ',
|
||||
'error.container_not_found': 'Không tìm thấy bộ chứa', 'error.service_not_found': 'Không tìm thấy dịch vụ',
|
||||
'error.invalid_input': 'Đầu vào không hợp lệ', 'error.docker_unreachable': 'Không thể kết nối với Docker daemon',
|
||||
'error.disk_full': 'Không gian đĩa cực kỳ thấp',
|
||||
},
|
||||
zh: { // 🇨🇳 中文
|
||||
'dashboard.title': '仪表盘', 'dashboard.services': '服务', 'dashboard.containers': '容器',
|
||||
'dashboard.health': '健康', 'dashboard.settings': '设置', 'dashboard.backups': '备份',
|
||||
'dashboard.monitoring': '监控', 'dashboard.security': '安全',
|
||||
'service.status.healthy': '健康', 'service.status.degraded': '降级', 'service.status.down': '宕机',
|
||||
'service.status.unknown': '未知', 'service.status.pending': '待处理',
|
||||
'action.start': '启动', 'action.stop': '停止', 'action.restart': '重启', 'action.delete': '删除',
|
||||
'action.update': '更新', 'action.deploy': '部署', 'action.save': '保存', 'action.cancel': '取消',
|
||||
'action.confirm': '确认',
|
||||
'error.not_found': '未找到资源', 'error.unauthorized': '未授权', 'error.forbidden': '禁止访问',
|
||||
'error.rate_limited': '请求过多', 'error.internal': '内部服务器错误',
|
||||
'error.container_not_found': '未找到容器', 'error.service_not_found': '未找到服务',
|
||||
'error.invalid_input': '输入无效', 'error.docker_unreachable': '无法连接 Docker 守护进程',
|
||||
'error.disk_full': '磁盘空间严重不足',
|
||||
},
|
||||
};
|
||||
|
||||
const SUPPORTED_LANGUAGES = Object.keys(TRANSLATIONS);
|
||||
const DEFAULT_LANGUAGE = 'en';
|
||||
|
||||
/**
|
||||
* Translate a key to the specified language.
|
||||
* Falls back to English, then to the key itself if not found.
|
||||
*/
|
||||
function t(key, lang = DEFAULT_LANGUAGE) {
|
||||
const dict = TRANSLATIONS[lang] || TRANSLATIONS[DEFAULT_LANGUAGE];
|
||||
// Language metadata for UI dropdowns
|
||||
const LANGUAGE_META = {
|
||||
en: { name: 'English', flag: '🇬🇧', rtl: false },
|
||||
ar: { name: 'العربية', flag: '🇸🇦', rtl: true },
|
||||
bn: { name: 'বাংলা', flag: '🇧🇩', rtl: false },
|
||||
cs: { name: 'Čeština', flag: '🇨🇿', rtl: false },
|
||||
da: { name: 'Dansk', flag: '🇩🇰', rtl: false },
|
||||
de: { name: 'Deutsch', flag: '🇩🇪', rtl: false },
|
||||
el: { name: 'Ελληνικά', flag: '🇬🇷', rtl: false },
|
||||
es: { name: 'Español', flag: '🇪🇸', rtl: false },
|
||||
fa: { name: 'فارسی', flag: '🇮🇷', rtl: true },
|
||||
fi: { name: 'Suomi', flag: '🇫🇮', rtl: false },
|
||||
fr: { name: 'Français', flag: '🇫🇷', rtl: false },
|
||||
hi: { name: 'हिन्दी', flag: '🇮🇳', rtl: false },
|
||||
hu: { name: 'Magyar', flag: '🇭🇺', rtl: false },
|
||||
id: { name: 'Indonesia', flag: '🇮🇩', rtl: false },
|
||||
it: { name: 'Italiano', flag: '🇮🇹', rtl: false },
|
||||
ja: { name: '日本語', flag: '🇯🇵', rtl: false },
|
||||
ko: { name: '한국어', flag: '🇰🇷', rtl: false },
|
||||
ms: { name: 'Melayu', flag: '🇲🇾', rtl: false },
|
||||
nl: { name: 'Nederlands', flag: '🇳🇱', rtl: false },
|
||||
no: { name: 'Norsk', flag: '🇳🇴', rtl: false },
|
||||
pl: { name: 'Polski', flag: '🇵🇱', rtl: false },
|
||||
pt: { name: 'Português', flag: '🇵🇹', rtl: false },
|
||||
ro: { name: 'Română', flag: '🇷🇴', rtl: false },
|
||||
ru: { name: 'Русский', flag: '🇷🇺', rtl: false },
|
||||
sv: { name: 'Svenska', flag: '🇸🇪', rtl: false },
|
||||
th: { name: 'ไทย', flag: '🇹🇭', rtl: false },
|
||||
tr: { name: 'Türkçe', flag: '🇹🇷', rtl: false },
|
||||
uk: { name: 'Українська', flag: '🇺🇦', rtl: false },
|
||||
ur: { name: 'اردو', flag: '🇵🇰', rtl: true },
|
||||
vi: { name: 'Tiếng Việt', flag: '🇻🇳', rtl: false },
|
||||
zh: { name: '中文', flag: '🇨🇳', rtl: false },
|
||||
};
|
||||
|
||||
function t(key, lang) {
|
||||
lang = lang || DEFAULT_LANGUAGE;
|
||||
var dict = TRANSLATIONS[lang] || TRANSLATIONS[DEFAULT_LANGUAGE];
|
||||
return dict[key] || TRANSLATIONS[DEFAULT_LANGUAGE][key] || key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of supported languages
|
||||
*/
|
||||
function getSupportedLanguages() {
|
||||
return SUPPORTED_LANGUAGES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a language is supported
|
||||
*/
|
||||
function isSupported(lang) {
|
||||
return SUPPORTED_LANGUAGES.includes(lang);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect language from Accept-Language header
|
||||
*/
|
||||
function getSupportedLanguages() { return SUPPORTED_LANGUAGES; }
|
||||
function getLanguageMeta(lang) { return LANGUAGE_META[lang] || LANGUAGE_META[DEFAULT_LANGUAGE]; }
|
||||
function getAllLanguages() { return LANGUAGE_META; }
|
||||
function isRTL(lang) { return lang === 'ar' || lang === 'fa' || lang === 'ur'; }
|
||||
function isSupported(lang) { return SUPPORTED_LANGUAGES.indexOf(lang) >= 0; }
|
||||
function detectLanguage(acceptLanguage) {
|
||||
if (!acceptLanguage) return DEFAULT_LANGUAGE;
|
||||
const langs = acceptLanguage.split(',').map(l => {
|
||||
const [code, q] = l.trim().split(';q=');
|
||||
return { code: code.split('-')[0].toLowerCase(), q: q ? parseFloat(q) : 1 };
|
||||
}).sort((a, b) => b.q - a.q);
|
||||
|
||||
for (const { code } of langs) {
|
||||
var parts = acceptLanguage.split(',');
|
||||
for (var i = 0; i < parts.length; i++) {
|
||||
var code = parts[i].trim().split(';')[0].split('-')[0].toLowerCase();
|
||||
if (isSupported(code)) return code;
|
||||
}
|
||||
return DEFAULT_LANGUAGE;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
t,
|
||||
getSupportedLanguages,
|
||||
isSupported,
|
||||
detectLanguage,
|
||||
DEFAULT_LANGUAGE,
|
||||
TRANSLATIONS,
|
||||
t, getSupportedLanguages, getLanguageMeta, getAllLanguages,
|
||||
isRTL, isSupported, detectLanguage, DEFAULT_LANGUAGE,
|
||||
TRANSLATIONS, LANGUAGE_META,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Recursive data nesting guard.
|
||||
*
|
||||
* In past versions, a buggy update/restore path created data/data/data/...
|
||||
* directories — each containing a full recursive copy of the parent.
|
||||
* This module runs at startup, detects and removes nested duplicates.
|
||||
*
|
||||
* Add to app.js: require('./utilities/nesting-guard')();
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const log = require('./logging');
|
||||
|
||||
module.exports = function nestingGuard() {
|
||||
try {
|
||||
const dataDir = require('../config/paths').dataDir;
|
||||
const dataDataPath = path.join(dataDir, 'data');
|
||||
|
||||
// If data/data exists, it's a recursive duplicate — remove it
|
||||
if (fs.existsSync(dataDataPath)) {
|
||||
const stat = fs.statSync(dataDataPath);
|
||||
if (stat.isDirectory()) {
|
||||
// Verify it's truly a duplicate (contains config.json like the parent)
|
||||
const markerFile = path.join(dataDataPath, 'config.json');
|
||||
const parentMarker = path.join(dataDir, 'config.json');
|
||||
if (fs.existsSync(markerFile) && fs.existsSync(parentMarker)) {
|
||||
const size = require('child_process')
|
||||
.execSync(`du -sh '${dataDataPath}' 2>/dev/null | cut -f1`)
|
||||
.toString().trim();
|
||||
log.warn('startup', `Removing recursive data nesting: ${dataDataPath} (${size})`);
|
||||
fs.rmSync(dataDataPath, { recursive: true, force: true });
|
||||
log.info('startup', 'Recursive nesting removed');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Non-fatal — don't crash startup over cleanup
|
||||
log.warn('startup', `Nesting guard skipped: ${e.message}`);
|
||||
}
|
||||
};
|
||||
Generated
+98
-7
@@ -8,6 +8,9 @@
|
||||
"name": "dashcaddy-installer",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"electron-updater": "^6.8.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "^28.3.3",
|
||||
"electron-builder": "^24.9.1",
|
||||
@@ -1999,7 +2002,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/assert-plus": {
|
||||
@@ -2895,7 +2897,6 @@
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
@@ -3422,6 +3423,82 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/electron-updater": {
|
||||
"version": "6.8.9",
|
||||
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",
|
||||
"integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"builder-util-runtime": "9.7.0",
|
||||
"fs-extra": "^10.1.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lazy-val": "^1.0.5",
|
||||
"lodash.escaperegexp": "^4.1.2",
|
||||
"lodash.isequal": "^4.5.0",
|
||||
"semver": "~7.7.3",
|
||||
"tiny-typed-emitter": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater/node_modules/builder-util-runtime": {
|
||||
"version": "9.7.0",
|
||||
"resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
|
||||
"integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.3.4",
|
||||
"sax": "^1.2.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater/node_modules/fs-extra": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
|
||||
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.0",
|
||||
"jsonfile": "^6.0.1",
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater/node_modules/jsonfile": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
|
||||
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater/node_modules/semver": {
|
||||
"version": "7.7.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-updater/node_modules/universalify": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/emittery": {
|
||||
"version": "0.13.1",
|
||||
"resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz",
|
||||
@@ -4109,7 +4186,6 @@
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
@@ -5202,7 +5278,6 @@
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
@@ -5300,7 +5375,6 @@
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",
|
||||
"integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lazystream": {
|
||||
@@ -5406,6 +5480,12 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash.escaperegexp": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
|
||||
"integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.flatten": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
|
||||
@@ -5414,6 +5494,13 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash.isequal": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
|
||||
"integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
|
||||
"deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
@@ -5670,7 +5757,6 @@
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/natural-compare": {
|
||||
@@ -6325,7 +6411,6 @@
|
||||
"version": "1.4.4",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
|
||||
"integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=11.0.0"
|
||||
@@ -6823,6 +6908,12 @@
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-typed-emitter": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz",
|
||||
"integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tmp": {
|
||||
"version": "0.2.5",
|
||||
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz",
|
||||
|
||||
@@ -47,12 +47,24 @@
|
||||
{
|
||||
"from": "../status",
|
||||
"to": "status",
|
||||
"filter": ["**/*", "!node_modules/**", "!.git/**", "!**/*.test.js", "!**/*.spec.js"]
|
||||
"filter": [
|
||||
"**/*",
|
||||
"!node_modules/**",
|
||||
"!.git/**",
|
||||
"!**/*.test.js",
|
||||
"!**/*.spec.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "../dashcaddy-api",
|
||||
"to": "dashcaddy-api",
|
||||
"filter": ["**/*", "!node_modules/**", "!.git/**", "!**/*.test.js", "!**/*.spec.js"]
|
||||
"filter": [
|
||||
"**/*",
|
||||
"!node_modules/**",
|
||||
"!.git/**",
|
||||
"!**/*.test.js",
|
||||
"!**/*.spec.js"
|
||||
]
|
||||
}
|
||||
],
|
||||
"icon": "assets/favicon.ico",
|
||||
@@ -65,7 +77,9 @@
|
||||
"signAndEditExecutable": false
|
||||
},
|
||||
"mac": {
|
||||
"target": "dmg",
|
||||
"target": [
|
||||
"zip"
|
||||
],
|
||||
"icon": "assets/dashcaddy-logo.png"
|
||||
},
|
||||
"linux": {
|
||||
@@ -82,6 +96,13 @@
|
||||
"installerIcon": "assets/icon.ico",
|
||||
"uninstallerIcon": "assets/icon.ico",
|
||||
"installerHeaderIcon": "assets/icon.ico"
|
||||
},
|
||||
"publish": {
|
||||
"provider": "generic",
|
||||
"url": "https://get.dashcaddy.net/release/"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-updater": "^6.8.9"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"name": "dashcaddy-installer",
|
||||
"version": "1.0.0",
|
||||
"description": "Cross-platform installer for DashCaddy platform",
|
||||
"main": "src/main/index.js",
|
||||
"scripts": {
|
||||
"start": "electron .",
|
||||
"dev": "electron . --dev",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"build": "electron-builder",
|
||||
"build:win": "electron-builder --win",
|
||||
"build:mac": "electron-builder --mac",
|
||||
"build:linux": "electron-builder --linux"
|
||||
},
|
||||
"keywords": [
|
||||
"dashcaddy",
|
||||
"installer",
|
||||
"docker",
|
||||
"caddy"
|
||||
],
|
||||
"author": {
|
||||
"name": "DashCaddy Team",
|
||||
"email": "dashcaddy@sami.cloud"
|
||||
},
|
||||
"homepage": "https://github.com/dashcaddy/dashcaddy",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"electron": "^28.3.3",
|
||||
"electron-builder": "^24.9.1",
|
||||
"fast-check": "^3.15.0",
|
||||
"jest": "^29.7.0"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.dashcaddy.installer",
|
||||
"productName": "DashCaddy Installer",
|
||||
"asar": true,
|
||||
"directories": {
|
||||
"output": "build-output"
|
||||
},
|
||||
"files": [
|
||||
"src/**/*",
|
||||
"assets/**/*",
|
||||
"templates/**/*"
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "../status",
|
||||
"to": "status",
|
||||
"filter": [
|
||||
"**/*",
|
||||
"!node_modules/**",
|
||||
"!.git/**",
|
||||
"!**/*.test.js",
|
||||
"!**/*.spec.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "../dashcaddy-api",
|
||||
"to": "dashcaddy-api",
|
||||
"filter": [
|
||||
"**/*",
|
||||
"!node_modules/**",
|
||||
"!.git/**",
|
||||
"!**/*.test.js",
|
||||
"!**/*.spec.js"
|
||||
]
|
||||
}
|
||||
],
|
||||
"icon": "assets/favicon.ico",
|
||||
"win": {
|
||||
"target": [
|
||||
"nsis",
|
||||
"portable"
|
||||
],
|
||||
"icon": "assets/favicon.ico",
|
||||
"signAndEditExecutable": false
|
||||
},
|
||||
"mac": {
|
||||
"target": [
|
||||
"zip"
|
||||
],
|
||||
"icon": "assets/dashcaddy-logo.png"
|
||||
},
|
||||
"linux": {
|
||||
"target": [
|
||||
"AppImage",
|
||||
"deb"
|
||||
],
|
||||
"icon": "assets/dashcaddy-logo.png",
|
||||
"category": "Utility"
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": false,
|
||||
"allowToChangeInstallationDirectory": true,
|
||||
"installerIcon": "assets/icon.ico",
|
||||
"uninstallerIcon": "assets/icon.ico",
|
||||
"installerHeaderIcon": "assets/icon.ico"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"electron-updater": "^6.8.9"
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,105 @@ process.on('uncaughtException', (error) => {
|
||||
let mainWindow;
|
||||
const { registerVMHandlers } = require('./vm-ipc');
|
||||
|
||||
// --- Auto-updater (electron-updater) ---
|
||||
// Checks get.dashcaddy.net for new installer versions. Failures are silent
|
||||
// so offline / air-gapped hosts are unaffected.
|
||||
const { autoUpdater, Notification } = require('electron-updater');
|
||||
const UPDATE_FEED_URL = 'https://get.dashcaddy.net/release/';
|
||||
|
||||
function configureAutoUpdater() {
|
||||
autoUpdater.autoDownload = true; // download silently in background
|
||||
autoUpdater.autoInstallOnAppQuit = true; // install on next quit
|
||||
autoUpdater.setFeedURL({ provider: 'generic', url: UPDATE_FEED_URL });
|
||||
|
||||
// Graceful error handling — never crash on update failures
|
||||
autoUpdater.on('error', (error) => {
|
||||
console.error('[Updater] Error:', error == null ? 'unknown' : error.message || String(error));
|
||||
});
|
||||
|
||||
autoUpdater.on('update-available', (info) => {
|
||||
console.log('[Updater] Update available:', info && info.version);
|
||||
try {
|
||||
// Show a desktop notification if supported; renderer is notified via IPC too
|
||||
if (Notification && Notification.isSupported()) {
|
||||
new Notification({
|
||||
title: 'A new version of DashCaddy is available',
|
||||
body: `Version ${info && info.version ? info.version : 'new'} is downloading and will install when you quit.`,
|
||||
silent: true
|
||||
}).show();
|
||||
}
|
||||
} catch (e) {
|
||||
// notifications may be unsupported (headless) — ignore
|
||||
}
|
||||
// Forward to the wizard so it can show an in-app banner
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('update-available', {
|
||||
version: info && info.version ? info.version : null
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
autoUpdater.on('update-not-available', (info) => {
|
||||
console.log('[Updater] Up to date.');
|
||||
});
|
||||
|
||||
autoUpdater.on('download-progress', (progress) => {
|
||||
// keep verbose; useful for debugging but not surfaced to UI unless desired
|
||||
if (progress && progress.percent) {
|
||||
console.log(`[Updater] Downloading update: ${Math.round(progress.percent)}%`);
|
||||
}
|
||||
});
|
||||
|
||||
autoUpdater.on('update-downloaded', (info) => {
|
||||
console.log('[Updater] Update downloaded; will install on quit.', info && info.version);
|
||||
try {
|
||||
if (Notification && Notification.isSupported()) {
|
||||
new Notification({
|
||||
title: 'DashCaddy update ready',
|
||||
body: 'It will be installed automatically when you quit the installer.',
|
||||
silent: true
|
||||
}).show();
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('update-downloaded', {
|
||||
version: info && info.version ? info.version : null
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Check for updates after a short delay so the wizard can boot first.
|
||||
setTimeout(() => {
|
||||
autoUpdater.checkForUpdates().catch((e) => {
|
||||
// offline / network errors are expected — stay silent
|
||||
console.error('[Updater] checkForUpdates failed (likely offline):', e == null ? 'unknown' : e.message || String(e));
|
||||
});
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
// IPC: renderer can manually trigger an update check
|
||||
ipcMain.handle('check-for-updates', async () => {
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
return { success: true, updateInfo: result && result.updateInfo ? { version: result.updateInfo.version } : null };
|
||||
} catch (e) {
|
||||
return { success: false, error: e == null ? 'unknown' : e.message || String(e) };
|
||||
}
|
||||
});
|
||||
|
||||
// IPC: renderer can request to quit-and-install a downloaded update
|
||||
ipcMain.handle('quit-and-install', async () => {
|
||||
try {
|
||||
autoUpdater.quitAndInstall();
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return { success: false, error: e == null ? 'unknown' : e.message || String(e) };
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 900,
|
||||
@@ -64,6 +163,9 @@ ipcMain.handle('get-disk-space', async (event, targetPath) => {
|
||||
app.whenReady().then(() => {
|
||||
createWindow();
|
||||
|
||||
// Start the auto-updater (10s delayed check, silent on failure)
|
||||
configureAutoUpdater();
|
||||
|
||||
registerVMHandlers(mainWindow);
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -113,6 +113,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
ipcRenderer.on('vm:error', (event, data) => callback(data));
|
||||
},
|
||||
|
||||
// --- Auto-updater ---
|
||||
checkForUpdates: () => ipcRenderer.invoke('check-for-updates'),
|
||||
quitAndInstall: () => ipcRenderer.invoke('quit-and-install'),
|
||||
onUpdateAvailable: (callback) => {
|
||||
ipcRenderer.on('update-available', (event, data) => callback(data));
|
||||
},
|
||||
onUpdateDownloaded: (callback) => {
|
||||
ipcRenderer.on('update-downloaded', (event, data) => callback(data));
|
||||
},
|
||||
|
||||
// Remove listeners
|
||||
removeListener: (channel) => {
|
||||
ipcRenderer.removeAllListeners(channel);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="./disk-budget-step.js"></script>
|
||||
<script src="./wizard.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -44,12 +44,24 @@ const state = {
|
||||
email: '',
|
||||
caName: 'DashCaddy Local CA'
|
||||
},
|
||||
// Disk budget / VM sandbox configuration
|
||||
diskBudget: {
|
||||
preset: 'balanced',
|
||||
diskSizeGB: 30,
|
||||
customSizeGB: 30
|
||||
},
|
||||
// Detected network IPs
|
||||
network: {
|
||||
lanIP: '',
|
||||
tailscaleIP: '',
|
||||
detected: false
|
||||
},
|
||||
// Auto-updater state
|
||||
update: {
|
||||
available: false,
|
||||
downloaded: false,
|
||||
version: null
|
||||
},
|
||||
installation: {
|
||||
status: 'pending', // pending, running, complete, error
|
||||
progress: 0,
|
||||
@@ -91,6 +103,7 @@ const steps = [
|
||||
{ id: 'welcome', title: 'Welcome' },
|
||||
{ id: 'dependencies', title: 'Dependencies' },
|
||||
{ id: 'folder', title: 'Install Path' },
|
||||
{ id: 'disk', title: 'Storage' },
|
||||
{ id: 'tier', title: 'Tier' },
|
||||
{ id: 'access', title: 'Access' },
|
||||
{ id: 'dns', title: 'DNS' },
|
||||
@@ -179,7 +192,7 @@ function setupEventListeners() {
|
||||
state.result.dashboardUrl = data.dashboardUrl;
|
||||
state.result.installPath = data.installPath;
|
||||
state.result.health = data.health || null;
|
||||
state.currentStep = 8; // Move to complete step
|
||||
state.currentStep = 9; // Move to complete step
|
||||
render();
|
||||
});
|
||||
|
||||
@@ -207,6 +220,35 @@ function setupEventListeners() {
|
||||
state.uninstall.error = data.error;
|
||||
render();
|
||||
});
|
||||
|
||||
// VM provisioning progress / error listeners
|
||||
window.electronAPI.onVMProgress((data) => {
|
||||
if (state.installation.status === 'running') {
|
||||
state.installation.progress = Math.min(data.progress || 0, 5);
|
||||
state.installation.currentTask = data.task || 'Provisioning sandboxed virtual disk...';
|
||||
render();
|
||||
}
|
||||
});
|
||||
|
||||
window.electronAPI.onVMError((data) => {
|
||||
state.installation.status = 'error';
|
||||
state.installation.error = data.error || 'VM provisioning failed';
|
||||
render();
|
||||
});
|
||||
|
||||
// Auto-updater listeners
|
||||
window.electronAPI.onUpdateAvailable((data) => {
|
||||
state.update.available = true;
|
||||
state.update.downloaded = false;
|
||||
state.update.version = (data && data.version) ? data.version : null;
|
||||
render();
|
||||
});
|
||||
|
||||
window.electronAPI.onUpdateDownloaded((data) => {
|
||||
state.update.downloaded = true;
|
||||
state.update.version = (data && data.version) ? data.version : state.update.version;
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
// Navigation
|
||||
@@ -219,7 +261,7 @@ function nextStep() {
|
||||
case 1: // Dependencies
|
||||
checkDependencies();
|
||||
break;
|
||||
case 7: // Installation
|
||||
case 8: // Installation
|
||||
startInstallation();
|
||||
break;
|
||||
}
|
||||
@@ -420,6 +462,33 @@ async function startInstallation() {
|
||||
render();
|
||||
|
||||
try {
|
||||
// ── Provision sandboxed VM disk before installation ─────────
|
||||
if (state.diskBudget && state.diskBudget.diskSizeGB) {
|
||||
state.installation.currentTask = 'Provisioning sandboxed virtual disk...';
|
||||
state.installation.progress = 1;
|
||||
render();
|
||||
|
||||
const domain = state.domainMode === 'public'
|
||||
? state.domain.publicDomain
|
||||
: state.domainMode === 'custom-tld'
|
||||
? state.domain.tld
|
||||
: null;
|
||||
|
||||
const vmResult = await window.electronAPI.vmProvision({
|
||||
diskSizeGB: state.diskBudget.diskSizeGB,
|
||||
installPath: state.paths.install,
|
||||
apiPort: state.branding.apiPort,
|
||||
domain
|
||||
});
|
||||
|
||||
if (!vmResult || !vmResult.success) {
|
||||
throw new Error((vmResult && vmResult.error) || 'VM provisioning failed');
|
||||
}
|
||||
state.installation.completedTasks.push('Virtual disk provisioned');
|
||||
state.installation.progress = 5;
|
||||
render();
|
||||
}
|
||||
|
||||
await window.electronAPI.runInstallation({
|
||||
installPath: state.paths.install,
|
||||
dockerDataPath: state.paths.dockerData,
|
||||
@@ -511,12 +580,13 @@ function renderCurrentStep() {
|
||||
case 0: return renderWelcome();
|
||||
case 1: return renderDependencies();
|
||||
case 2: return renderFolderSelection();
|
||||
case 3: return renderTierSelection();
|
||||
case 4: return renderAccessMode();
|
||||
case 5: return renderDNSConfiguration();
|
||||
case 6: return renderDashboardSetup();
|
||||
case 7: return renderInstallation();
|
||||
case 8: return renderComplete();
|
||||
case 3: return renderDiskBudgetStep();
|
||||
case 4: return renderTierSelection();
|
||||
case 5: return renderAccessMode();
|
||||
case 6: return renderDNSConfiguration();
|
||||
case 7: return renderDashboardSetup();
|
||||
case 8: return renderInstallation();
|
||||
case 9: return renderComplete();
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
@@ -1125,7 +1195,7 @@ function renderComplete() {
|
||||
function renderFooter() {
|
||||
const isFirst = state.currentStep === 0;
|
||||
const isLast = state.currentStep === steps.length - 1;
|
||||
const isInstalling = state.currentStep === 7 && state.installation.status === 'running';
|
||||
const isInstalling = state.currentStep === 8 && state.installation.status === 'running';
|
||||
|
||||
// Determine if user can proceed
|
||||
let canProceed = true;
|
||||
@@ -1136,7 +1206,7 @@ function renderFooter() {
|
||||
case 2: // Folder
|
||||
canProceed = !!state.paths.install;
|
||||
break;
|
||||
case 4: // Access mode
|
||||
case 5: // Access mode
|
||||
if (state.domainMode === 'public') {
|
||||
canProceed = !!state.domain.publicDomain && !!state.domain.email;
|
||||
} else if (state.domainMode === 'custom-tld') {
|
||||
@@ -1165,7 +1235,7 @@ function renderFooter() {
|
||||
|
||||
// Button text
|
||||
let nextLabel = 'Next';
|
||||
if (state.currentStep === 6) nextLabel = 'Install';
|
||||
if (state.currentStep === 7) nextLabel = 'Install';
|
||||
|
||||
return `
|
||||
<div class="step-footer">
|
||||
@@ -1263,6 +1333,26 @@ async function startUninstallation() {
|
||||
render();
|
||||
|
||||
try {
|
||||
// Destroy VM sandbox first (if it exists)
|
||||
if (window.electronAPI.vmDestroy && state.uninstall.config?.vmInfo) {
|
||||
state.uninstall.currentTask = 'Destroying virtual disk sandbox...';
|
||||
render();
|
||||
try {
|
||||
const vmResult = await window.electronAPI.vmDestroy({
|
||||
installPath: state.uninstall.installPath,
|
||||
vmInfo: state.uninstall.config.vmInfo,
|
||||
exportDataPath: state.uninstall.preserveSettings ? null : null
|
||||
});
|
||||
if (vmResult.success) {
|
||||
state.uninstall.completedTasks.push({ step: 'VM sandbox removed', detail: vmResult.message || 'Virtual disk deleted' });
|
||||
render();
|
||||
}
|
||||
} catch (vmErr) {
|
||||
console.warn('VM destroy failed (non-fatal):', vmErr.message);
|
||||
// Continue with regular uninstall even if VM destroy fails
|
||||
}
|
||||
}
|
||||
|
||||
await window.electronAPI.runUninstallation({
|
||||
installPath: state.uninstall.installPath,
|
||||
preserveSettings: state.uninstall.preserveSettings,
|
||||
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
# DashCaddy Deployment Script
|
||||
# Deploys changes from Dev (E:) to Prod (C:)
|
||||
|
||||
$DevRoot = "E:\CaddyCerts\sites"
|
||||
$ProdRoot = "C:\Caddy"
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
Write-Host "Deploying DashCaddy Changes..." -ForegroundColor Cyan
|
||||
|
||||
# 1. Pre-deploy validation - syntax check all JS files
|
||||
Write-Host "Validating JavaScript syntax..." -ForegroundColor Yellow
|
||||
$syntaxErrors = 0
|
||||
Get-ChildItem "$DevRoot\dashcaddy-api" -Filter "*.js" | ForEach-Object {
|
||||
$result = & node -c $_.FullName 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Syntax error in $($_.Name): $result"
|
||||
$syntaxErrors++
|
||||
}
|
||||
}
|
||||
Get-ChildItem "$DevRoot\dashcaddy-api\routes" -Filter "*.js" | ForEach-Object {
|
||||
$result = & node -c $_.FullName 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Syntax error in routes/$($_.Name): $result"
|
||||
$syntaxErrors++
|
||||
}
|
||||
}
|
||||
if ($syntaxErrors -gt 0) {
|
||||
Write-Error "Aborting deploy: $syntaxErrors syntax error(s) found."
|
||||
exit 1
|
||||
}
|
||||
Write-Host " All files pass syntax check." -ForegroundColor Green
|
||||
|
||||
# 2. Update Frontend
|
||||
Write-Host "Updating Dashboard UI..." -ForegroundColor Yellow
|
||||
if (Test-Path "$ProdRoot\sites\status") {
|
||||
# Build frontend bundles
|
||||
Write-Host "Building frontend JavaScript..." -ForegroundColor Yellow
|
||||
Set-Location "$DevRoot\status"
|
||||
& npm install
|
||||
& node build.js
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Frontend build failed!"
|
||||
exit 1
|
||||
}
|
||||
Write-Host " Frontend build complete." -ForegroundColor Green
|
||||
|
||||
# Copy all necessary files
|
||||
Copy-Item "$DevRoot\status\index.html" "$ProdRoot\sites\status\index.html" -Force
|
||||
Copy-Item "$DevRoot\status\dist\*" "$ProdRoot\sites\status\dist\" -Force
|
||||
Set-Location $ProdRoot
|
||||
} else {
|
||||
Write-Warning "Target status folder not found. Skipping UI update."
|
||||
}
|
||||
|
||||
# 3. Update Backend API
|
||||
Write-Host "Updating API Server..." -ForegroundColor Yellow
|
||||
if (Test-Path "$ProdRoot\sites\dashcaddy-api") {
|
||||
# Copy all JS files, package files, API spec
|
||||
Get-ChildItem "$DevRoot\dashcaddy-api" -Filter "*.js" | Copy-Item -Destination "$ProdRoot\sites\dashcaddy-api\" -Force
|
||||
Copy-Item "$DevRoot\dashcaddy-api\package.json" "$ProdRoot\sites\dashcaddy-api\" -Force
|
||||
Copy-Item "$DevRoot\dashcaddy-api\package-lock.json" "$ProdRoot\sites\dashcaddy-api\" -Force -ErrorAction SilentlyContinue
|
||||
Copy-Item "$DevRoot\dashcaddy-api\openapi.yaml" "$ProdRoot\sites\dashcaddy-api\" -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# Copy route modules
|
||||
if (!(Test-Path "$ProdRoot\sites\dashcaddy-api\routes")) {
|
||||
New-Item -ItemType Directory -Path "$ProdRoot\sites\dashcaddy-api\routes" | Out-Null
|
||||
}
|
||||
Copy-Item "$DevRoot\dashcaddy-api\routes\*" "$ProdRoot\sites\dashcaddy-api\routes\" -Force
|
||||
|
||||
# 4. Rebuild and Restart
|
||||
Write-Host "Rebuilding API Container..." -ForegroundColor Yellow
|
||||
Set-Location $ProdRoot
|
||||
docker-compose up -d --build dashcaddy-api
|
||||
|
||||
# 5. Post-deploy health check
|
||||
Write-Host "Waiting for container startup..." -ForegroundColor Yellow
|
||||
Start-Sleep -Seconds 5
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri "http://localhost:3001/health" -TimeoutSec 10 -ErrorAction Stop
|
||||
if ($health.status -eq 'ok') {
|
||||
Write-Host " Health check passed." -ForegroundColor Green
|
||||
} else {
|
||||
Write-Warning "Health check returned unexpected status: $($health.status)"
|
||||
}
|
||||
} catch {
|
||||
Write-Warning "Health check failed: $_"
|
||||
Write-Warning "Check logs with: docker logs --tail 30 dashcaddy-api"
|
||||
}
|
||||
} else {
|
||||
Write-Warning "Target API folder not found. Skipping API update."
|
||||
}
|
||||
|
||||
Write-Host "Deployment Complete! Refresh your dashboard." -ForegroundColor Green
|
||||
@@ -1,242 +0,0 @@
|
||||
# SAMI-CLOUD Status Dashboard API
|
||||
|
||||
Cross-platform Node.js API server for managing Caddy reverse proxy and DNS records via REST APIs.
|
||||
|
||||
## Features
|
||||
|
||||
- **Cross-Platform**: Works on Windows, Linux, and macOS
|
||||
- **API-Based**: Uses Caddy Admin API and Technitium DNS API (no PowerShell required)
|
||||
- **App Deployment**: Deploy apps by creating DNS records and Caddy reverse proxy routes
|
||||
- **App Deletion**: Clean removal of DNS records and Caddy routes
|
||||
- **Automatic Rollback**: If deployment fails, automatically rolls back changes
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Node.js** (v14 or higher)
|
||||
2. **Caddy** with Admin API enabled
|
||||
3. **Technitium DNS Server** (optional, for DNS management)
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cd api
|
||||
npm install
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Set the following environment variables (or use defaults):
|
||||
|
||||
```bash
|
||||
# Caddy Admin API endpoint (default: http://localhost:2019)
|
||||
export CADDY_ADMIN_API=http://localhost:2019
|
||||
|
||||
# Technitium DNS Server API endpoint (default: http://192.168.254.204:5380)
|
||||
export DNS_SERVER_API=http://192.168.254.204:5380
|
||||
|
||||
# Technitium DNS API token (required for DNS operations)
|
||||
export TECHNITIUM_API_TOKEN=your_api_token_here
|
||||
```
|
||||
|
||||
### Windows (PowerShell)
|
||||
```powershell
|
||||
$env:CADDY_ADMIN_API="http://localhost:2019"
|
||||
$env:DNS_SERVER_API="http://192.168.254.204:5380"
|
||||
$env:TECHNITIUM_API_TOKEN="your_api_token_here"
|
||||
```
|
||||
|
||||
### Windows (Command Prompt)
|
||||
```cmd
|
||||
set CADDY_ADMIN_API=http://localhost:2019
|
||||
set DNS_SERVER_API=http://192.168.254.204:5380
|
||||
set TECHNITIUM_API_TOKEN=your_api_token_here
|
||||
```
|
||||
|
||||
## Running the Server
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
Or directly:
|
||||
```bash
|
||||
node caddy-api.js
|
||||
```
|
||||
|
||||
The server will start on port 3001.
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Deploy an App
|
||||
```http
|
||||
POST /api/apps/deploy
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"appId": "myapp",
|
||||
"config": {
|
||||
"subdomain": "myapp",
|
||||
"ip": "192.168.1.100",
|
||||
"port": "8080",
|
||||
"createDns": true,
|
||||
"dnsType": "private",
|
||||
"sslType": "internal"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "App myapp deployed successfully",
|
||||
"url": "https://myapp.sami",
|
||||
"domain": "myapp.sami",
|
||||
"ip": "192.168.1.100",
|
||||
"port": "8080",
|
||||
"dnsCreated": true,
|
||||
"caddyConfigured": true
|
||||
}
|
||||
```
|
||||
|
||||
### Delete an App
|
||||
```http
|
||||
POST /api/apps/delete
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"domain": "myapp.sami",
|
||||
"ip": "192.168.1.100"
|
||||
}
|
||||
```
|
||||
|
||||
### Get Services List
|
||||
```http
|
||||
GET /api/services
|
||||
```
|
||||
|
||||
### Get Caddy Configuration
|
||||
```http
|
||||
GET /api/caddy/config
|
||||
```
|
||||
|
||||
### Test API
|
||||
```http
|
||||
GET /api/caddy/test
|
||||
```
|
||||
|
||||
### Health Check
|
||||
```http
|
||||
GET /health
|
||||
```
|
||||
|
||||
## Caddy Configuration Requirements
|
||||
|
||||
Your Caddyfile should have the Admin API enabled:
|
||||
|
||||
```caddyfile
|
||||
{
|
||||
admin localhost:2019 {
|
||||
origins localhost localhost:2019
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For the status dashboard to proxy API requests, add this to your Caddyfile:
|
||||
|
||||
```caddyfile
|
||||
status.sami {
|
||||
tls internal
|
||||
|
||||
# API proxy to Node.js server
|
||||
handle /api/* {
|
||||
reverse_proxy localhost:3001
|
||||
}
|
||||
|
||||
# Static site
|
||||
root * /path/to/sites/status
|
||||
file_server
|
||||
}
|
||||
```
|
||||
|
||||
## Getting Technitium DNS API Token
|
||||
|
||||
1. Open Technitium DNS web interface
|
||||
2. Go to Settings → API
|
||||
3. Create a new API token or copy existing one
|
||||
4. Set it as the `TECHNITIUM_API_TOKEN` environment variable
|
||||
|
||||
## Deployment Flow
|
||||
|
||||
When deploying an app:
|
||||
|
||||
1. **Validate** - Checks required fields (appId, subdomain, ip)
|
||||
2. **DNS Record** - Creates A record in DNS (if `createDns: true` and `dnsType: "private"`)
|
||||
3. **Caddy Route** - Adds reverse proxy route via Caddy Admin API
|
||||
4. **Rollback** - If Caddy configuration fails, removes DNS record
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Caddy Admin API not accessible
|
||||
- Verify Caddy is running
|
||||
- Check that admin API is enabled in your Caddyfile
|
||||
- Confirm the CADDY_ADMIN_API URL is correct
|
||||
|
||||
### DNS operations failing
|
||||
- Verify TECHNITIUM_API_TOKEN is set correctly
|
||||
- Check DNS_SERVER_API URL is accessible
|
||||
- Ensure the API token has permissions to manage zones
|
||||
|
||||
### Routes not appearing in Caddy
|
||||
- Check Caddy logs: `caddy logs`
|
||||
- Verify the route was added: `curl http://localhost:2019/config/`
|
||||
- Ensure the domain resolves correctly in DNS
|
||||
|
||||
## Production Deployment
|
||||
|
||||
For production use:
|
||||
|
||||
1. Set up environment variables persistently
|
||||
2. Use a process manager (PM2, systemd, etc.)
|
||||
3. Configure proper logging
|
||||
4. Set up SSL/TLS for the API if exposed externally
|
||||
|
||||
### Using PM2
|
||||
```bash
|
||||
npm install -g pm2
|
||||
pm2 start caddy-api.js --name sami-api
|
||||
pm2 save
|
||||
pm2 startup
|
||||
```
|
||||
|
||||
### Using systemd (Linux)
|
||||
Create `/etc/systemd/system/sami-api.service`:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=SAMI-CLOUD API Server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=caddy
|
||||
WorkingDirectory=/path/to/sites/status/api
|
||||
Environment="CADDY_ADMIN_API=http://localhost:2019"
|
||||
Environment="DNS_SERVER_API=http://192.168.254.204:5380"
|
||||
Environment="TECHNITIUM_API_TOKEN=your_token"
|
||||
ExecStart=/usr/bin/node caddy-api.js
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Then:
|
||||
```bash
|
||||
sudo systemctl enable sami-api
|
||||
sudo systemctl start sami-api
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,362 +0,0 @@
|
||||
// Cross-platform Node.js API server for Caddy management
|
||||
// Uses Caddy Admin API and Technitium DNS API directly
|
||||
// Run with: node caddy-api.js
|
||||
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const cors = require('cors');
|
||||
const fs = require('fs');
|
||||
|
||||
const app = express();
|
||||
const PORT = 3001;
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static('public'));
|
||||
|
||||
// Configuration
|
||||
const CADDY_ADMIN_API = process.env.CADDY_ADMIN_API || 'http://localhost:2019';
|
||||
const DNS_SERVER_API = process.env.DNS_SERVER_API || 'http://192.168.254.204:5380';
|
||||
const DNS_API_TOKEN = process.env.TECHNITIUM_API_TOKEN || '';
|
||||
|
||||
// Helper function to make HTTP requests
|
||||
async function makeRequest(url, options = {}) {
|
||||
const https = url.startsWith('https:') ? require('https') : require('http');
|
||||
const urlObj = new URL(url);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const reqOptions = {
|
||||
hostname: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: options.method || 'GET',
|
||||
headers: options.headers || {},
|
||||
...options
|
||||
};
|
||||
|
||||
const req = https.request(reqOptions, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => data += chunk);
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
resolve({ status: res.statusCode, data: parsed });
|
||||
} catch (e) {
|
||||
resolve({ status: res.statusCode, data: data });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', reject);
|
||||
|
||||
if (options.body) {
|
||||
req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));
|
||||
}
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// Get current Caddy configuration
|
||||
app.get('/api/v1/caddy/config', async (req, res) => {
|
||||
try {
|
||||
const response = await makeRequest(`${CADDY_ADMIN_API}/config/`);
|
||||
|
||||
if (response.status === 200) {
|
||||
res.json({
|
||||
status: 'success',
|
||||
config: response.data
|
||||
});
|
||||
} else {
|
||||
res.status(response.status).json({
|
||||
status: 'error',
|
||||
message: 'Failed to get Caddy configuration',
|
||||
details: response.data
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting Caddy config:', error);
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get list of services (from apps.json + custom apps)
|
||||
app.get('/api/v1/services', async (req, res) => {
|
||||
try {
|
||||
const servicesPath = path.join(__dirname, '../apps.json');
|
||||
|
||||
if (fs.existsSync(servicesPath)) {
|
||||
const servicesData = fs.readFileSync(servicesPath, 'utf8');
|
||||
const services = JSON.parse(servicesData);
|
||||
res.json({ status: 'success', services });
|
||||
} else {
|
||||
res.json({ status: 'success', services: [] });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reading services:', error);
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Add DNS record via Technitium API
|
||||
async function addDnsRecord(domain, ipAddress, ttl = 3600) {
|
||||
if (!DNS_API_TOKEN) {
|
||||
throw new Error('DNS API token not configured. Set TECHNITIUM_API_TOKEN environment variable.');
|
||||
}
|
||||
|
||||
const url = `${DNS_SERVER_API}/api/zones/records/add?token=${DNS_API_TOKEN}&domain=${domain}&type=A&ipAddress=${ipAddress}&ttl=${ttl}`;
|
||||
|
||||
console.log('Adding DNS record:', { domain, ipAddress, ttl });
|
||||
const response = await makeRequest(url);
|
||||
|
||||
if (response.data.status === 'ok') {
|
||||
return { success: true, message: 'DNS record added successfully' };
|
||||
} else {
|
||||
throw new Error(`DNS API error: ${response.data.message || 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete DNS record via Technitium API
|
||||
async function deleteDnsRecord(domain, ipAddress) {
|
||||
if (!DNS_API_TOKEN) {
|
||||
console.warn('DNS API token not configured. Skipping DNS deletion.');
|
||||
return { success: true, message: 'DNS deletion skipped (no token)' };
|
||||
}
|
||||
|
||||
const url = `${DNS_SERVER_API}/api/zones/records/delete?token=${DNS_API_TOKEN}&domain=${domain}&type=A&ipAddress=${ipAddress}`;
|
||||
|
||||
console.log('Deleting DNS record:', { domain, ipAddress });
|
||||
const response = await makeRequest(url);
|
||||
|
||||
if (response.data.status === 'ok') {
|
||||
return { success: true, message: 'DNS record deleted successfully' };
|
||||
} else {
|
||||
throw new Error(`DNS API error: ${response.data.message || 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Add route to Caddy via Admin API
|
||||
async function addCaddyRoute(domain, upstreamUrl, useTls = true) {
|
||||
// Build Caddy route configuration
|
||||
const routeConfig = {
|
||||
"@id": domain,
|
||||
"match": [{
|
||||
"host": [domain]
|
||||
}],
|
||||
"handle": [{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [{
|
||||
"dial": upstreamUrl.replace(/^https?:\/\//, '')
|
||||
}]
|
||||
}],
|
||||
"terminal": true
|
||||
};
|
||||
|
||||
// If using internal TLS, we need to add TLS configuration
|
||||
if (useTls) {
|
||||
// Caddy handles TLS automatically for matched domains
|
||||
// Internal CA is configured in the global Caddyfile
|
||||
}
|
||||
|
||||
console.log('Adding Caddy route:', JSON.stringify(routeConfig, null, 2));
|
||||
|
||||
// Add the route to the HTTP server
|
||||
const response = await makeRequest(`${CADDY_ADMIN_API}/config/apps/http/servers/srv0/routes/0`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(routeConfig)
|
||||
});
|
||||
|
||||
if (response.status === 200 || response.status === 201) {
|
||||
return { success: true, message: 'Caddy route added successfully' };
|
||||
} else {
|
||||
throw new Error(`Caddy API error: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Deploy app endpoint - handles DNS and Caddy configuration via APIs
|
||||
app.post('/api/v1/apps/deploy', async (req, res) => {
|
||||
try {
|
||||
const { appId, config } = req.body;
|
||||
const { subdomain, ip, createDns, port, sslType, dnsType } = config;
|
||||
|
||||
console.log('Deploying app:', { appId, config });
|
||||
|
||||
// Validate required fields
|
||||
if (!appId || !subdomain || !ip) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Missing required fields: appId, subdomain, ip'
|
||||
});
|
||||
}
|
||||
|
||||
// Build the full domain
|
||||
const domain = subdomain.includes('.') ? subdomain : `${subdomain}.sami`;
|
||||
const finalPort = port || '80';
|
||||
const upstreamUrl = `${ip}:${finalPort}`;
|
||||
|
||||
// Step 1: Add DNS record if requested (private DNS)
|
||||
if (createDns && dnsType === 'private') {
|
||||
try {
|
||||
await addDnsRecord(domain, ip);
|
||||
} catch (dnsError) {
|
||||
console.error('DNS creation failed:', dnsError);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: `DNS creation failed: ${dnsError.message}`,
|
||||
step: 'dns'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Add route to Caddy via Admin API
|
||||
try {
|
||||
const useTls = sslType === 'internal';
|
||||
await addCaddyRoute(domain, upstreamUrl, useTls);
|
||||
} catch (caddyError) {
|
||||
console.error('Caddy route addition failed:', caddyError);
|
||||
|
||||
// Rollback DNS if it was created
|
||||
if (createDns && dnsType === 'private') {
|
||||
try {
|
||||
await deleteDnsRecord(domain, ip);
|
||||
} catch (rollbackError) {
|
||||
console.error('DNS rollback failed:', rollbackError);
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: `Caddy configuration failed: ${caddyError.message}`,
|
||||
step: 'caddy'
|
||||
});
|
||||
}
|
||||
|
||||
// Step 3: Return success response
|
||||
res.json({
|
||||
success: true,
|
||||
message: `App ${appId} deployed successfully`,
|
||||
url: `https://${domain}`,
|
||||
domain: domain,
|
||||
ip: ip,
|
||||
port: finalPort,
|
||||
containerId: null,
|
||||
dnsCreated: createDns && dnsType === 'private',
|
||||
caddyConfigured: true
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Deployment error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Delete app endpoint - removes DNS and Caddy configuration
|
||||
app.post('/api/v1/apps/delete', async (req, res) => {
|
||||
try {
|
||||
const { domain, ip } = req.body;
|
||||
|
||||
if (!domain) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Domain is required'
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Deleting app:', { domain, ip });
|
||||
|
||||
// Step 1: Remove from Caddy
|
||||
try {
|
||||
const response = await makeRequest(`${CADDY_ADMIN_API}/id/${domain}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (response.status !== 200) {
|
||||
console.warn('Caddy route deletion warning:', response.data);
|
||||
}
|
||||
} catch (caddyError) {
|
||||
console.error('Caddy route deletion failed:', caddyError);
|
||||
// Continue anyway to try DNS deletion
|
||||
}
|
||||
|
||||
// Step 2: Remove DNS record if IP provided
|
||||
if (ip) {
|
||||
try {
|
||||
await deleteDnsRecord(domain, ip);
|
||||
} catch (dnsError) {
|
||||
console.error('DNS deletion failed:', dnsError);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: `DNS deletion failed: ${dnsError.message}`,
|
||||
caddyDeleted: true,
|
||||
dnsDeleted: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'App deleted successfully',
|
||||
domain: domain,
|
||||
caddyDeleted: true,
|
||||
dnsDeleted: !!ip
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Deletion error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Test endpoint
|
||||
app.get('/api/v1/caddy/test', (req, res) => {
|
||||
res.json({
|
||||
status: 'success',
|
||||
message: 'Caddy API is running',
|
||||
timestamp: new Date().toISOString(),
|
||||
platform: process.platform,
|
||||
caddyAdminApi: CADDY_ADMIN_API,
|
||||
dnsServerApi: DNS_SERVER_API,
|
||||
dnsTokenConfigured: !!DNS_API_TOKEN
|
||||
});
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`\n====================================`);
|
||||
console.log(`Caddy API server running on http://localhost:${PORT}`);
|
||||
console.log(`====================================`);
|
||||
console.log(`Caddy Admin API: ${CADDY_ADMIN_API}`);
|
||||
console.log(`DNS Server API: ${DNS_SERVER_API}`);
|
||||
console.log(`DNS Token: ${DNS_API_TOKEN ? '✓ Configured' : '✗ Not configured'}`);
|
||||
console.log(`\nEndpoints:`);
|
||||
console.log(` POST /api/apps/deploy - Deploy an app (DNS + Caddy)`);
|
||||
console.log(` POST /api/apps/delete - Delete an app (DNS + Caddy)`);
|
||||
console.log(` GET /api/services - Get list of services`);
|
||||
console.log(` GET /api/caddy/config - Get current Caddy configuration`);
|
||||
console.log(` GET /api/caddy/test - Test API connectivity`);
|
||||
console.log(` GET /health - Health check`);
|
||||
console.log(`====================================\n`);
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
@@ -1,206 +0,0 @@
|
||||
# Caddy Configuration Manager for Windows
|
||||
# This script adds new service configurations to your Caddyfile
|
||||
|
||||
param(
|
||||
[string]$Config,
|
||||
[string]$Subdomain,
|
||||
[string]$CaddyfilePath = "C:\caddy\Caddyfile",
|
||||
[bool]$ReloadCaddy = $true
|
||||
)
|
||||
|
||||
# Function to write JSON response
|
||||
function Write-JsonResponse {
|
||||
param($Status, $Message, $Data = $null)
|
||||
|
||||
$response = @{
|
||||
status = $Status
|
||||
message = $Message
|
||||
timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
|
||||
}
|
||||
|
||||
if ($Data) {
|
||||
$response.data = $Data
|
||||
}
|
||||
|
||||
return $response | ConvertTo-Json
|
||||
}
|
||||
|
||||
# Function to extract CA names from Caddyfile
|
||||
function Get-CaddyfileCAs {
|
||||
param([string]$CaddyfilePath)
|
||||
|
||||
try {
|
||||
Write-Host "DEBUG: Checking file path: $CaddyfilePath"
|
||||
|
||||
if (-not (Test-Path $CaddyfilePath)) {
|
||||
Write-Host "DEBUG: File not found"
|
||||
return @()
|
||||
}
|
||||
|
||||
$content = Get-Content $CaddyfilePath -Raw
|
||||
Write-Host "DEBUG: File content length: $($content.Length)"
|
||||
Write-Host "DEBUG: First 200 chars: $($content.Substring(0, [Math]::Min(200, $content.Length)))"
|
||||
|
||||
$caNames = @()
|
||||
|
||||
# Pattern 1: PKI block with CA definitions - pki { ca ca_name { name "Friendly Name" } }
|
||||
$pkiPattern = 'pki\s*\{[^}]*?ca\s+([^\s\{]+)\s*\{([^}]*?)\}'
|
||||
Write-Host "DEBUG: Searching for PKI pattern: $pkiPattern"
|
||||
|
||||
$pkiMatches = [regex]::Matches($content, $pkiPattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::Singleline)
|
||||
Write-Host "DEBUG: PKI matches found: $($pkiMatches.Count)"
|
||||
|
||||
foreach ($match in $pkiMatches) {
|
||||
$caId = $match.Groups[1].Value
|
||||
$caBlock = $match.Groups[2].Value
|
||||
Write-Host "DEBUG: Found CA ID: $caId"
|
||||
Write-Host "DEBUG: CA Block: $caBlock"
|
||||
|
||||
# Try to extract the friendly name from within the CA block
|
||||
$nameMatch = [regex]::Match($caBlock, 'name\s+"([^"]+)"', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
|
||||
if ($nameMatch.Success) {
|
||||
$friendlyName = $nameMatch.Groups[1].Value
|
||||
Write-Host "DEBUG: Found friendly name: $friendlyName"
|
||||
$caNames += "$caId ($friendlyName)"
|
||||
} else {
|
||||
Write-Host "DEBUG: No friendly name found, using ID only"
|
||||
$caNames += $caId
|
||||
}
|
||||
}
|
||||
|
||||
# Pattern 2: tls { ca ca_name }
|
||||
$matches1 = [regex]::Matches($content, 'tls\s*\{\s*ca\s+([^\s\}]+)', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
|
||||
Write-Host "DEBUG: TLS block matches: $($matches1.Count)"
|
||||
foreach ($match in $matches1) {
|
||||
$caNames += $match.Groups[1].Value
|
||||
}
|
||||
|
||||
# Pattern 3: tls ca_name (direct)
|
||||
$matches2 = [regex]::Matches($content, 'tls\s+([^\s\{]+)', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
|
||||
Write-Host "DEBUG: Direct TLS matches: $($matches2.Count)"
|
||||
foreach ($match in $matches2) {
|
||||
$caName = $match.Groups[1].Value
|
||||
if ($caName -ne "internal" -and $caName -ne "off") {
|
||||
$caNames += $caName
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "DEBUG: Total CAs found: $($caNames.Count)"
|
||||
Write-Host "DEBUG: CA list: $($caNames -join ', ')"
|
||||
|
||||
# Remove duplicates and return
|
||||
return $caNames | Sort-Object | Get-Unique
|
||||
}
|
||||
catch {
|
||||
Write-Host "DEBUG: Exception in Get-CaddyfileCAs: $($_.Exception.Message)"
|
||||
Write-Host "Error reading CAs from Caddyfile: $($_.Exception.Message)"
|
||||
return @()
|
||||
}
|
||||
}
|
||||
|
||||
# Handle get-cas command
|
||||
if ($args[0] -eq "get-cas") {
|
||||
$CaddyfilePath = if ($args[1]) { $args[1] } else { "C:\caddy\Caddyfile" }
|
||||
|
||||
Write-Host "DEBUG: get-cas command received"
|
||||
Write-Host "DEBUG: Caddyfile path: $CaddyfilePath"
|
||||
Write-Host "DEBUG: File exists: $(Test-Path $CaddyfilePath)"
|
||||
|
||||
try {
|
||||
$cas = Get-CaddyfileCAs -CaddyfilePath $CaddyfilePath
|
||||
|
||||
Write-Host "DEBUG: CAs found: $($cas -join ', ')"
|
||||
|
||||
$response = @{
|
||||
status = "success"
|
||||
message = "CAs retrieved successfully"
|
||||
data = @{
|
||||
cas = $cas
|
||||
count = $cas.Count
|
||||
caddyfilePath = $CaddyfilePath
|
||||
}
|
||||
timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
|
||||
}
|
||||
|
||||
Write-Output ($response | ConvertTo-Json)
|
||||
exit 0
|
||||
}
|
||||
catch {
|
||||
Write-Host "DEBUG: Error occurred: $($_.Exception.Message)"
|
||||
|
||||
$response = @{
|
||||
status = "error"
|
||||
message = "Failed to retrieve CAs: $($_.Exception.Message)"
|
||||
timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
|
||||
}
|
||||
|
||||
Write-Output ($response | ConvertTo-Json)
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
# Main configuration addition logic
|
||||
try {
|
||||
# Validate required parameters for config addition
|
||||
if (-not $Config -or -not $Subdomain) {
|
||||
Write-Output (Write-JsonResponse "error" "Config and Subdomain parameters are required")
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Check if Caddyfile exists
|
||||
if (-not (Test-Path $CaddyfilePath)) {
|
||||
Write-Output (Write-JsonResponse "error" "Caddyfile not found at: $CaddyfilePath")
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Read existing Caddyfile
|
||||
$existingConfig = Get-Content $CaddyfilePath -Raw -ErrorAction Stop
|
||||
|
||||
# Check if subdomain already exists
|
||||
if ($existingConfig -match "$Subdomain\.sami\s*\{") {
|
||||
Write-Output (Write-JsonResponse "error" "Subdomain '$Subdomain.sami' already exists in Caddyfile")
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Create backup
|
||||
$backupPath = "$CaddyfilePath.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
|
||||
Copy-Item $CaddyfilePath $backupPath -ErrorAction Stop
|
||||
Write-Host "Backup created: $backupPath"
|
||||
|
||||
# Append new configuration
|
||||
$newContent = $existingConfig.TrimEnd() + "`n`n" + $Config.TrimEnd() + "`n"
|
||||
Set-Content -Path $CaddyfilePath -Value $newContent -NoNewline -ErrorAction Stop
|
||||
|
||||
Write-Host "Configuration added successfully"
|
||||
|
||||
# Reload Caddy if requested
|
||||
if ($ReloadCaddy) {
|
||||
Write-Host "Reloading Caddy..."
|
||||
|
||||
# Try to reload Caddy
|
||||
$reloadResult = & caddy reload --config $CaddyfilePath 2>&1
|
||||
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host "Caddy reloaded successfully"
|
||||
Write-Output (Write-JsonResponse "success" "Configuration added and Caddy reloaded successfully" @{
|
||||
backup = $backupPath
|
||||
subdomain = "$Subdomain.sami"
|
||||
})
|
||||
} else {
|
||||
Write-Host "Caddy reload failed: $reloadResult"
|
||||
# Restore backup if reload failed
|
||||
Copy-Item $backupPath $CaddyfilePath -Force
|
||||
Write-Output (Write-JsonResponse "error" "Caddy reload failed. Configuration rolled back. Error: $reloadResult")
|
||||
exit 1
|
||||
}
|
||||
} else {
|
||||
Write-Output (Write-JsonResponse "success" "Configuration added successfully (Caddy not reloaded)" @{
|
||||
backup = $backupPath
|
||||
subdomain = "$Subdomain.sami"
|
||||
})
|
||||
}
|
||||
|
||||
} catch {
|
||||
Write-Output (Write-JsonResponse "error" "Error: $($_.Exception.Message)")
|
||||
exit 1
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
@echo off
|
||||
title SAMI Caddy API Server
|
||||
echo ========================================
|
||||
echo Installing SAMI Caddy API Server...
|
||||
echo ========================================
|
||||
|
||||
REM Check if Node.js is installed
|
||||
echo Checking for Node.js...
|
||||
node --version >nul 2>&1
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo ERROR: Node.js is not installed or not in PATH
|
||||
echo Please install Node.js from https://nodejs.org/
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo Node.js found:
|
||||
node --version
|
||||
|
||||
echo.
|
||||
echo Installing dependencies...
|
||||
echo.
|
||||
|
||||
REM Install npm dependencies
|
||||
npm install
|
||||
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo ERROR: Failed to install dependencies
|
||||
echo Check the error messages above
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ========================================
|
||||
echo Dependencies installed successfully!
|
||||
echo ========================================
|
||||
echo.
|
||||
echo Starting Caddy API server...
|
||||
echo.
|
||||
echo Server URL: http://localhost:3001
|
||||
echo Test URL: http://localhost:3001/api/caddy/test
|
||||
echo.
|
||||
echo Press Ctrl+C to stop the server
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM Start the server and keep window open on error
|
||||
npm start
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo ERROR: Server failed to start
|
||||
echo Check the error messages above
|
||||
echo.
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Server stopped.
|
||||
pause
|
||||
Generated
-1227
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "sami-caddy-api",
|
||||
"version": "2.0.0",
|
||||
"description": "Cross-platform API server for managing Caddy and DNS via REST APIs",
|
||||
"main": "caddy-api.js",
|
||||
"scripts": {
|
||||
"start": "node caddy-api.js",
|
||||
"dev": "nodemon caddy-api.js",
|
||||
"test": "node test-api.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"cors": "^2.8.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.1"
|
||||
},
|
||||
"keywords": ["caddy", "api", "dns", "technitium", "reverse-proxy", "cross-platform", "sami-cloud"],
|
||||
"author": "SAMI-CLOUD",
|
||||
"license": "MIT"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
@echo off
|
||||
REM Quick start script for SAMI-CLOUD API Server (Windows)
|
||||
|
||||
echo ====================================
|
||||
echo SAMI-CLOUD API Server
|
||||
echo ====================================
|
||||
echo.
|
||||
|
||||
REM Check if Node.js is installed
|
||||
where node >nul 2>nul
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Node.js is not installed or not in PATH
|
||||
echo Please install Node.js from https://nodejs.org/
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM Check if node_modules exists
|
||||
if not exist "node_modules" (
|
||||
echo Installing dependencies...
|
||||
call npm install
|
||||
echo.
|
||||
)
|
||||
|
||||
REM Check environment variables
|
||||
if "%CADDY_ADMIN_API%"=="" (
|
||||
echo Warning: CADDY_ADMIN_API not set, using default: http://localhost:2019
|
||||
set CADDY_ADMIN_API=http://localhost:2019
|
||||
)
|
||||
|
||||
if "%DNS_SERVER_API%"=="" (
|
||||
echo Warning: DNS_SERVER_API not set, using default: http://192.168.254.204:5380
|
||||
set DNS_SERVER_API=http://192.168.254.204:5380
|
||||
)
|
||||
|
||||
if "%TECHNITIUM_API_TOKEN%"=="" (
|
||||
echo Warning: TECHNITIUM_API_TOKEN not set - DNS operations will fail
|
||||
echo Set it with: set TECHNITIUM_API_TOKEN=your_token
|
||||
echo.
|
||||
)
|
||||
|
||||
echo Starting API server...
|
||||
echo.
|
||||
node caddy-api.js
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Quick start script for SAMI-CLOUD API Server (Linux/macOS)
|
||||
|
||||
echo "===================================="
|
||||
echo "SAMI-CLOUD API Server"
|
||||
echo "===================================="
|
||||
echo ""
|
||||
|
||||
# Check if Node.js is installed
|
||||
if ! command -v node &> /dev/null; then
|
||||
echo "Error: Node.js is not installed or not in PATH"
|
||||
echo "Please install Node.js from https://nodejs.org/"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if node_modules exists
|
||||
if [ ! -d "node_modules" ]; then
|
||||
echo "Installing dependencies..."
|
||||
npm install
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Check environment variables
|
||||
if [ -z "$CADDY_ADMIN_API" ]; then
|
||||
echo "Warning: CADDY_ADMIN_API not set, using default: http://localhost:2019"
|
||||
export CADDY_ADMIN_API="http://localhost:2019"
|
||||
fi
|
||||
|
||||
if [ -z "$DNS_SERVER_API" ]; then
|
||||
echo "Warning: DNS_SERVER_API not set, using default: http://192.168.254.204:5380"
|
||||
export DNS_SERVER_API="http://192.168.254.204:5380"
|
||||
fi
|
||||
|
||||
if [ -z "$TECHNITIUM_API_TOKEN" ]; then
|
||||
echo "Warning: TECHNITIUM_API_TOKEN not set - DNS operations will fail"
|
||||
echo "Set it with: export TECHNITIUM_API_TOKEN=your_token"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
echo "Starting API server..."
|
||||
echo ""
|
||||
node caddy-api.js
|
||||
@@ -1,72 +0,0 @@
|
||||
// Simple test script to verify API connectivity
|
||||
const http = require('http');
|
||||
|
||||
const API_URL = 'http://localhost:3001';
|
||||
|
||||
function makeRequest(path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
http.get(`${API_URL}${path}`, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => data += chunk);
|
||||
res.on('end', () => {
|
||||
try {
|
||||
resolve({ status: res.statusCode, data: JSON.parse(data) });
|
||||
} catch (e) {
|
||||
resolve({ status: res.statusCode, data: data });
|
||||
}
|
||||
});
|
||||
}).on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
console.log('Testing SAMI-CLOUD API...\n');
|
||||
|
||||
// Test 1: Health Check
|
||||
console.log('1. Testing health endpoint...');
|
||||
try {
|
||||
const health = await makeRequest('/health');
|
||||
if (health.status === 200) {
|
||||
console.log(' ✓ Health check passed');
|
||||
} else {
|
||||
console.log(' ✗ Health check failed:', health.status);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(' ✗ Health check error:', error.message);
|
||||
}
|
||||
|
||||
// Test 2: API Test Endpoint
|
||||
console.log('\n2. Testing API test endpoint...');
|
||||
try {
|
||||
const test = await makeRequest('/api/v1/caddy/test');
|
||||
if (test.status === 200) {
|
||||
console.log(' ✓ API test passed');
|
||||
console.log(' Platform:', test.data.platform);
|
||||
console.log(' Caddy Admin API:', test.data.caddyAdminApi);
|
||||
console.log(' DNS Server API:', test.data.dnsServerApi);
|
||||
console.log(' DNS Token:', test.data.dnsTokenConfigured ? 'Configured' : 'Not configured');
|
||||
} else {
|
||||
console.log(' ✗ API test failed:', test.status);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(' ✗ API test error:', error.message);
|
||||
}
|
||||
|
||||
// Test 3: Services Endpoint
|
||||
console.log('\n3. Testing services endpoint...');
|
||||
try {
|
||||
const services = await makeRequest('/api/v1/services');
|
||||
if (services.status === 200) {
|
||||
console.log(' ✓ Services endpoint passed');
|
||||
console.log(' Found', services.data.services.length, 'services');
|
||||
} else {
|
||||
console.log(' ✗ Services endpoint failed:', services.status);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(' ✗ Services endpoint error:', error.message);
|
||||
}
|
||||
|
||||
console.log('\nTests complete!');
|
||||
}
|
||||
|
||||
runTests().catch(console.error);
|
||||
@@ -1,84 +0,0 @@
|
||||
@echo off
|
||||
title SAMI Caddy API Server - Debug Mode
|
||||
echo ========================================
|
||||
echo SAMI Caddy API Server - Debug Mode
|
||||
echo ========================================
|
||||
|
||||
cd /d "%~dp0"
|
||||
echo Current directory: %CD%
|
||||
|
||||
echo.
|
||||
echo Checking Node.js...
|
||||
node --version
|
||||
if %errorlevel% neq 0 (
|
||||
echo ERROR: Node.js not found
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Checking files...
|
||||
if exist "caddy-api.js" (
|
||||
echo ✓ caddy-api.js found
|
||||
) else (
|
||||
echo ✗ caddy-api.js NOT found
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "package.json" (
|
||||
echo ✓ package.json found
|
||||
) else (
|
||||
echo ✗ package.json NOT found
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "caddy-manager.ps1" (
|
||||
echo ✓ caddy-manager.ps1 found
|
||||
) else (
|
||||
echo ✗ caddy-manager.ps1 NOT found
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Installing dependencies...
|
||||
npm install
|
||||
if %errorlevel% neq 0 (
|
||||
echo ERROR: npm install failed
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ========================================
|
||||
echo Starting server with error capture...
|
||||
echo ========================================
|
||||
echo Server will run on: http://localhost:3001
|
||||
echo Test endpoint: http://localhost:3001/api/caddy/test
|
||||
echo.
|
||||
echo If server starts successfully, you'll see "Caddy API server running..."
|
||||
echo Press Ctrl+C to stop the server
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM Capture both stdout and stderr
|
||||
node caddy-api.js 2>&1
|
||||
set SERVER_EXIT_CODE=%errorlevel%
|
||||
|
||||
echo.
|
||||
echo ========================================
|
||||
echo Server exited with code: %SERVER_EXIT_CODE%
|
||||
echo ========================================
|
||||
|
||||
if %SERVER_EXIT_CODE% neq 0 (
|
||||
echo ERROR: Server failed to start or crashed
|
||||
echo Check the error messages above
|
||||
) else (
|
||||
echo Server stopped normally
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Press any key to close this window...
|
||||
pause >nul
|
||||
@@ -207,6 +207,7 @@
|
||||
<button id="audit-log-btn" aria-label="Audit log">📜 Audit</button>
|
||||
<button id="security-center-btn" aria-label="Security Center">🛡️ Security</button>
|
||||
<button id="log-insights-btn" aria-label="Log Insights">🔍 Insights</button>
|
||||
<button onclick="openDiskSettings()" aria-label="Disk Safety">💾 Disk</button>
|
||||
<button id="docker-resources-btn" aria-label="Docker resources">🐳 Docker</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -952,7 +953,9 @@
|
||||
|
||||
<!-- Tailscale device list panel (self-contained, polls /api/v1/tailscale/devices) -->
|
||||
<script src="/js/log-insights.js" defer></script>
|
||||
<script src="/js/disk-settings.js" defer></script>
|
||||
<script src="/js/tailscale-devices.js" defer></script>
|
||||
<script src="/js/language-selector.js" defer></script>
|
||||
|
||||
<!-- Bundled JS (built with: npm run build) -->
|
||||
<script src="/dist/core.js" defer></script>
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Disk Safety Settings Panel
|
||||
(function() {
|
||||
let diskSettings = null;
|
||||
|
||||
async function loadDiskSettings() {
|
||||
try {
|
||||
const res = await secureFetch('/api/v1/disk-settings');
|
||||
if (res.ok) {
|
||||
diskSettings = await res.json();
|
||||
renderDiskSettingsModal();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load disk settings:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function renderDiskSettingsModal() {
|
||||
const existing = document.getElementById('disk-settings-modal');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const c = diskSettings?.current || {};
|
||||
const du = diskSettings?.diskUsage || {};
|
||||
const usedGB = (du.dataDirSize / 1073741824).toFixed(2);
|
||||
const diskFreeGB = (du.free / 1073741824).toFixed(1);
|
||||
const diskTotalGB = (du.total / 1073741824).toFixed(1);
|
||||
const diskPct = du.total > 0 ? ((du.used / du.total) * 100).toFixed(1) : 0;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.id = 'disk-settings-modal';
|
||||
modal.className = 'modal';
|
||||
modal.style.cssText = 'display:flex;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:10000;align-items:center;justify-content:center;';
|
||||
modal.innerHTML = `
|
||||
<div style="background:var(--bg-card,#1a1a2e);border-radius:12px;padding:28px;max-width:520px;width:90%;max-height:85vh;overflow-y:auto;border:1px solid var(--border,#333);">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
|
||||
<h2 style="margin:0;font-size:1.3rem;">💾 Disk Safety</h2>
|
||||
<button onclick="document.getElementById('disk-settings-modal').remove()" style="background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--text-muted,#888);">×</button>
|
||||
</div>
|
||||
|
||||
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:8px;padding:14px;margin-bottom:20px;">
|
||||
<div style="display:flex;justify-content:space-between;margin-bottom:6px;">
|
||||
<span style="font-size:0.9rem;color:var(--text-muted,#888);">DashCaddy Data Size</span>
|
||||
<span style="font-weight:600;">${usedGB} GB</span>
|
||||
</div>
|
||||
<div style="display:flex;justify-content:space-between;margin-bottom:6px;">
|
||||
<span style="font-size:0.9rem;color:var(--text-muted,#888);">Disk Free</span>
|
||||
<span style="font-weight:600;">${diskFreeGB} GB / ${diskTotalGB} GB (${diskPct}% used)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display:grid;gap:16px;">
|
||||
${settingRow('Health Check Interval', 'healthInterval', c.healthCheckInterval, 'seconds', Math.round((c.healthCheckInterval||30000)/1000), 5, 300)}
|
||||
${settingRow('Max Health Entries/Service', 'healthMaxEntries', c.healthMaxEntries, 'entries', c.healthMaxEntries||500, 50, 5000)}
|
||||
${settingRow('Health Retention', 'healthRetentionDays', c.healthRetentionDays, 'days', c.healthRetentionDays||14, 1, 90)}
|
||||
${settingRow('Max Stats Entries', 'statsMaxEntries', c.statsMaxEntries, 'entries', c.statsMaxEntries||500, 100, 10000)}
|
||||
${settingRow('Max Audit Entries', 'auditMaxEntries', c.auditMaxEntries, 'entries', c.auditMaxEntries||1000, 100, 10000)}
|
||||
</div>
|
||||
|
||||
<div style="display:flex;gap:10px;margin-top:24px;">
|
||||
<button onclick="saveDiskSettings()" style="flex:1;padding:10px 16px;background:#6366f1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Save Settings</button>
|
||||
<button onclick="cleanupDiskNow()" style="flex:1;padding:10px 16px;background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.3);border-radius:8px;cursor:pointer;font-weight:600;">Clean Up Now</button>
|
||||
</div>
|
||||
<p style="font-size:0.8rem;color:var(--text-muted,#666);margin-top:12px;text-align:center;">Some changes apply on next container restart.</p>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(modal);
|
||||
}
|
||||
|
||||
function settingRow(label, id, current, unit, displayVal, min, max) {
|
||||
return `
|
||||
<div>
|
||||
<label style="font-size:0.85rem;color:var(--text-muted,#aaa);display:block;margin-bottom:4px;">${label}</label>
|
||||
<div style="display:flex;align-items:center;gap:10px;">
|
||||
<input type="range" id="disk-${id}" min="${min}" max="${max}" value="${displayVal}" oninput="document.getElementById('disk-${id}-val').textContent=this.value"
|
||||
style="flex:1;accent-color:#6366f1;">
|
||||
<span id="disk-${id}-val" style="min-width:50px;text-align:right;font-weight:600;">${displayVal}</span>
|
||||
<span style="font-size:0.8rem;color:var(--text-muted,#666);min-width:60px;">${unit}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function saveDiskSettings() {
|
||||
const payload = {
|
||||
healthInterval: parseInt(document.getElementById('disk-healthInterval').value) * 1000,
|
||||
healthMaxEntries: parseInt(document.getElementById('disk-healthMaxEntries').value),
|
||||
healthRetentionDays: parseInt(document.getElementById('disk-healthRetentionDays').value),
|
||||
statsMaxEntries: parseInt(document.getElementById('disk-statsMaxEntries').value),
|
||||
auditMaxEntries: parseInt(document.getElementById('disk-auditMaxEntries').value),
|
||||
};
|
||||
try {
|
||||
const res = await secureFetch('/api/v1/disk-settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
showToast('Disk settings saved', 'success');
|
||||
} else {
|
||||
showToast(data.error || 'Save failed', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanupDiskNow() {
|
||||
if (!confirm('Clean up old health entries, stats, and audit logs now?')) return;
|
||||
try {
|
||||
const res = await secureFetch('/api/v1/disk-settings/cleanup', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
const items = Object.entries(data.results.cleaned).map(([k,v]) => `${k}: ${v}`).join('\n');
|
||||
showToast('Cleanup complete', 'success');
|
||||
loadDiskSettings();
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
window.openDiskSettings = function() { loadDiskSettings(); };
|
||||
window.saveDiskSettings = saveDiskSettings;
|
||||
window.cleanupDiskNow = cleanupDiskNow;
|
||||
})();
|
||||
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* DC-077: i18n Language Selector
|
||||
*
|
||||
* Compact dropdown in the navbar (next to the theme toggle) that lets users switch
|
||||
* the dashboard language between en / es / zh / ar / de.
|
||||
*
|
||||
* - Shows current language with flag emoji
|
||||
* - Persists selection to localStorage('dashcaddy-language')
|
||||
* - Sends selection to backend via POST /api/v1/config with { language: 'xx' }
|
||||
* - Reloads the page on change so the new language takes effect
|
||||
*
|
||||
* Depends on: secureFetch() / postJSON() from globals.js (bundled in /dist/core.js).
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const STORAGE_KEY = 'dashcaddy-language';
|
||||
const CONFIG_ENDPOINT = '/api/v1/config';
|
||||
|
||||
const LANGUAGES = [
|
||||
{ code: 'en', flag: '🇬🇧', label: 'English' },
|
||||
{ code: 'es', flag: '🇪🇸', label: 'Español' },
|
||||
{ code: 'zh', flag: '🇨🇳', label: '中文' },
|
||||
{ code: 'ar', flag: '🇸🇦', label: 'العربية' },
|
||||
{ code: 'de', flag: '🇩🇪', label: 'Deutsch' },
|
||||
];
|
||||
|
||||
const SUPPORTED = LANGUAGES.map(l => l.code);
|
||||
|
||||
function getCurrentLanguage() {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored && SUPPORTED.includes(stored)) return stored;
|
||||
return 'en';
|
||||
}
|
||||
|
||||
function langMeta(code) {
|
||||
return LANGUAGES.find(l => l.code === code) || LANGUAGES[0];
|
||||
}
|
||||
|
||||
// ===== Inject styles once =====
|
||||
function injectStyles() {
|
||||
if (document.getElementById('dc-lang-selector-styles')) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = 'dc-lang-selector-styles';
|
||||
style.textContent = `
|
||||
.dc-lang-wrap {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
.dc-lang-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 14px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
white-space: nowrap;
|
||||
background: var(--card-base);
|
||||
color: var(--accent);
|
||||
border: 1px solid var(--border);
|
||||
font-family: inherit;
|
||||
}
|
||||
.dc-lang-btn:hover {
|
||||
background: color-mix(in srgb, var(--accent) 22%, transparent);
|
||||
}
|
||||
.dc-lang-btn .dc-lang-flag {
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.dc-lang-btn .dc-lang-caret {
|
||||
font-size: 0.6rem;
|
||||
opacity: 0.7;
|
||||
margin-left: 2px;
|
||||
}
|
||||
.dc-lang-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
right: 0;
|
||||
min-width: 160px;
|
||||
background: var(--card-base, #1e1e2e);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
padding: 4px;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
}
|
||||
.dc-lang-menu.open {
|
||||
display: block;
|
||||
}
|
||||
.dc-lang-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
color: var(--fg);
|
||||
transition: background 0.15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dc-lang-option:hover {
|
||||
background: color-mix(in srgb, var(--accent) 15%, transparent);
|
||||
}
|
||||
.dc-lang-option.active {
|
||||
background: color-mix(in srgb, var(--accent) 25%, transparent);
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.dc-lang-option .dc-lang-flag {
|
||||
font-size: 1.1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.dc-lang-option .dc-lang-check {
|
||||
margin-left: auto;
|
||||
opacity: 0;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.dc-lang-option.active .dc-lang-check {
|
||||
opacity: 1;
|
||||
}
|
||||
.dc-lang-label-sm {
|
||||
background: none !important;
|
||||
border: none !important;
|
||||
color: var(--muted);
|
||||
font-size: 0.7rem;
|
||||
cursor: pointer;
|
||||
padding: 2px 6px;
|
||||
font-family: inherit;
|
||||
opacity: 0.8;
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function buildMenu(current) {
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'dc-lang-menu';
|
||||
menu.setAttribute('role', 'menu');
|
||||
|
||||
for (const lang of LANGUAGES) {
|
||||
const opt = document.createElement('div');
|
||||
opt.className = 'dc-lang-option' + (lang.code === current ? ' active' : '');
|
||||
opt.setAttribute('role', 'menuitemradio');
|
||||
opt.setAttribute('aria-checked', lang.code === current ? 'true' : 'false');
|
||||
opt.dataset.lang = lang.code;
|
||||
opt.innerHTML =
|
||||
'<span class="dc-lang-flag">' + lang.flag + '</span>' +
|
||||
'<span class="dc-lang-name">' + lang.label + '</span>' +
|
||||
'<span class="dc-lang-check">✓</span>';
|
||||
menu.appendChild(opt);
|
||||
}
|
||||
return menu;
|
||||
}
|
||||
|
||||
async function selectLanguage(code) {
|
||||
if (!SUPPORTED.includes(code) || code === getCurrentLanguage()) return;
|
||||
// Persist locally immediately for instant reload
|
||||
localStorage.setItem(STORAGE_KEY, code);
|
||||
|
||||
// Best-effort backend sync — don't block the reload on failure
|
||||
try {
|
||||
if (typeof postJSON === 'function') {
|
||||
await postJSON(CONFIG_ENDPOINT, { language: code });
|
||||
} else if (typeof secureFetch === 'function') {
|
||||
await secureFetch(CONFIG_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ language: code }),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
// Non-fatal: localStorage already holds the preference
|
||||
console.warn('[LanguageSelector] backend sync failed:', err);
|
||||
}
|
||||
|
||||
// Reload so the new language takes effect across the dashboard
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
function init() {
|
||||
injectStyles();
|
||||
|
||||
const current = getCurrentLanguage();
|
||||
const meta = langMeta(current);
|
||||
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'dc-lang-wrap';
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'dc-lang-btn';
|
||||
btn.type = 'button';
|
||||
btn.setAttribute('aria-label', 'Select language');
|
||||
btn.setAttribute('aria-haspopup', 'true');
|
||||
btn.setAttribute('aria-expanded', 'false');
|
||||
btn.title = 'Switch language';
|
||||
btn.innerHTML =
|
||||
'<span class="dc-lang-flag">' + meta.flag + '</span>' +
|
||||
'<span class="dc-lang-code">' + current.toUpperCase() + '</span>' +
|
||||
'<span class="dc-lang-caret">▼</span>';
|
||||
|
||||
const menu = buildMenu(current);
|
||||
|
||||
// Small label beneath, matching the "Customize Theme" link style
|
||||
const label = document.createElement('span');
|
||||
label.className = 'dc-lang-label-sm';
|
||||
label.textContent = 'Language';
|
||||
|
||||
wrap.appendChild(btn);
|
||||
wrap.appendChild(label);
|
||||
wrap.appendChild(menu);
|
||||
|
||||
// Toggle menu open/closed
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const isOpen = menu.classList.toggle('open');
|
||||
btn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
||||
});
|
||||
|
||||
// Option clicks
|
||||
menu.addEventListener('click', (e) => {
|
||||
const opt = e.target.closest('.dc-lang-option');
|
||||
if (!opt) return;
|
||||
const code = opt.dataset.lang;
|
||||
menu.classList.remove('open');
|
||||
btn.setAttribute('aria-expanded', 'false');
|
||||
selectLanguage(code);
|
||||
});
|
||||
|
||||
// Close when clicking outside
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!wrap.contains(e.target)) {
|
||||
menu.classList.remove('open');
|
||||
btn.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
});
|
||||
|
||||
// Close on Escape
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
menu.classList.remove('open');
|
||||
btn.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
});
|
||||
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Expose for programmatic use / testing
|
||||
window.DCLanguageSelector = {
|
||||
getCurrentLanguage,
|
||||
selectLanguage,
|
||||
LANGUAGES,
|
||||
STORAGE_KEY,
|
||||
};
|
||||
|
||||
// Auto-mount into the navbar next to the theme toggle.
|
||||
// The dashboard loads core.js (globals) before this deferred script, but the
|
||||
// navbar container is always present in the initial HTML.
|
||||
function mount() {
|
||||
const group = document.querySelector('.theme-toggle-group');
|
||||
if (group && group.parentNode) {
|
||||
// Insert immediately after the theme-toggle-group so it sits beside it
|
||||
group.parentNode.insertBefore(init(), group.nextSibling);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', mount);
|
||||
} else {
|
||||
mount();
|
||||
}
|
||||
|
||||
console.log('[LanguageSelector] Module loaded — current language:', getCurrentLanguage());
|
||||
})();
|
||||
Reference in New Issue
Block a user