feat: premium tier features — auto-backup scheduling, resource alerting, bundled workflows, one-click revert, notification manager
This commit is contained in:
+455
-333
@@ -94,7 +94,9 @@
|
||||
<!-- Tab bar -->
|
||||
<div class="panel-tabs">
|
||||
<button class="panel-tab active" data-panel="backup-manual">Manual</button>
|
||||
<button class="panel-tab" data-panel="backup-automated">Automated</button>
|
||||
<button class="panel-tab" data-panel="backup-schedules-tab">Schedules</button>
|
||||
<button class="panel-tab" data-panel="backup-disk-tab">Backups on Disk</button>
|
||||
<button class="panel-tab" data-panel="backup-pointintime-tab">Point-in-Time</button>
|
||||
<button class="panel-tab" data-panel="backup-history-tab">History</button>
|
||||
</div>
|
||||
|
||||
@@ -143,12 +145,32 @@
|
||||
<div id="backup-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 8px;"></div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Automated Backups -->
|
||||
<div id="backup-automated" class="panel-section">
|
||||
<div id="backup-schedule-container">
|
||||
<!-- Tab: Schedules (Premium) -->
|
||||
<div id="backup-schedules-tab" class="panel-section">
|
||||
<div id="backup-schedules-container">
|
||||
<div class="panel-empty">
|
||||
<span class="empty-icon">⏰</span>
|
||||
<span class="brand-spinner"></span> Loading backup schedule...
|
||||
<span class="brand-spinner"></span> Loading schedules...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Backups on Disk -->
|
||||
<div id="backup-disk-tab" class="panel-section">
|
||||
<div id="backup-disk-container">
|
||||
<div class="panel-empty">
|
||||
<span class="empty-icon">💾</span>
|
||||
<span class="brand-spinner"></span> Loading backup files...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Point-in-Time Restore -->
|
||||
<div id="backup-pointintime-tab" class="panel-section">
|
||||
<div id="pointintime-container">
|
||||
<div class="panel-empty">
|
||||
<span class="empty-icon">⏪</span>
|
||||
<span class="brand-spinner"></span> Loading...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -181,8 +203,10 @@
|
||||
var previewContent = document.getElementById('backup-preview-content');
|
||||
var restoreBtn = document.getElementById('backup-do-restore-btn');
|
||||
var resultDiv = document.getElementById('backup-result');
|
||||
var scheduleContainer = document.getElementById('backup-schedule-container');
|
||||
var scheduleContainer = document.getElementById('backup-schedules-container');
|
||||
var historyContainer = document.getElementById('backup-history-container');
|
||||
var diskContainer = document.getElementById('backup-disk-container');
|
||||
var pointintimeContainer = document.getElementById('pointintime-container');
|
||||
|
||||
var selectedBackup = null;
|
||||
|
||||
@@ -383,359 +407,272 @@
|
||||
restoreBtn.innerHTML = '⚡ Restore Everything';
|
||||
});
|
||||
|
||||
// === Automated Backups Tab ===
|
||||
// Holds the destination currently being edited in the form
|
||||
var currentDestination = { type: 'local' };
|
||||
|
||||
async function loadBackupSchedule() {
|
||||
// === Schedules Tab (Premium) ===
|
||||
async function loadSchedulesTab() {
|
||||
if (!scheduleContainer) return;
|
||||
scheduleContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||
try {
|
||||
var res = await fetch('/api/v1/backups/config');
|
||||
var res = await fetch('/api/v1/backups/schedule');
|
||||
var data = await res.json();
|
||||
if (!data.success) throw new Error(data.error || 'Failed to load config');
|
||||
var cfg = data.config?.backups || {};
|
||||
var autoKey = Object.keys(cfg)[0];
|
||||
var auto = autoKey ? cfg[autoKey] : null;
|
||||
|
||||
// Pull existing destination (first one) — fall back to local
|
||||
var existingDest = (auto?.destinations && auto.destinations[0]) || { type: 'local' };
|
||||
currentDestination = JSON.parse(JSON.stringify(existingDest));
|
||||
|
||||
var html = '<div style="padding: 16px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); margin-bottom: 16px;">';
|
||||
html += '<h4 style="margin: 0 0 12px; color: var(--accent); font-size: 0.9rem;">⏰ Backup Schedule</h4>';
|
||||
html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">';
|
||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Schedule:</label>';
|
||||
html += ' <select id="backup-schedule-select" style="width: 100%;">';
|
||||
html += ' <option value="disabled"' + (!auto?.enabled ? ' selected' : '') + '>Disabled</option>';
|
||||
html += ' <option value="hourly"' + (auto?.schedule === 'hourly' ? ' selected' : '') + '>Hourly</option>';
|
||||
html += ' <option value="daily"' + (auto?.schedule === 'daily' ? ' selected' : '') + '>Daily</option>';
|
||||
html += ' <option value="weekly"' + (auto?.schedule === 'weekly' ? ' selected' : '') + '>Weekly</option>';
|
||||
html += ' <option value="monthly"' + (auto?.schedule === 'monthly' ? ' selected' : '') + '>Monthly</option>';
|
||||
html += ' </select></div>';
|
||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Keep last:</label>';
|
||||
html += ' <select id="backup-retention-select" style="width: 100%;">';
|
||||
html += ' <option value="3"' + (auto?.retention?.keep === 3 ? ' selected' : '') + '>3 backups</option>';
|
||||
html += ' <option value="5"' + (!auto?.retention || auto?.retention?.keep === 5 ? ' selected' : '') + '>5 backups</option>';
|
||||
html += ' <option value="10"' + (auto?.retention?.keep === 10 ? ' selected' : '') + '>10 backups</option>';
|
||||
html += ' <option value="30"' + (auto?.retention?.keep === 30 ? ' selected' : '') + '>30 backups</option>';
|
||||
html += ' </select></div>';
|
||||
|
||||
if (data.premiumRequired) {
|
||||
scheduleContainer.innerHTML = '<div class="panel-empty" style="padding: 24px; text-align: center;">' +
|
||||
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
|
||||
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
|
||||
'<div style="font-size: 0.85rem; color: var(--muted);">Auto-backup scheduling requires a DashCaddy Premium subscription.</div>' +
|
||||
'<button onclick="showNotification(\'Upgrade to Premium to enable auto-backups!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
|
||||
'</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.success) throw new Error(data.error || 'Failed to load schedules');
|
||||
|
||||
var schedules = data.schedules || [];
|
||||
|
||||
if (schedules.length === 0) {
|
||||
scheduleContainer.innerHTML = '<div class="panel-empty">' +
|
||||
'<span class="empty-icon">⏰</span>' +
|
||||
'<div>No backup schedules configured</div>' +
|
||||
'<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Select apps below to enable auto-backup</div>' +
|
||||
'</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '<div style="display: flex; flex-direction: column; gap: 8px;">';
|
||||
for (var i = 0; i < schedules.length; i++) {
|
||||
var sch = schedules[i];
|
||||
var nextRunStr = sch.nextRun ? new Date(sch.nextRun).toLocaleString() : 'Not scheduled';
|
||||
var lastRunStr = sch.lastRun ? new Date(sch.lastRun).toLocaleString() : 'Never';
|
||||
|
||||
html += '<div style="padding: 12px 14px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">' +
|
||||
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">' +
|
||||
' <div style="font-weight: 600; font-size: 0.9rem;">' + escapeHtml(sch.appId) + '</div>' +
|
||||
' <label class="toggle-switch" style="display: flex; align-items: center; gap: 6px;">' +
|
||||
' <input type="checkbox" class="schedule-toggle" data-appid="' + escapeHtml(sch.appId) + '"' + (sch.enabled ? ' checked' : '') + ' />' +
|
||||
' <span style="font-size: 0.75rem; color: var(--muted);">' + (sch.enabled ? 'ON' : 'OFF') + '</span>' +
|
||||
' </label>' +
|
||||
'</div>' +
|
||||
'<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.8rem; margin-bottom: 10px;">' +
|
||||
' <div><span style="color: var(--muted);">Schedule:</span> <select class="schedule-select" data-appid="' + escapeHtml(sch.appId) + '" style="background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;">' +
|
||||
' <option value="hourly"' + (sch.schedule === 'hourly' ? ' selected' : '') + '>Hourly</option>' +
|
||||
' <option value="daily"' + (sch.schedule === 'daily' ? ' selected' : '') + '>Daily</option>' +
|
||||
' <option value="weekly"' + (sch.schedule === 'weekly' ? ' selected' : '') + '>Weekly</option>' +
|
||||
' <option value="monthly"' + (sch.schedule === 'monthly' ? ' selected' : '') + '>Monthly</option>' +
|
||||
' </select></div>' +
|
||||
' <div><span style="color: var(--muted);">Keep last:</span> <input type="number" class="retention-input" data-appid="' + escapeHtml(sch.appId) + '" value="' + (sch.retention?.keep || 7) + '" min="1" max="100" style="width: 50px; background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;" /></div>' +
|
||||
'</div>' +
|
||||
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 10px;">' +
|
||||
' <div>Next run: ' + escapeHtml(nextRunStr) + '</div>' +
|
||||
' <div>Last run: ' + escapeHtml(lastRunStr) + '</div>' +
|
||||
'</div>' +
|
||||
'<div style="display: flex; gap: 6px;">' +
|
||||
' <button class="schedule-run-now" data-appid="' + escapeHtml(sch.appId) + '" style="padding: 5px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--ok-fg) 20%, transparent); border: 1px solid var(--ok-fg); color: var(--ok-fg); border-radius: 6px; cursor: pointer;">▶️ Run Now</button>' +
|
||||
' <button class="schedule-delete" data-appid="' + escapeHtml(sch.appId) + '" style="padding: 5px 12px; font-size: 0.8rem; background: transparent; border: 1px solid var(--bad-fg); color: var(--bad-fg); border-radius: 6px; cursor: pointer;">🗑️ Remove</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
html += '</div>';
|
||||
html += '<div style="margin-top: 12px;">';
|
||||
html += ' <label style="display: flex; align-items: center; gap: 8px; font-size: 0.85rem; cursor: pointer;">';
|
||||
html += ' <input type="checkbox" id="backup-encrypt-toggle"' + (auto?.encrypt !== false ? ' checked' : '') + ' />';
|
||||
html += ' Encrypt backups';
|
||||
html += ' </label></div>';
|
||||
html += '<div style="display: flex; gap: 8px; margin-top: 12px;">';
|
||||
html += ' <button id="backup-save-schedule" style="padding: 8px 16px; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 6px; cursor: pointer; font-weight: 500;">Save Schedule</button>';
|
||||
html += ' <button id="backup-run-now" style="padding: 8px 16px; border-radius: 6px; cursor: pointer;">▶️ Run Backup Now</button>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
|
||||
// === Destination Section ===
|
||||
html += '<div style="padding: 16px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); margin-bottom: 16px;">';
|
||||
html += '<h4 style="margin: 0 0 12px; color: var(--accent); font-size: 0.9rem;">☁️ Backup Destination</h4>';
|
||||
html += '<div><label style="font-size: 0.8rem; color: var(--muted);">Where to store backups:</label>';
|
||||
html += ' <select id="backup-dest-type" style="width: 100%;">';
|
||||
html += ' <option value="local"' + (currentDestination.type === 'local' ? ' selected' : '') + '>💾 Local disk</option>';
|
||||
html += ' <option value="dropbox"' + (currentDestination.type === 'dropbox' ? ' selected' : '') + '>📦 Dropbox</option>';
|
||||
html += ' <option value="webdav"' + (currentDestination.type === 'webdav' ? ' selected' : '') + '>🌐 WebDAV (Nextcloud / ownCloud)</option>';
|
||||
html += ' <option value="sftp"' + (currentDestination.type === 'sftp' ? ' selected' : '') + '>🔐 SFTP</option>';
|
||||
html += ' </select></div>';
|
||||
html += '<div id="backup-dest-form" style="margin-top: 12px;"></div>';
|
||||
html += '<div id="backup-dest-result" style="display: none; margin-top: 10px; padding: 8px 10px; border-radius: 6px; font-size: 0.8rem;"></div>';
|
||||
html += '</div>';
|
||||
|
||||
html += '<div id="backup-schedule-result" style="display: none; margin-top: 12px; padding: 10px; border-radius: 8px; font-size: 0.85rem;"></div>';
|
||||
|
||||
// Add "Add Schedule" section at bottom
|
||||
html += '<div style="margin-top: 16px; padding: 16px; background: color-mix(in srgb, var(--accent) 5%, transparent); border-radius: 10px; border: 1px dashed var(--border);">' +
|
||||
'<h4 style="margin: 0 0 12px; font-size: 0.85rem; color: var(--muted);">➕ Add New Schedule</h4>' +
|
||||
'<div style="display: flex; gap: 8px; flex-wrap: wrap;">' +
|
||||
' <input type="text" id="new-schedule-appid" placeholder="App ID (e.g., plex, sonarr)" style="flex: 1; min-width: 150px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />' +
|
||||
' <select id="new-schedule-interval" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);">' +
|
||||
' <option value="hourly">Hourly</option>' +
|
||||
' <option value="daily" selected>Daily</option>' +
|
||||
' <option value="weekly">Weekly</option>' +
|
||||
' <option value="monthly">Monthly</option>' +
|
||||
' <option value="6h">Every 6 hours</option>' +
|
||||
' <option value="30m">Every 30 minutes</option>' +
|
||||
' </select>' +
|
||||
' <input type="number" id="new-schedule-retention" value="7" min="1" max="100" placeholder="Keep" style="width: 70px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />' +
|
||||
' <button id="add-schedule-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Add Schedule</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
|
||||
scheduleContainer.innerHTML = html;
|
||||
|
||||
document.getElementById('backup-save-schedule')?.addEventListener('click', saveSchedule);
|
||||
document.getElementById('backup-run-now')?.addEventListener('click', runBackupNow);
|
||||
|
||||
var destTypeSel = document.getElementById('backup-dest-type');
|
||||
destTypeSel?.addEventListener('change', function() {
|
||||
currentDestination = { type: destTypeSel.value };
|
||||
renderDestinationForm(destTypeSel.value);
|
||||
|
||||
// Wire up event listeners
|
||||
scheduleContainer.querySelectorAll('.schedule-toggle').forEach(function(toggle) {
|
||||
toggle.addEventListener('change', function() { updateSchedule(toggle.dataset.appid, { enabled: toggle.checked }); });
|
||||
});
|
||||
renderDestinationForm(currentDestination.type);
|
||||
scheduleContainer.querySelectorAll('.schedule-select').forEach(function(sel) {
|
||||
sel.addEventListener('change', function() { updateSchedule(sel.dataset.appid, { schedule: sel.value }); });
|
||||
});
|
||||
scheduleContainer.querySelectorAll('.retention-input').forEach(function(inp) {
|
||||
inp.addEventListener('change', function() { updateSchedule(inp.dataset.appid, { retention: { keep: parseInt(inp.value) || 7 } }); });
|
||||
});
|
||||
scheduleContainer.querySelectorAll('.schedule-run-now').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { runBackupNow(btn.dataset.appid); });
|
||||
});
|
||||
scheduleContainer.querySelectorAll('.schedule-delete').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { deleteSchedule(btn.dataset.appid); });
|
||||
});
|
||||
document.getElementById('add-schedule-btn')?.addEventListener('click', addNewSchedule);
|
||||
|
||||
} catch (e) {
|
||||
scheduleContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed to load schedule: ' + escapeHtml(e.message) + '</div>';
|
||||
scheduleContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed to load: ' + escapeHtml(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// Render the provider-specific form fields and load saved credentials (masked)
|
||||
async function renderDestinationForm(type) {
|
||||
var formEl = document.getElementById('backup-dest-form');
|
||||
if (!formEl) return;
|
||||
|
||||
if (type === 'local') {
|
||||
formEl.innerHTML = '<div style="font-size: 0.8rem; color: var(--muted); padding: 8px;">Backups are stored on the host filesystem. No additional configuration required.</div>';
|
||||
|
||||
async function updateSchedule(appId, updates) {
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/schedule', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ appId, ...updates })
|
||||
});
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
showNotification('Schedule updated for ' + appId, 'success');
|
||||
} else {
|
||||
showNotification('Update failed: ' + (data.error || 'Unknown'), 'error');
|
||||
loadSchedulesTab(); // Refresh on failure
|
||||
}
|
||||
} catch (e) {
|
||||
showNotification('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function runBackupNow(appId) {
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/backup/' + encodeURIComponent(appId), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
showNotification('Backup started for ' + appId + '!', 'success');
|
||||
} else {
|
||||
showNotification('Backup failed: ' + (data.error || 'Unknown'), 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showNotification('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSchedule(appId) {
|
||||
if (!confirm('Remove backup schedule for ' + appId + '?')) return;
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/schedule/' + encodeURIComponent(appId), { method: 'DELETE' });
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
showNotification('Schedule removed for ' + appId, 'success');
|
||||
loadSchedulesTab();
|
||||
} else {
|
||||
showNotification('Delete failed: ' + (data.error || 'Unknown'), 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showNotification('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function addNewSchedule() {
|
||||
var appId = document.getElementById('new-schedule-appid')?.value?.trim();
|
||||
var interval = document.getElementById('new-schedule-interval')?.value || 'daily';
|
||||
var retention = parseInt(document.getElementById('new-schedule-retention')?.value) || 7;
|
||||
|
||||
if (!appId) {
|
||||
showNotification('Please enter an App ID', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
|
||||
if (type === 'dropbox') {
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Access Token:</label>';
|
||||
html += '<input type="password" id="dest-dropbox-token" placeholder="sl.B..." style="width: 100%; margin-bottom: 8px;" />';
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Folder path:</label>';
|
||||
html += '<input type="text" id="dest-dropbox-path" placeholder="/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
||||
html += '<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 8px;">Generate a token at <a href="https://www.dropbox.com/developers/apps" target="_blank" style="color: var(--accent);">Dropbox App Console</a> with files.content.write + files.content.read scopes.</div>';
|
||||
} else if (type === 'webdav') {
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Server URL:</label>';
|
||||
html += '<input type="text" id="dest-webdav-url" placeholder="https://cloud.example.com/remote.php/dav/files/username" style="width: 100%; margin-bottom: 8px;" />';
|
||||
html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">';
|
||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Username:</label>';
|
||||
html += ' <input type="text" id="dest-webdav-username" style="width: 100%;" /></div>';
|
||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Password / App password:</label>';
|
||||
html += ' <input type="password" id="dest-webdav-password" style="width: 100%;" /></div>';
|
||||
html += '</div>';
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Folder path:</label>';
|
||||
html += '<input type="text" id="dest-webdav-path" placeholder="/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
||||
} else if (type === 'sftp') {
|
||||
html += '<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-bottom: 8px;">';
|
||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Host:</label>';
|
||||
html += ' <input type="text" id="dest-sftp-host" placeholder="backup.example.com" style="width: 100%;" /></div>';
|
||||
html += ' <div><label style="font-size: 0.8rem; color: var(--muted);">Port:</label>';
|
||||
html += ' <input type="number" id="dest-sftp-port" value="22" style="width: 100%;" /></div>';
|
||||
html += '</div>';
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Username:</label>';
|
||||
html += '<input type="text" id="dest-sftp-username" style="width: 100%; margin-bottom: 8px;" />';
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Auth method:</label>';
|
||||
html += '<select id="dest-sftp-authtype" style="width: 100%; margin-bottom: 8px;">';
|
||||
html += ' <option value="password">Password</option>';
|
||||
html += ' <option value="key">Private key</option>';
|
||||
html += '</select>';
|
||||
html += '<div id="dest-sftp-password-row"><label style="font-size: 0.8rem; color: var(--muted);">Password:</label>';
|
||||
html += ' <input type="password" id="dest-sftp-password" style="width: 100%; margin-bottom: 8px;" /></div>';
|
||||
html += '<div id="dest-sftp-key-row" style="display: none;"><label style="font-size: 0.8rem; color: var(--muted);">Private key (PEM):</label>';
|
||||
html += ' <textarea id="dest-sftp-privatekey" rows="4" style="width: 100%; font-family: monospace; font-size: 0.75rem; margin-bottom: 8px;" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"></textarea></div>';
|
||||
html += '<label style="font-size: 0.8rem; color: var(--muted);">Remote path:</label>';
|
||||
html += '<input type="text" id="dest-sftp-path" placeholder="/home/user/dashcaddy-backups" value="' + escapeHtml(currentDestination.path || '/home/user/dashcaddy-backups') + '" style="width: 100%; margin-bottom: 8px;" />';
|
||||
}
|
||||
|
||||
html += '<div style="display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap;">';
|
||||
html += ' <button id="dest-save-creds" style="padding: 6px 12px; font-size: 0.8rem; border-radius: 6px; cursor: pointer;">💾 Save Credentials</button>';
|
||||
html += ' <button id="dest-test-conn" style="padding: 6px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 6px; cursor: pointer;">🔌 Test Connection</button>';
|
||||
html += ' <button id="dest-clear-creds" style="padding: 6px 12px; font-size: 0.8rem; border-radius: 6px; cursor: pointer; color: var(--bad-fg);">🗑️ Clear</button>';
|
||||
html += '</div>';
|
||||
|
||||
formEl.innerHTML = html;
|
||||
|
||||
// SFTP auth type toggle
|
||||
if (type === 'sftp') {
|
||||
var authSel = document.getElementById('dest-sftp-authtype');
|
||||
var pwRow = document.getElementById('dest-sftp-password-row');
|
||||
var keyRow = document.getElementById('dest-sftp-key-row');
|
||||
authSel?.addEventListener('change', function() {
|
||||
if (authSel.value === 'key') { pwRow.style.display = 'none'; keyRow.style.display = ''; }
|
||||
else { pwRow.style.display = ''; keyRow.style.display = 'none'; }
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('dest-save-creds')?.addEventListener('click', function() { saveCredentials(type); });
|
||||
document.getElementById('dest-test-conn')?.addEventListener('click', function() { testDestination(type); });
|
||||
document.getElementById('dest-clear-creds')?.addEventListener('click', function() { clearCredentials(type); });
|
||||
|
||||
// Pull existing (masked) credentials
|
||||
await loadCredentials(type);
|
||||
}
|
||||
|
||||
function destResult(msg, ok) {
|
||||
var el = document.getElementById('backup-dest-result');
|
||||
if (!el) return;
|
||||
el.innerHTML = msg;
|
||||
el.style.display = 'block';
|
||||
el.style.background = ok ? 'color-mix(in srgb, var(--ok-fg) 15%, transparent)' : 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
||||
el.style.border = ok ? '1px solid var(--ok-fg)' : '1px solid var(--bad-fg)';
|
||||
}
|
||||
|
||||
async function loadCredentials(provider) {
|
||||
|
||||
try {
|
||||
var res = await fetch('/api/v1/backups/credentials/' + provider);
|
||||
var data = await res.json();
|
||||
if (!data.success || !data.credentials) return;
|
||||
var c = data.credentials;
|
||||
if (provider === 'dropbox') {
|
||||
var t = document.getElementById('dest-dropbox-token'); if (t && c.token) t.value = c.token;
|
||||
} else if (provider === 'webdav') {
|
||||
var u = document.getElementById('dest-webdav-url'); if (u && c.url) u.value = c.url;
|
||||
var n = document.getElementById('dest-webdav-username'); if (n && c.username) n.value = c.username;
|
||||
var p = document.getElementById('dest-webdav-password'); if (p && c.password) p.value = c.password;
|
||||
} else if (provider === 'sftp') {
|
||||
var h = document.getElementById('dest-sftp-host'); if (h && c.host) h.value = c.host;
|
||||
var po = document.getElementById('dest-sftp-port'); if (po && c.port) po.value = c.port;
|
||||
var un = document.getElementById('dest-sftp-username'); if (un && c.username) un.value = c.username;
|
||||
var pw = document.getElementById('dest-sftp-password'); if (pw && c.password) pw.value = c.password;
|
||||
var pk = document.getElementById('dest-sftp-privatekey'); if (pk && c.privateKey) pk.value = c.privateKey;
|
||||
if (c.privateKey) {
|
||||
var sel = document.getElementById('dest-sftp-authtype');
|
||||
if (sel) { sel.value = 'key'; sel.dispatchEvent(new Event('change')); }
|
||||
}
|
||||
}
|
||||
} catch (e) { /* no creds yet — silent */ }
|
||||
}
|
||||
|
||||
function collectCredentials(provider) {
|
||||
if (provider === 'dropbox') {
|
||||
return { token: document.getElementById('dest-dropbox-token')?.value };
|
||||
}
|
||||
if (provider === 'webdav') {
|
||||
return {
|
||||
url: document.getElementById('dest-webdav-url')?.value,
|
||||
username: document.getElementById('dest-webdav-username')?.value,
|
||||
password: document.getElementById('dest-webdav-password')?.value
|
||||
};
|
||||
}
|
||||
if (provider === 'sftp') {
|
||||
var auth = document.getElementById('dest-sftp-authtype')?.value;
|
||||
var creds = {
|
||||
host: document.getElementById('dest-sftp-host')?.value,
|
||||
port: parseInt(document.getElementById('dest-sftp-port')?.value) || 22,
|
||||
username: document.getElementById('dest-sftp-username')?.value
|
||||
};
|
||||
if (auth === 'key') creds.privateKey = document.getElementById('dest-sftp-privatekey')?.value;
|
||||
else creds.password = document.getElementById('dest-sftp-password')?.value;
|
||||
return creds;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function saveCredentials(provider) {
|
||||
try {
|
||||
var creds = collectCredentials(provider);
|
||||
var res = await secureFetch('/api/v1/backups/credentials/' + provider, {
|
||||
var res = await secureFetch('/api/v1/backups/schedule', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(creds)
|
||||
});
|
||||
var data = await res.json();
|
||||
destResult(data.success ? '✅ Credentials saved' : '⚠️ ' + escapeHtml(data.error || 'Failed'), data.success);
|
||||
} catch (e) {
|
||||
destResult('❌ ' + escapeHtml(e.message), false);
|
||||
}
|
||||
}
|
||||
|
||||
async function clearCredentials(provider) {
|
||||
if (!confirm('Delete saved ' + provider + ' credentials?')) return;
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/credentials/' + provider, { method: 'DELETE' });
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
destResult('✅ Credentials cleared', true);
|
||||
renderDestinationForm(provider);
|
||||
} else {
|
||||
destResult('⚠️ ' + escapeHtml(data.error || 'Failed'), false);
|
||||
}
|
||||
} catch (e) { destResult('❌ ' + escapeHtml(e.message), false); }
|
||||
}
|
||||
|
||||
function buildDestination(type) {
|
||||
var dest = { type: type };
|
||||
if (type === 'local') return dest;
|
||||
if (type === 'dropbox') dest.path = document.getElementById('dest-dropbox-path')?.value || '/dashcaddy-backups';
|
||||
else if (type === 'webdav') dest.path = document.getElementById('dest-webdav-path')?.value || '/dashcaddy-backups';
|
||||
else if (type === 'sftp') dest.path = document.getElementById('dest-sftp-path')?.value || '/dashcaddy-backups';
|
||||
return dest;
|
||||
}
|
||||
|
||||
async function testDestination(type) {
|
||||
destResult('<span class="brand-spinner"></span> Testing connection...', true);
|
||||
try {
|
||||
var dest = buildDestination(type);
|
||||
var res = await secureFetch('/api/v1/backups/test-destination', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(dest)
|
||||
body: JSON.stringify({ appId, schedule: interval, retention: { keep: retention }, enabled: true })
|
||||
});
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
var ms = data.elapsedMs ? ' (' + data.elapsedMs + 'ms)' : '';
|
||||
destResult('✅ Connection OK' + ms + ' — write/read/delete probe succeeded', true);
|
||||
showNotification('Schedule created for ' + appId, 'success');
|
||||
loadSchedulesTab();
|
||||
// Clear inputs
|
||||
var appIdInput = document.getElementById('new-schedule-appid');
|
||||
if (appIdInput) appIdInput.value = '';
|
||||
} else {
|
||||
destResult('❌ ' + escapeHtml(data.error || 'Connection failed'), false);
|
||||
}
|
||||
} catch (e) { destResult('❌ ' + escapeHtml(e.message), false); }
|
||||
}
|
||||
|
||||
async function saveSchedule() {
|
||||
var schedule = document.getElementById('backup-schedule-select')?.value;
|
||||
var retention = parseInt(document.getElementById('backup-retention-select')?.value) || 5;
|
||||
var encrypt = document.getElementById('backup-encrypt-toggle')?.checked ?? true;
|
||||
var destType = document.getElementById('backup-dest-type')?.value || 'local';
|
||||
var resultEl = document.getElementById('backup-schedule-result');
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
backups: {
|
||||
auto: {
|
||||
enabled: schedule !== 'disabled',
|
||||
schedule: schedule === 'disabled' ? 'daily' : schedule,
|
||||
include: ['all'],
|
||||
encrypt: encrypt,
|
||||
verify: true,
|
||||
retention: { keep: retention },
|
||||
destinations: [buildDestination(destType)]
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
var data = await res.json();
|
||||
if (resultEl) {
|
||||
resultEl.innerHTML = data.success ? '✅ Schedule saved' : '⚠️ ' + escapeHtml(data.error);
|
||||
resultEl.style.display = 'block';
|
||||
resultEl.style.background = data.success ? 'color-mix(in srgb, var(--ok-fg) 15%, transparent)' : 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
||||
resultEl.style.border = data.success ? '1px solid var(--ok-fg)' : '1px solid var(--bad-fg)';
|
||||
setTimeout(function() { if (resultEl) resultEl.style.display = 'none'; }, 3000);
|
||||
showNotification('Failed: ' + (data.error || 'Unknown'), 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
if (resultEl) {
|
||||
resultEl.innerHTML = '❌ ' + escapeHtml(e.message);
|
||||
resultEl.style.display = 'block';
|
||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
||||
}
|
||||
showNotification('Error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function runBackupNow() {
|
||||
var btn = document.getElementById('backup-run-now');
|
||||
var resultEl = document.getElementById('backup-schedule-result');
|
||||
var destType = document.getElementById('backup-dest-type')?.value || 'local';
|
||||
if (btn) { btn.disabled = true; btn.innerHTML = '<span class="brand-spinner"></span> Running...'; }
|
||||
|
||||
// === Backups on Disk Tab ===
|
||||
async function loadDiskBackups() {
|
||||
if (!diskContainer) return;
|
||||
diskContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/execute', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ include: ['all'], destinations: [buildDestination(destType)] })
|
||||
});
|
||||
var res = await fetch('/api/v1/backups/files');
|
||||
var data = await res.json();
|
||||
if (resultEl) {
|
||||
if (data.success) {
|
||||
var sizeMB = data.backup?.size ? (data.backup.size / 1024 / 1024).toFixed(2) : '?';
|
||||
resultEl.innerHTML = '✅ Backup complete (' + sizeMB + ' MB)';
|
||||
resultEl.style.background = 'color-mix(in srgb, var(--ok-fg) 15%, transparent)';
|
||||
resultEl.style.border = '1px solid var(--ok-fg)';
|
||||
} else {
|
||||
resultEl.innerHTML = '⚠️ ' + escapeHtml(data.error);
|
||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
||||
if (!data.success) throw new Error(data.error || 'Failed to load');
|
||||
|
||||
var files = data.files || [];
|
||||
|
||||
if (files.length === 0) {
|
||||
diskContainer.innerHTML = '<div class="panel-empty">' +
|
||||
'<span class="empty-icon">💾</span>' +
|
||||
'<div>No backup files on disk</div>' +
|
||||
'<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Run a backup to create backup files</div>' +
|
||||
'</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by appId
|
||||
var byApp = {};
|
||||
for (var i = 0; i < files.length; i++) {
|
||||
var f = files[i];
|
||||
var appId = f.appId || 'unknown';
|
||||
if (!byApp[appId]) byApp[appId] = [];
|
||||
byApp[appId].push(f);
|
||||
}
|
||||
|
||||
var html = '<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 12px;">' + files.length + ' backup file(s) across ' + Object.keys(byApp).length + ' app(s)</div>';
|
||||
html += '<div style="display: flex; flex-direction: column; gap: 12px;">';
|
||||
|
||||
var appIds = Object.keys(byApp).sort();
|
||||
for (var a = 0; a < appIds.length; a++) {
|
||||
var appId = appIds[a];
|
||||
var appFiles = byApp[appId];
|
||||
html += '<div style="background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); overflow: hidden;">' +
|
||||
'<div style="padding: 8px 12px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-bottom: 1px solid var(--border); font-weight: 600; font-size: 0.85rem;">' +
|
||||
escapeHtml(appId) + ' <span style="font-weight: normal; color: var(--muted); font-size: 0.75rem;">(' + appFiles.length + ' backup(s))</span>' +
|
||||
'</div>';
|
||||
|
||||
for (var j = 0; j < appFiles.length; j++) {
|
||||
var f = appFiles[j];
|
||||
var dateStr = new Date(f.timestamp).toLocaleString();
|
||||
html += '<div style="padding: 10px 12px; border-bottom: 1px solid var(--border);">' +
|
||||
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">' +
|
||||
' <div style="font-weight: 500; font-size: 0.85rem;">' + escapeHtml(f.name) + '</div>' +
|
||||
' <div style="font-size: 0.75rem; color: var(--muted);">' + f.sizeFormatted + '</div>' +
|
||||
'</div>' +
|
||||
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + dateStr + '</div>' +
|
||||
'<div style="display: flex; gap: 6px;">' +
|
||||
' <button class="disk-compare-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 3px 8px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>' +
|
||||
' <button class="disk-restore-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 3px 8px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
resultEl.style.display = 'block';
|
||||
html += '</div>';
|
||||
}
|
||||
loadBackupHistory();
|
||||
} catch (e) {
|
||||
if (resultEl) {
|
||||
resultEl.innerHTML = '❌ ' + escapeHtml(e.message);
|
||||
resultEl.style.display = 'block';
|
||||
resultEl.style.background = 'color-mix(in srgb, var(--bad-fg) 15%, transparent)';
|
||||
resultEl.style.border = '1px solid var(--bad-fg)';
|
||||
}
|
||||
}
|
||||
if (btn) { btn.disabled = false; btn.innerHTML = '▶️ Run Backup Now'; }
|
||||
}
|
||||
html += '</div>';
|
||||
|
||||
diskContainer.innerHTML = html;
|
||||
|
||||
// Wire up buttons
|
||||
diskContainer.querySelectorAll('.disk-compare-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { compareBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||
});
|
||||
diskContainer.querySelectorAll('.disk-restore-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { restoreBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||
});
|
||||
} catch (e) {
|
||||
diskContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// === Backup History Tab ===
|
||||
async function loadBackupHistory() {
|
||||
if (!historyContainer) return;
|
||||
@@ -794,6 +731,191 @@
|
||||
};
|
||||
|
||||
// Lazy-load tabs
|
||||
document.querySelector('[data-panel="backup-automated"]')?.addEventListener('click', loadBackupSchedule);
|
||||
document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener('click', loadSchedulesTab);
|
||||
document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener('click', loadDiskBackups);
|
||||
document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener('click', loadPointInTimeTab);
|
||||
document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener('click', loadBackupHistory);
|
||||
|
||||
// ===== Point-in-Time Restore Tab =====
|
||||
async function loadPointInTimeTab() {
|
||||
if (!pointintimeContainer) return;
|
||||
|
||||
// Check premium
|
||||
try {
|
||||
var licenseRes = await fetch('/api/v1/license/status');
|
||||
var licenseData = await licenseRes.json();
|
||||
if (licenseData.tier !== 'premium') {
|
||||
pointintimeContainer.innerHTML = '<div class="panel-empty" style="padding: 24px; text-align: center;">' +
|
||||
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
|
||||
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
|
||||
'<div style="font-size: 0.85rem; color: var(--muted);">Point-in-time restore requires DashCaddy Premium with auto-backup enabled.</div>' +
|
||||
'<button onclick="showNotification(\'Upgrade to Premium for point-in-time restore!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
|
||||
'</div>';
|
||||
return;
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
pointintimeContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
|
||||
|
||||
try {
|
||||
// Fetch services for dropdown
|
||||
var servicesRes = await fetch('/api/v1/services');
|
||||
var servicesData = await servicesRes.json();
|
||||
var services = servicesData.services || [];
|
||||
|
||||
if (services.length === 0) {
|
||||
pointintimeContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">📦</span> No apps deployed yet</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '<div style="padding: 8px 0 12px;">' +
|
||||
'<div style="display: flex; gap: 8px; align-items: center; margin-bottom: 12px;">' +
|
||||
' <label style="font-size: 0.85rem; color: var(--muted); white-space: nowrap;">App:</label>' +
|
||||
' <select id="pit-app-select" style="flex: 1; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base); max-width: 240px;">';
|
||||
for (var i = 0; i < services.length; i++) {
|
||||
html += '<option value="' + escapeHtml(services[i].id || services[i].name || '') + '">' +
|
||||
escapeHtml(services[i].name || services[i].id || '') + '</option>';
|
||||
}
|
||||
html += '</select>' +
|
||||
' <button id="pit-load-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Load Backups</button>' +
|
||||
'</div>' +
|
||||
'<div id="pit-backups-list" style="max-height: 320px; overflow-y: auto;"></div>' +
|
||||
'</div>';
|
||||
|
||||
pointintimeContainer.innerHTML = html;
|
||||
|
||||
document.getElementById('pit-load-btn')?.addEventListener('click', function() {
|
||||
var appId = document.getElementById('pit-app-select')?.value;
|
||||
if (appId) loadPointInTimeBackups(appId);
|
||||
});
|
||||
} catch (e) {
|
||||
pointintimeContainer.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPointInTimeBackups(appId) {
|
||||
var listEl = document.getElementById('pit-backups-list');
|
||||
if (!listEl) return;
|
||||
|
||||
listEl.innerHTML = '<div style="padding: 20px; text-align: center;"><span class="brand-spinner"></span> Loading backups...</div>';
|
||||
|
||||
try {
|
||||
var res = await fetch('/api/v1/backups/files/' + encodeURIComponent(appId));
|
||||
var data = await res.json();
|
||||
|
||||
if (!data.success || !data.files || data.files.length === 0) {
|
||||
listEl.innerHTML = '<div class="panel-empty"><span class="empty-icon">💾</span> No backup files for ' + escapeHtml(appId) + '</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + data.files.length + ' backup(s)</div>' +
|
||||
'<div style="display: flex; flex-direction: column; gap: 6px;">';
|
||||
|
||||
for (var i = 0; i < data.files.length; i++) {
|
||||
var f = data.files[i];
|
||||
var dateStr = new Date(f.timestamp).toLocaleString();
|
||||
html += '<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">' +
|
||||
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">' +
|
||||
' <div style="font-weight: 500; font-size: 0.85rem;">' + escapeHtml(f.name) + '</div>' +
|
||||
' <div style="font-size: 0.75rem; color: var(--muted);">' + f.sizeFormatted + '</div>' +
|
||||
'</div>' +
|
||||
'<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">' + dateStr + '</div>' +
|
||||
'<div style="display: flex; gap: 6px;">' +
|
||||
' <button class="pit-compare-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 4px 10px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>' +
|
||||
' <button class="pit-restore-btn" data-appid="' + escapeHtml(appId) + '" data-filename="' + escapeHtml(f.name) + '" style="padding: 4px 10px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
html += '</div>';
|
||||
listEl.innerHTML = html;
|
||||
|
||||
// Wire up buttons
|
||||
listEl.querySelectorAll('.pit-compare-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { compareBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||
});
|
||||
listEl.querySelectorAll('.pit-restore-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() { restoreBackupFile(btn.dataset.appid, btn.dataset.filename); });
|
||||
});
|
||||
} catch (e) {
|
||||
listEl.innerHTML = '<div class="panel-empty" style="color: var(--bad-fg);">Failed: ' + escapeHtml(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function compareBackupFile(appId, filename) {
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/backups/compare/' + encodeURIComponent(filename), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
var data = await res.json();
|
||||
if (!data.success) {
|
||||
showNotification('Compare failed: ' + (data.error || 'Unknown'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
var diff = data.diff;
|
||||
var html = '<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;" id="compare-overlay">' +
|
||||
'<div style="background: var(--base); border-radius: 12px; max-width: 600px; width: 90%; max-height: 80vh; overflow: auto; padding: 20px; border: 1px solid var(--border);">' +
|
||||
'<h4 style="margin: 0 0 16px;">📊 Compare: ' + escapeHtml(filename) + '</h4>' +
|
||||
'<div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 16px;">Size: ' + (diff.sizeFormatted || '?') + ' | Created: ' + new Date(diff.timestamp).toLocaleString() + '</div>';
|
||||
|
||||
if (diff.services) {
|
||||
var svcChanged = diff.services.hasChanges ? '🔴' : '🟢';
|
||||
html += '<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);">' +
|
||||
'<div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">' + svcChanged + ' Services (backup vs current)</div>' +
|
||||
'<div style="font-size: 0.8rem; color: var(--muted);">Backup: ' + diff.services.backupCount + ' services | Current: ' + diff.services.currentCount + ' services</div>';
|
||||
if (diff.services.hasChanges) {
|
||||
html += '<div style="margin-top: 6px; font-size: 0.8rem; color: #f39c12;">Services differ — restoring will replace current configuration</div>';
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
if (diff.config) {
|
||||
var cfgChanged = diff.config.hasChanges ? '🔴' : '🟢';
|
||||
html += '<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);">' +
|
||||
'<div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">' + cfgChanged + ' Configuration</div>';
|
||||
if (diff.config.hasChanges) {
|
||||
html += '<div style="font-size: 0.8rem; color: #f39c12;">Configuration differs — restoring will replace current settings</div>';
|
||||
} else {
|
||||
html += '<div style="font-size: 0.8rem; color: var(--ok-fg);">No changes</div>';
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
html += '<button id="compare-close-btn" style="padding: 8px 20px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Close</button>' +
|
||||
'</div></div>';
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', html);
|
||||
document.getElementById('compare-close-btn')?.addEventListener('click', function() {
|
||||
document.getElementById('compare-overlay')?.remove();
|
||||
});
|
||||
document.getElementById('compare-overlay')?.addEventListener('click', function(e) {
|
||||
if (e.target === this) this.remove();
|
||||
});
|
||||
} catch (e) {
|
||||
showNotification('Compare error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreBackupFile(appId, filename) {
|
||||
if (!confirm('Restore ' + filename + ' for ' + appId + '?\n\nThis will replace current configuration, credentials, and data. Containers will be restarted.')) return;
|
||||
|
||||
try {
|
||||
var res = await secureFetch('/api/v1/apps/' + encodeURIComponent(appId) + '/revert/' + encodeURIComponent(filename), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ restartContainers: true })
|
||||
});
|
||||
var data = await res.json();
|
||||
if (data.success) {
|
||||
showNotification(appId + ' restored to ' + filename, 'success');
|
||||
setTimeout(function() { location.reload(); }, 1500);
|
||||
} else {
|
||||
showNotification('Restore failed: ' + (data.error || 'Unknown'), 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showNotification('Restore error: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
// ========== BUNDLED WORKFLOWS ==========
|
||||
(function() {
|
||||
const WORKFLOW_DEFINITIONS = {
|
||||
'auto-restart-on-crash': {
|
||||
name: 'Auto-Restart on Crash',
|
||||
icon: '🔄',
|
||||
description: 'Automatically restart a container when it goes down',
|
||||
trigger: 'container-down',
|
||||
actions: 'restart + notify'
|
||||
},
|
||||
'backup-before-update': {
|
||||
name: 'Backup Before Update',
|
||||
icon: '💾',
|
||||
description: 'Create a backup before any app update',
|
||||
trigger: 'pre-update',
|
||||
actions: 'backup + notify'
|
||||
},
|
||||
'health-check-on-interval': {
|
||||
name: 'Periodic Health Check',
|
||||
icon: '🏥',
|
||||
description: 'Run health checks every 15 minutes and alert if degraded',
|
||||
trigger: 'scheduled (15m)',
|
||||
actions: 'health-check + alert'
|
||||
},
|
||||
'disk-space-alert': {
|
||||
name: 'Disk Space Alert',
|
||||
icon: '⚠️',
|
||||
description: 'Alert when disk usage exceeds 80%',
|
||||
trigger: 'resource-alert',
|
||||
actions: 'notify'
|
||||
},
|
||||
'weekly-container-report': {
|
||||
name: 'Weekly Container Report',
|
||||
icon: '📊',
|
||||
description: 'Send a weekly summary of container status and resource usage',
|
||||
trigger: 'scheduled (weekly)',
|
||||
actions: 'collect metrics + report'
|
||||
}
|
||||
};
|
||||
|
||||
let isPremium = false;
|
||||
|
||||
// === CHECK PREMIUM ===
|
||||
async function checkPremium() {
|
||||
try {
|
||||
const resp = await fetch('/api/v1/license/feature/workflows');
|
||||
const data = await resp.json();
|
||||
isPremium = data.available;
|
||||
} catch {
|
||||
isPremium = false;
|
||||
}
|
||||
return isPremium;
|
||||
}
|
||||
|
||||
// === RENDER WORKFLOW CARD ===
|
||||
function renderWorkflowCard(workflow) {
|
||||
const def = WORKFLOW_DEFINITIONS[workflow.id] || {
|
||||
name: workflow.name || workflow.id,
|
||||
icon: '⚡',
|
||||
description: workflow.description || '',
|
||||
trigger: workflow.trigger || 'unknown',
|
||||
actions: workflow.actions ? workflow.actions.map(a => a.type).join(' + ') : ''
|
||||
};
|
||||
|
||||
const locked = !isPremium;
|
||||
const cardClass = locked ? 'workflow-card locked' : 'workflow-card';
|
||||
|
||||
return `<div class="${cardClass}" data-workflow="${workflow.id}">
|
||||
<div class="workflow-header">
|
||||
<span class="workflow-name">${def.icon} ${escapeHtml(def.name)}</span>
|
||||
<label class="toggle-switch">
|
||||
<input type="checkbox" class="workflow-toggle" data-workflow="${workflow.id}" ${workflow.enabled ? 'checked' : ''} ${locked ? 'disabled' : ''} />
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="workflow-desc">${escapeHtml(def.description)}</p>
|
||||
<div class="workflow-meta">
|
||||
<span class="workflow-trigger">⚡ Trigger: ${escapeHtml(def.trigger)}</span>
|
||||
<span class="workflow-actions">▶ Actions: ${escapeHtml(def.actions)}</span>
|
||||
</div>
|
||||
${locked ? `<div class="workflow-locked-overlay">
|
||||
<span class="lock-icon">🔒</span>
|
||||
<span class="lock-text">Upgrade to Enable</span>
|
||||
</div>` : ''}
|
||||
<button class="btn-run-now" data-workflow="${workflow.id}" ${locked ? 'disabled' : ''}>
|
||||
▶ Run Now
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// === LOAD WORKFLOWS TAB ===
|
||||
async function loadWorkflowsTab() {
|
||||
const container = document.getElementById('workflow-list-container');
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading workflows...</div>';
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/v1/workflows');
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.success && data.workflows) {
|
||||
if (data.workflows.length === 0) {
|
||||
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚡</span>No workflows configured</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
for (const workflow of data.workflows) {
|
||||
html += renderWorkflowCard(workflow);
|
||||
}
|
||||
|
||||
// Add non-premium banner
|
||||
if (!isPremium) {
|
||||
html += `<div class="accent-info-box" style="margin-top: 16px; text-align: center;">
|
||||
<span>🔒 Upgrade to unlock automated workflows</span>
|
||||
<button onclick="showNotification('Upgrade to Premium to enable workflows!', 'info'); scrollToSection('license');" style="margin-left: 12px; padding: 6px 16px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
container.innerHTML = `<div class="workflow-list">${html}</div>`;
|
||||
wireWorkflowEvents();
|
||||
} else {
|
||||
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚠️</span>Failed to load workflows</div>';
|
||||
}
|
||||
} catch (error) {
|
||||
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚠️</span>Error loading workflows: ' + escapeHtml(error.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// === LOAD HISTORY TAB ===
|
||||
async function loadHistoryTab() {
|
||||
const container = document.getElementById('workflow-history-body');
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px;"><span class="brand-spinner"></span> Loading history...</td></tr>';
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/v1/workflows/history?limit=100');
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.success && data.history && data.history.length > 0) {
|
||||
let html = '';
|
||||
for (const entry of data.history) {
|
||||
const time = new Date(entry.timestamp).toLocaleString();
|
||||
const duration = entry.duration ? entry.duration + 'ms' : '-';
|
||||
const resultClass = entry.success ? 'result-success' : 'result-failure';
|
||||
const resultText = entry.success ? '✓ Success' : '✗ Failed';
|
||||
|
||||
html += `<tr>
|
||||
<td>${escapeHtml(time)}</td>
|
||||
<td>${escapeHtml(entry.workflowName || entry.workflowId)}</td>
|
||||
<td>${escapeHtml(entry.trigger || 'manual')}</td>
|
||||
<td class="${resultClass}">${resultText}</td>
|
||||
<td>${escapeHtml(duration)}</td>
|
||||
</tr>`;
|
||||
}
|
||||
container.innerHTML = html;
|
||||
} else {
|
||||
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: var(--muted);">No workflow history yet</td></tr>';
|
||||
}
|
||||
} catch (error) {
|
||||
container.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: var(--bad-fg);">Error loading history</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
// === WIRE WORKFLOW EVENTS ===
|
||||
function wireWorkflowEvents() {
|
||||
// Toggle switches
|
||||
document.querySelectorAll('.workflow-toggle').forEach(toggle => {
|
||||
toggle.addEventListener('change', async function() {
|
||||
const workflowId = this.dataset.workflow;
|
||||
const enabled = this.checked;
|
||||
const endpoint = enabled ? 'enable' : 'disable';
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/v1/workflows/${workflowId}/${endpoint}`, { method: 'POST' });
|
||||
const data = await resp.json();
|
||||
if (!data.success) {
|
||||
showNotification(`Failed to ${endpoint} workflow`, 'error', 3000);
|
||||
this.checked = !enabled; // revert
|
||||
}
|
||||
} catch (error) {
|
||||
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||
this.checked = !enabled; // revert
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Run Now buttons
|
||||
document.querySelectorAll('.btn-run-now').forEach(btn => {
|
||||
btn.addEventListener('click', async function() {
|
||||
const workflowId = this.dataset.workflow;
|
||||
const originalText = this.innerHTML;
|
||||
this.innerHTML = '<span class="brand-spinner"></span>';
|
||||
this.disabled = true;
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/v1/workflows/${workflowId}/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ trigger: 'manual' })
|
||||
});
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.success) {
|
||||
showNotification(`Workflow "${WORKFLOW_DEFINITIONS[workflowId]?.name || workflowId}" executed successfully`, 'success', 3000);
|
||||
} else {
|
||||
showNotification(`Workflow failed: ${data.error || 'Unknown error'}`, 'error', 4000);
|
||||
}
|
||||
} catch (error) {
|
||||
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||
} finally {
|
||||
this.innerHTML = originalText;
|
||||
this.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// === TAB SWITCHING ===
|
||||
function setupTabSwitching() {
|
||||
document.querySelectorAll('.workflows-tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const panelId = this.dataset.panel;
|
||||
|
||||
// Update tab buttons
|
||||
document.querySelectorAll('.workflows-tab-btn').forEach(b => b.classList.remove('active'));
|
||||
this.classList.add('active');
|
||||
|
||||
// Update panels
|
||||
document.querySelectorAll('.workflow-panel').forEach(p => p.classList.remove('active'));
|
||||
document.getElementById(panelId)?.classList.add('active');
|
||||
|
||||
// Load data for the active panel
|
||||
if (panelId === 'workflows-list-panel') {
|
||||
loadWorkflowsTab();
|
||||
} else if (panelId === 'workflows-history-panel') {
|
||||
loadHistoryTab();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// === INJECT MODAL HTML ===
|
||||
injectModal('bundled-workflows-modal', `<div id="bundled-workflows-modal" class="weather-modal">
|
||||
<div class="weather-modal-content" style="min-width: 600px; max-width: 750px;">
|
||||
<h3>⚡ Bundled Workflows</h3>
|
||||
<p class="modal-subtitle">
|
||||
Automated workflows to keep your system running smoothly
|
||||
</p>
|
||||
|
||||
<!-- Tab bar -->
|
||||
<div class="panel-tabs">
|
||||
<button class="workflows-tab-btn panel-tab active" data-panel="workflows-list-panel">Workflows</button>
|
||||
<button class="workflows-tab-btn panel-tab" data-panel="workflows-history-panel">History</button>
|
||||
</div>
|
||||
|
||||
<!-- Tab: Workflows -->
|
||||
<div id="workflows-list-panel" class="workflow-panel panel-section active">
|
||||
<div id="workflow-list-container">
|
||||
<div class="panel-empty">
|
||||
<span class="brand-spinner"></span> Loading workflows...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tab: History -->
|
||||
<div id="workflows-history-panel" class="workflow-panel panel-section">
|
||||
<div class="workflow-history">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Time</th>
|
||||
<th>Workflow</th>
|
||||
<th>Trigger</th>
|
||||
<th>Result</th>
|
||||
<th>Duration</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="workflow-history-body">
|
||||
<!-- populated from API -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Close Button -->
|
||||
<div class="weather-modal-buttons modal-footer-bar">
|
||||
<button id="workflows-cancel">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`);
|
||||
|
||||
const modal = document.getElementById('bundled-workflows-modal');
|
||||
const openBtn = document.getElementById('bundled-workflows-btn');
|
||||
const cancelBtn = document.getElementById('workflows-cancel');
|
||||
|
||||
// === STYLES ===
|
||||
const style = document.createElement('style');
|
||||
style.textContent = `
|
||||
.workflow-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.workflow-card {
|
||||
position: relative;
|
||||
padding: 16px;
|
||||
background: var(--card-base);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.workflow-card:hover {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.workflow-card.locked {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.workflow-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.workflow-name {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.workflow-desc {
|
||||
font-size: 0.82rem;
|
||||
color: var(--muted);
|
||||
margin: 0 0 10px 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.workflow-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
font-size: 0.75rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.workflow-meta span {
|
||||
padding: 2px 8px;
|
||||
background: var(--base);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.workflow-locked-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0,0,0,0.5);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.lock-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.lock-text {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: #f39c12;
|
||||
}
|
||||
|
||||
.workflow-history {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.workflow-history table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.workflow-history th {
|
||||
text-align: left;
|
||||
padding: 8px 10px;
|
||||
background: var(--base);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-weight: 600;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.workflow-history td {
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.result-success {
|
||||
color: var(--ok-fg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.result-failure {
|
||||
color: var(--bad-fg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.workflow-panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.workflow-panel.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.accent-info-box {
|
||||
padding: 12px 16px;
|
||||
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
// === MODAL EVENTS ===
|
||||
openBtn?.addEventListener('click', async function() {
|
||||
modal.classList.add('show');
|
||||
await checkPremium();
|
||||
loadWorkflowsTab();
|
||||
});
|
||||
|
||||
setupTabSwitching();
|
||||
|
||||
// Close on cancel
|
||||
cancelBtn?.addEventListener('click', function() {
|
||||
modal.classList.remove('show');
|
||||
});
|
||||
|
||||
// Wire modal escape key / click outside
|
||||
wireModal(modal, cancelBtn);
|
||||
})();
|
||||
@@ -168,6 +168,9 @@
|
||||
<label class="checkbox-label-sm">
|
||||
<input type="checkbox" id="event-deploy-failed" checked /> Deployment Failed
|
||||
</label>
|
||||
<label class="checkbox-label-sm" style="grid-column: 1 / -1;">
|
||||
<input type="checkbox" id="event-resource-alert" checked /> Resource Alerts
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- History -->
|
||||
@@ -175,9 +178,11 @@
|
||||
<div id="notification-history" style="max-height: 150px; overflow-y: auto; padding: 8px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;">
|
||||
<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>
|
||||
</div>
|
||||
<div id="last-notification-sent" style="font-size: 0.75rem; color: var(--muted); text-align: center; margin-top: 6px;"></div>
|
||||
|
||||
<!-- Buttons -->
|
||||
<div class="weather-modal-buttons modal-footer-bar">
|
||||
<button id="notifications-send-test" class="btn-secondary" style="margin-right: auto;">Send Test</button>
|
||||
<button id="notifications-cancel">Cancel</button>
|
||||
<button id="notifications-save" class="btn-accent">Save Settings</button>
|
||||
</div>
|
||||
@@ -254,6 +259,7 @@
|
||||
document.getElementById('event-container-up').checked = config.events?.containerUp !== false;
|
||||
document.getElementById('event-deploy-success').checked = config.events?.deploymentSuccess !== false;
|
||||
document.getElementById('event-deploy-failed').checked = config.events?.deploymentFailed !== false;
|
||||
document.getElementById('event-resource-alert').checked = config.events?.resourceAlert !== false;
|
||||
}
|
||||
} catch (error) {
|
||||
errorHandler.logError('[Notifications] Load Config', error, { function: 'loadConfig' });
|
||||
@@ -329,7 +335,8 @@
|
||||
containerDown: document.getElementById('event-container-down').checked,
|
||||
containerUp: document.getElementById('event-container-up').checked,
|
||||
deploymentSuccess: document.getElementById('event-deploy-success').checked,
|
||||
deploymentFailed: document.getElementById('event-deploy-failed').checked
|
||||
deploymentFailed: document.getElementById('event-deploy-failed').checked,
|
||||
resourceAlert: document.getElementById('event-resource-alert').checked
|
||||
},
|
||||
healthCheck: {
|
||||
enabled: document.getElementById('health-check-enabled').checked,
|
||||
@@ -404,5 +411,56 @@
|
||||
});
|
||||
|
||||
saveBtn?.addEventListener('click', saveNotificationConfig);
|
||||
|
||||
// Send Test button - sends test notification to all enabled providers
|
||||
document.getElementById('notifications-send-test')?.addEventListener('click', async () => {
|
||||
const btn = document.getElementById('notifications-send-test');
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = 'Sending...';
|
||||
btn.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await secureFetch('/api/v1/notifications/send', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
event: 'test',
|
||||
data: { message: 'This is a test notification from DashCaddy.' },
|
||||
type: 'info'
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
showNotification('Test notification sent!', 'success', 3000);
|
||||
// Update last sent timestamp
|
||||
loadNotificationStatus();
|
||||
} else {
|
||||
showNotification(`Test failed: ${data.results?.map(r => `${r.provider}: ${r.error || 'ok'}`).join(', ')}`, 'error', 5000);
|
||||
}
|
||||
} catch (error) {
|
||||
showNotification(`Error: ${error.message}`, 'error', 3000);
|
||||
} finally {
|
||||
btn.textContent = originalText;
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Load notification status (last sent timestamp)
|
||||
async function loadNotificationStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/v1/notifications/status');
|
||||
const data = await response.json();
|
||||
if (data.success && data.lastSent) {
|
||||
const lastSentEl = document.getElementById('last-notification-sent');
|
||||
if (lastSentEl) {
|
||||
lastSentEl.textContent = `Last sent: ${new Date(data.lastSent).toLocaleString()}`;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently fail - status is not critical
|
||||
}
|
||||
}
|
||||
|
||||
wireModal(modal, cancelBtn);
|
||||
})();
|
||||
|
||||
+172
-57
@@ -236,70 +236,185 @@
|
||||
async function loadAlerts() {
|
||||
if (!alertsContainer) return;
|
||||
alertsContainer.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';
|
||||
|
||||
const data = cachedMonitoringData;
|
||||
if (!data || Object.keys(data).length === 0) {
|
||||
alertsContainer.innerHTML = '<div class="panel-empty"><span class="empty-icon">🔔</span>No containers found. Open the Live Stats tab first.</div>';
|
||||
return;
|
||||
}
|
||||
let html = '<div style="display: flex; flex-direction: column; gap: 12px;">';
|
||||
for (const [id, info] of Object.entries(data)) {
|
||||
const alertCfg = info.alertConfig || {};
|
||||
html += `<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
|
||||
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px;">
|
||||
<span style="font-weight: 600; flex: 1;">${info.name || id}</span>
|
||||
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
|
||||
<input type="checkbox" class="alert-enabled" data-container="${id}" ${alertCfg.enabled ? 'checked' : ''} /> Enabled
|
||||
</label>
|
||||
</div>
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
|
||||
<div>
|
||||
<label style="font-size: 0.75rem; color: var(--muted);">CPU Threshold %</label>
|
||||
<input type="number" class="alert-cpu" data-container="${id}" value="${alertCfg.cpuThreshold || 80}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size: 0.75rem; color: var(--muted);">Memory Threshold %</label>
|
||||
<input type="number" class="alert-mem" data-container="${id}" value="${alertCfg.memoryThreshold || 85}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size: 0.75rem; color: var(--muted);">Cooldown (min)</label>
|
||||
<input type="number" class="alert-cooldown" data-container="${id}" value="${alertCfg.cooldownMinutes || 15}" min="1" max="1440" style="width: 100%; font-size: 0.85rem;" />
|
||||
</div>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; margin-top: 8px; align-items: center;">
|
||||
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
|
||||
<input type="checkbox" class="alert-autorestart" data-container="${id}" ${alertCfg.autoRestart ? 'checked' : ''} /> Auto-restart on breach
|
||||
</label>
|
||||
<span style="flex: 1;"></span>
|
||||
<button class="alert-save-btn" data-container="${id}" style="padding: 4px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 4px; cursor: pointer;">Save</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
html += '</div>';
|
||||
alertsContainer.innerHTML = html;
|
||||
|
||||
// Wire up save buttons
|
||||
alertsContainer.querySelectorAll('.alert-save-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const cId = btn.dataset.container;
|
||||
const enabled = alertsContainer.querySelector(`.alert-enabled[data-container="${cId}"]`)?.checked || false;
|
||||
const cpuThreshold = parseInt(alertsContainer.querySelector(`.alert-cpu[data-container="${cId}"]`)?.value) || 80;
|
||||
const memoryThreshold = parseInt(alertsContainer.querySelector(`.alert-mem[data-container="${cId}"]`)?.value) || 85;
|
||||
const cooldownMinutes = parseInt(alertsContainer.querySelector(`.alert-cooldown[data-container="${cId}"]`)?.value) || 15;
|
||||
const autoRestart = alertsContainer.querySelector(`.alert-autorestart[data-container="${cId}"]`)?.checked || false;
|
||||
try {
|
||||
const res = await secureFetch(`/api/v1/monitoring/alerts/${cId}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled, cpuThreshold, memoryThreshold, cooldownMinutes, autoRestart })
|
||||
});
|
||||
const data = await res.json();
|
||||
btn.textContent = data.success ? '✅ Saved' : '⚠️ Failed';
|
||||
setTimeout(() => { btn.textContent = 'Save'; }, 2000);
|
||||
} catch (e) {
|
||||
btn.textContent = '❌ Error';
|
||||
setTimeout(() => { btn.textContent = 'Save'; }, 2000);
|
||||
}
|
||||
// Check premium status for config section visibility
|
||||
let isPremium = false;
|
||||
try {
|
||||
const resp = await fetch('/api/v1/license/feature/resource-alerts');
|
||||
const ld = await resp.json();
|
||||
isPremium = ld.available;
|
||||
} catch (_) { isPremium = false; }
|
||||
|
||||
// Fetch alert history
|
||||
let alertHistory = [];
|
||||
try {
|
||||
const hr = await fetch('/api/v1/monitoring/alerts?limit=50');
|
||||
const hd = await hr.json();
|
||||
if (hd.success) alertHistory = hd.history || [];
|
||||
} catch (_) {}
|
||||
|
||||
// Fetch all alert configs
|
||||
let allConfigs = {};
|
||||
try {
|
||||
const cr = await fetch('/api/v1/monitoring/alerts/config');
|
||||
const cd = await cr.json();
|
||||
if (cd.success) allConfigs = cd.configs || {};
|
||||
} catch (_) {}
|
||||
|
||||
const containers = Object.entries(data);
|
||||
const containerRows = containers.map(([id, info]) => {
|
||||
const cfg = allConfigs[id] || { cpuThreshold: 80, memoryThreshold: 90, diskIOThreshold: 50, autoRestart: false, enabled: false };
|
||||
return `
|
||||
<tr data-container="${id}">
|
||||
<td style="font-weight: 600; padding: 8px;">${info.name || id}</td>
|
||||
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${cfg.cpuThreshold ?? 80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${cfg.memoryThreshold ?? 90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${cfg.diskIOThreshold ?? 50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${isPremium ? '' : 'disabled'} /></td>
|
||||
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${cfg.autoRestart ? 'checked' : ''} ${isPremium ? '' : 'disabled'} /></td>
|
||||
<td style="padding: 4px 8px;">
|
||||
<button class="alert-test-btn btn-xs" data-container="${id}" data-name="${info.name || id}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const historyRows = alertHistory.map(entry => {
|
||||
const time = new Date(entry.timestamp).toLocaleString();
|
||||
const notifiedMark = entry.notified ? '✓' : '—';
|
||||
return `
|
||||
<tr>
|
||||
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${time}</td>
|
||||
<td style="padding: 6px 8px; font-weight: 500;">${entry.containerName || entry.containerId}</td>
|
||||
<td style="padding: 6px 8px; text-transform: capitalize;">${entry.metric || entry.type}</td>
|
||||
<td style="padding: 6px 8px;">${typeof entry.value === 'number' ? entry.value.toFixed(1) : entry.value}${entry.metric === 'disk' ? ' MB/s' : '%'}</td>
|
||||
<td style="padding: 6px 8px; text-align: center;">${notifiedMark}</td>
|
||||
<td style="padding: 6px 8px; font-size: 0.75rem; color: ${entry.autoRestartTriggered ? '#f39c12' : 'var(--muted)'};">${entry.autoRestartTriggered ? '↻' : ''}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const configSection = isPremium ? `
|
||||
<div style="margin-bottom: 20px;">
|
||||
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
|
||||
<h4 style="margin: 0; font-size: 0.9rem;">⚙️ Alert Configuration</h4>
|
||||
<a href="#" id="go-to-notifications" style="font-size: 0.8rem; color: var(--accent); text-decoration: none;">Configure notifications →</a>
|
||||
</div>
|
||||
<div style="overflow-x: auto;">
|
||||
<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
|
||||
<thead>
|
||||
<tr style="border-bottom: 1px solid var(--border);">
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">CPU %</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Mem %</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Disk I/O MB/s</th>
|
||||
<th style="text-align: center; padding: 6px 8px; color: var(--muted);">Auto-Restart</th>
|
||||
<th style="padding: 6px 8px;"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${containerRows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div style="margin-top: 12px; display: flex; justify-content: flex-end;">
|
||||
<button id="save-all-alerts" style="padding: 6px 16px; font-size: 0.85rem; background: var(--accent); color: var(--base); border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Save All</button>
|
||||
</div>
|
||||
</div>
|
||||
` : `
|
||||
<div style="margin-bottom: 20px; padding: 12px; background: rgba(241,196,15,0.1); border: 1px solid rgba(241,196,15,0.3); border-radius: 8px; text-align: center;">
|
||||
<span style="color: #f1c40f; font-weight: 600; font-size: 0.85rem;">⭐ Premium Feature</span>
|
||||
<p style="margin: 6px 0 0; font-size: 0.75rem; color: var(--muted);">Upgrade to configure resource alert thresholds per container.</p>
|
||||
<button id="upgrade-for-alerts" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; background: #f1c40f; color: #000; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Upgrade Now</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
alertsContainer.innerHTML = `
|
||||
${configSection}
|
||||
<div>
|
||||
<h4 style="margin: 0 0 10px; font-size: 0.9rem;">📋 Recent Alerts</h4>
|
||||
${historyRows ? `
|
||||
<div style="overflow-x: auto;">
|
||||
<table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;">
|
||||
<thead>
|
||||
<tr style="border-bottom: 1px solid var(--border);">
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Time</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Metric</th>
|
||||
<th style="text-align: left; padding: 6px 8px; color: var(--muted);">Value</th>
|
||||
<th style="text-align: center; padding: 6px 8px; color: var(--muted);">✓?</th>
|
||||
<th style="padding: 6px 8px;"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${historyRows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
` : '<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Wire up save-all button
|
||||
document.getElementById('save-all-alerts')?.addEventListener('click', async () => {
|
||||
const configs = {};
|
||||
document.querySelectorAll('#stats-alerts-container tr[data-container]').forEach(row => {
|
||||
const cId = row.dataset.container;
|
||||
configs[cId] = {
|
||||
cpuThreshold: parseInt(row.querySelector('.alert-cpu')?.value) || 80,
|
||||
memoryThreshold: parseInt(row.querySelector('.alert-mem')?.value) || 90,
|
||||
diskIOThreshold: parseInt(row.querySelector('.alert-disk')?.value) || 50,
|
||||
autoRestart: !!row.querySelector('.alert-autorestart')?.checked,
|
||||
enabled: true
|
||||
};
|
||||
});
|
||||
try {
|
||||
const res = await secureFetch('/api/v1/monitoring/alerts/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ configs })
|
||||
});
|
||||
const d = await res.json();
|
||||
const btn = document.getElementById('save-all-alerts');
|
||||
btn.textContent = d.success ? '✅ Saved' : '❌ Failed';
|
||||
setTimeout(() => { btn.textContent = 'Save All'; }, 2000);
|
||||
} catch (e) {
|
||||
const btn = document.getElementById('save-all-alerts');
|
||||
btn.textContent = '❌ Error';
|
||||
setTimeout(() => { btn.textContent = 'Save All'; }, 2000);
|
||||
}
|
||||
});
|
||||
|
||||
// Wire up notification settings link
|
||||
document.getElementById('go-to-notifications')?.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
modal.classList.remove('show');
|
||||
stopAutoRefresh();
|
||||
document.getElementById('manage-notifications')?.click();
|
||||
});
|
||||
|
||||
// Wire up test buttons
|
||||
document.querySelectorAll('.alert-test-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const orig = btn.textContent;
|
||||
btn.textContent = '...';
|
||||
try {
|
||||
await secureFetch(`/api/v1/monitoring/alerts/${btn.dataset.container}/test`, { method: 'POST' });
|
||||
btn.textContent = '✅';
|
||||
showNotification('Test alert sent for ' + btn.dataset.name, 'success', 3000);
|
||||
} catch (e) {
|
||||
btn.textContent = '❌';
|
||||
}
|
||||
setTimeout(() => { btn.textContent = orig; }, 2000);
|
||||
});
|
||||
});
|
||||
|
||||
// Wire up upgrade button
|
||||
document.getElementById('upgrade-for-alerts')?.addEventListener('click', () => {
|
||||
modal.classList.remove('show');
|
||||
stopAutoRefresh();
|
||||
if (typeof openLicenseModal === 'function') openLicenseModal();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user