options.js aktualisiert

This commit is contained in:
2025-12-06 15:13:12 +00:00
parent 2a61d6a577
commit f78de6f2ff

View File

@@ -1,382 +1,501 @@
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const serviceForm = document.getElementById('add-service-form'); const serviceForm = document.getElementById('add-service-form');
const intervalSelect = document.getElementById('check-interval'); const intervalSelect = document.getElementById('check-interval');
const notifyOnlineCheckbox = document.getElementById('notify-online'); const notifyOnlineCheckbox = document.getElementById('notify-online');
const exportBtn = document.getElementById('export-services'); const exportBtn = document.getElementById('export-services');
const importBtn = document.getElementById('import-services'); const importBtn = document.getElementById('import-services');
const importFileInput = document.getElementById('import-file'); const importFileInput = document.getElementById('import-file');
const servicesListStat = document.getElementById('services-list-stat'); const servicesListStat = document.getElementById('services-list-stat');
const emptyState = document.getElementById('empty-state'); const emptyState = document.getElementById('empty-state');
const searchInput = document.getElementById('services-search'); const searchInput = document.getElementById('services-search');
const MAX_POPUP_SERVERS = 8; const MAX_POPUP_SERVERS = 8;
let currentChart = null; let currentChart = null;
// NEU: Discord Webhook Input // NEU: Discord Webhook Input
const discordWebhookInput = document.getElementById('discord-webhook-url'); const discordWebhookInput = document.getElementById('discord-webhook-url');
// NEU: Telegram Inputs
// --- Tab-Logik --- const telegramBotTokenInput = document.getElementById('telegram-bot-token');
const tabButtons = document.querySelectorAll('.tab-btn'); const telegramChatIdInput = document.getElementById('telegram-chat-id');
const tabPanels = document.querySelectorAll('.tab-panel');
tabButtons.forEach(button => { // --- Tab-Logik ---
button.addEventListener('click', () => { const tabButtons = document.querySelectorAll('.tab-btn');
const targetTab = button.getAttribute('data-tab'); const tabPanels = document.querySelectorAll('.tab-panel');
tabButtons.forEach(btn => btn.classList.remove('active')); tabButtons.forEach(button => {
tabPanels.forEach(panel => panel.classList.remove('active')); button.addEventListener('click', () => {
button.classList.add('active'); const targetTab = button.getAttribute('data-tab');
document.getElementById(`${targetTab}-panel`).classList.add('active'); tabButtons.forEach(btn => btn.classList.remove('active'));
}); tabPanels.forEach(panel => panel.classList.remove('active'));
}); button.classList.add('active');
document.getElementById(`${targetTab}-panel`).classList.add('active');
// --- Utilities --- });
function getAllData(callback) { });
chrome.storage.sync.get({ services: [], popupServers: [] }, function(syncData) {
chrome.storage.local.get({ serviceStatus: {}, history: {} }, function(localData) { // --- Utilities ---
callback(syncData.services || [], syncData.popupServers || [], localData.serviceStatus || {}, localData.history || {}); function getAllData(callback) {
}); chrome.storage.sync.get({ services: [], popupServers: [] }, function(syncData) {
}); chrome.storage.local.get({ serviceStatus: {}, history: {} }, function(localData) {
} callback(syncData.services || [], syncData.popupServers || [], localData.serviceStatus || {}, localData.history || {});
});
// --- NEU: Popup-Server-Auswahl rendern --- });
function renderPopupServerSelection(allServices) { }
const container = document.getElementById('popup-server-list');
const infoElement = document.getElementById('selection-info'); // --- NEU: Popup-Server-Auswahl rendern ---
container.innerHTML = ''; // Leeren function renderPopupServerSelection(allServices) {
const container = document.getElementById('popup-server-list');
if (allServices.length === 0) { const infoElement = document.getElementById('selection-info');
infoElement.textContent = 'Bitte fügen Sie zuerst Server hinzu.'; container.innerHTML = ''; // Leeren
return;
} if (allServices.length === 0) {
infoElement.textContent = 'Bitte fügen Sie zuerst Server hinzu.';
chrome.storage.sync.get({ popupServers: [] }, (data) => { return;
const selectedServers = data.popupServers || []; }
// Info-Text aktualisieren chrome.storage.sync.get({ popupServers: [] }, (data) => {
infoElement.textContent = `${selectedServers.length} von ${MAX_POPUP_SERVERS} Servern für das Popup ausgewählt.`; const selectedServers = data.popupServers || [];
allServices.forEach(service => { // Info-Text aktualisieren
const serverItem = document.createElement('div'); infoElement.textContent = `${selectedServers.length} von ${MAX_POPUP_SERVERS} Servern für das Popup ausgewählt.`;
serverItem.className = 'popup-server-item';
allServices.forEach(service => {
const isSelected = selectedServers.some(s => s.name === service.name && s.adresse === service.adresse); const serverItem = document.createElement('div');
serverItem.className = 'popup-server-item';
serverItem.innerHTML = `
<input type="checkbox" id="popup-server-${service.name.replace(/\s+/g, '-')}" ${isSelected ? 'checked' : ''}> const isSelected = selectedServers.some(s => s.name === service.name && s.adresse === service.adresse);
<div class="server-info">
<div class="server-name">${escapeHtml(service.name)}</div> serverItem.innerHTML = `
<div class="server-address">${escapeHtml(service.adresse || '')}</div> <input type="checkbox" id="popup-server-${service.name.replace(/\s+/g, '-')}" ${isSelected ? 'checked' : ''}>
</div> <div class="server-info">
`; <div class="server-name">${escapeHtml(service.name)}</div>
<div class="server-address">${escapeHtml(service.adresse || '')}</div>
const checkbox = serverItem.querySelector('input[type="checkbox"]'); </div>
checkbox.addEventListener('change', () => { `;
updatePopupServerSelection(service, checkbox.checked, allServices);
}); const checkbox = serverItem.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', () => {
container.appendChild(serverItem); updatePopupServerSelection(service, checkbox.checked, allServices);
}); });
});
} container.appendChild(serverItem);
});
// --- NEU: Auswahl aktualisieren --- });
function updatePopupServerSelection(service, isSelected, allServices) { }
chrome.storage.sync.get({ popupServers: [] }, (data) => {
let selectedServers = data.popupServers || []; // --- NEU: Auswahl aktualisieren ---
function updatePopupServerSelection(service, isSelected, allServices) {
if (isSelected) { chrome.storage.sync.get({ popupServers: [] }, (data) => {
// Verhindere, dass mehr als MAX_POPUP_SERVERS ausgewählt werden let selectedServers = data.popupServers || [];
if (selectedServers.length >= MAX_POPUP_SERVERS) {
alert(`Sie können maximal ${MAX_POPUP_SERVERS} Server auswählen.`); if (isSelected) {
checkbox.checked = false; // Haken entfernen // Verhindere, dass mehr als MAX_POPUP_SERVERS ausgewählt werden
return; if (selectedServers.length >= MAX_POPUP_SERVERS) {
} alert(`Sie können maximal ${MAX_POPUP_SERVERS} Server auswählen.`);
selectedServers.push(service); // Finde die Checkbox und setze den Haken zurück
} else { const checkboxId = `popup-server-${service.name.replace(/\s+/g, '-')}`;
selectedServers = selectedServers.filter(s => !(s.name === service.name && s.adresse === service.adresse)); const checkbox = document.getElementById(checkboxId);
} if(checkbox) checkbox.checked = false;
return;
chrome.storage.sync.set({ popupServers: selectedServers }, () => { }
// Info-Text und Checkboxen aktualisieren selectedServers.push(service);
renderPopupServerSelection(allServices); } else {
}); selectedServers = selectedServers.filter(s => !(s.name === service.name && s.adresse === service.adresse));
}); }
}
chrome.storage.sync.set({ popupServers: selectedServers }, () => {
// Info-Text und Checkboxen aktualisieren
// --- Services rendern --- renderPopupServerSelection(allServices);
function renderServices(filter = '') { });
getAllData((services, popupServers, statuses, history) => { });
servicesListStat.innerHTML = ''; }
const filtered = services.filter(s => s.name.toLowerCase().includes(filter.toLowerCase()));
if (filtered.length === 0) {
emptyState.style.display = services.length === 0 ? 'block' : 'none'; // --- Services rendern ---
if (services.length === 0) return; function renderServices(filter = '') {
} else { getAllData((services, popupServers, statuses, history) => {
emptyState.style.display = 'none'; servicesListStat.innerHTML = '';
} const filtered = services.filter(s => s.name.toLowerCase().includes(filter.toLowerCase()));
if (filtered.length === 0) {
filtered.forEach((service, index) => { emptyState.style.display = services.length === 0 ? 'block' : 'none';
const statusObj = statuses[service.name] || {}; if (services.length === 0) return;
const st = statusObj.status || 'unknown'; } else {
const resp = typeof statusObj.responseTime === 'number' ? `${statusObj.responseTime} ms` : ''; emptyState.style.display = 'none';
}
const li = document.createElement('li');
li.className = 'service-stat-item'; filtered.forEach((service, index) => {
li.dataset.index = index; const statusObj = statuses[service.name] || {};
const st = statusObj.status || 'unknown';
li.innerHTML = ` const resp = typeof statusObj.responseTime === 'number' ? `${statusObj.responseTime} ms` : '';
<div class="service-left">
<div class="service-name" role="button" tabindex="0">${escapeHtml(service.name)}</div> const li = document.createElement('li');
<div class="service-sub">${escapeHtml(service.adresse || '')}</div> li.className = 'service-stat-item';
</div> li.dataset.index = index;
<div class="service-right">
<div class="service-meta"> li.innerHTML = `
<span class="status-dot small ${st}" title="Status: ${st}"></span> <div class="service-left">
<span class="response-time">${resp}</span> <div class="service-name" role="button" tabindex="0">${escapeHtml(service.name)}</div>
</div> <div class="service-sub">${escapeHtml(service.adresse || '')}</div>
<div class="service-actions"> </div>
<button class="icon-btn edit" aria-label="Bearbeiten ${escapeHtml(service.name)}" title="Bearbeiten"> <div class="service-right">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <div class="service-meta">
<path d="M12 20h9"></path> <span class="status-dot small ${st}" title="Status: ${st}"></span>
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"></path> <span class="response-time">${resp}</span>
</svg> </div>
</button> <div class="service-actions">
<button class="icon-btn delete" aria-label="Löschen ${escapeHtml(service.name)}" title="Löschen"> <button class="icon-btn edit" aria-label="Bearbeiten ${escapeHtml(service.name)}" title="Bearbeiten">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"></polyline> <path d="M12 20h9"></path>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"></path> <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"></path>
</svg> </svg>
</button> </button>
</div> <button class="icon-btn delete" aria-label="Löschen ${escapeHtml(service.name)}" title="Löschen">
</div> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
`; <polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"></path>
li.querySelector('.service-name').addEventListener('click', () => { </svg>
showStatsForService(service); </button>
highlightSelection(li); </div>
}); </div>
`;
li.querySelector('.service-name').addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') { li.querySelector('.service-name').addEventListener('click', () => {
e.preventDefault(); showStatsForService(service);
li.querySelector('.service-name').click(); highlightSelection(li);
} });
});
li.querySelector('.service-name').addEventListener('keydown', (e) => {
li.querySelector('.icon-btn.edit').addEventListener('click', (e) => { if (e.key === 'Enter' || e.key === ' ') {
e.stopPropagation(); e.preventDefault();
enterEditMode(li, service, services); li.querySelector('.service-name').click();
}); }
});
li.querySelector('.icon-btn.delete').addEventListener('click', (e) => {
e.stopPropagation(); li.querySelector('.icon-btn.edit').addEventListener('click', (e) => {
if (confirm(`Server "${service.name}" wirklich löschen?`)) { e.stopPropagation();
services.splice(index, 1); enterEditMode(li, service, services);
chrome.storage.sync.set({ services }, () => { });
renderServices(searchInput.value.trim());
renderPopupServerSelection(services); // Auch die Auswahl neu rendern li.querySelector('.icon-btn.delete').addEventListener('click', (e) => {
}); e.stopPropagation();
} if (confirm(`Server "${service.name}" wirklich löschen?`)) {
}); services.splice(index, 1);
chrome.storage.sync.set({ services }, () => {
servicesListStat.appendChild(li); renderServices(searchInput.value.trim());
}); renderPopupServerSelection(services); // Auch die Auswahl neu rendern
}); });
} }
});
function highlightSelection(itemEl) {
document.querySelectorAll('.service-stat-item').forEach(it => it.classList.remove('selected')); servicesListStat.appendChild(li);
itemEl.classList.add('selected'); });
} });
}
function enterEditMode(li, service, allServices) {
li.classList.add('editing'); function highlightSelection(itemEl) {
li.innerHTML = ` document.querySelectorAll('.service-stat-item').forEach(it => it.classList.remove('selected'));
<div class="edit-left"> itemEl.classList.add('selected');
<input class="edit-name" value="${escapeAttr(service.name)}" /> }
<input class="edit-adresse" value="${escapeAttr(service.adresse || '')}" />
</div> function enterEditMode(li, service, allServices) {
<div class="edit-actions"> li.classList.add('editing');
<button class="btn-save" title="Speichern">Speichern</button> li.innerHTML = `
<button class="btn-cancel" title="Abbrechen">Abbrechen</button> <div class="edit-left">
</div> <input class="edit-name" value="${escapeAttr(service.name)}" />
`; <input class="edit-adresse" value="${escapeAttr(service.adresse || '')}" />
</div>
const saveBtn = li.querySelector('.btn-save'); <div class="edit-actions">
const cancelBtn = li.querySelector('.btn-cancel'); <button class="btn-save" title="Speichern">Speichern</button>
<button class="btn-cancel" title="Abbrechen">Abbrechen</button>
cancelBtn.addEventListener('click', (ev) => { </div>
ev.stopPropagation(); `;
renderServices(searchInput.value.trim());
}); const saveBtn = li.querySelector('.btn-save');
const cancelBtn = li.querySelector('.btn-cancel');
saveBtn.addEventListener('click', (ev) => {
ev.stopPropagation(); cancelBtn.addEventListener('click', (ev) => {
const newName = li.querySelector('.edit-name').value.trim(); ev.stopPropagation();
const newAdresse = li.querySelector('.edit-adresse').value.trim(); renderServices(searchInput.value.trim());
if (!newName || !newAdresse) { alert('Name und Adresse dürfen nicht leer sein.'); return; } });
chrome.storage.sync.get({ services: [] }, function(data) { saveBtn.addEventListener('click', (ev) => {
const services = data.services || []; ev.stopPropagation();
const idx = services.findIndex(s => s.name === service.name && (s.adresse || '') === (service.adresse || '')); const newName = li.querySelector('.edit-name').value.trim();
if (idx === -1) { const newAdresse = li.querySelector('.edit-adresse').value.trim();
alert('Fehler: Dienst nicht gefunden.'); if (!newName || !newAdresse) { alert('Name und Adresse dürfen nicht leer sein.'); return; }
renderServices(searchInput.value.trim());
return; chrome.storage.sync.get({ services: [] }, function(data) {
} const services = data.services || [];
services[idx].name = newName; const idx = services.findIndex(s => s.name === service.name && (s.adresse || '') === (service.adresse || ''));
services[idx].adresse = newAdresse; if (idx === -1) {
chrome.storage.sync.set({ services }, () => { alert('Fehler: Dienst nicht gefunden.');
renderServices(searchInput.value.trim()); renderServices(searchInput.value.trim());
renderPopupServerSelection(services); // Auch die Auswahl neu rendern return;
}); }
}); services[idx].name = newName;
}); services[idx].adresse = newAdresse;
} chrome.storage.sync.set({ services }, () => {
renderServices(searchInput.value.trim());
// --- Add service --- renderPopupServerSelection(services); // Auch die Auswahl neu rendern
function addService(name, adresse) { });
if (!name || !adresse) return; });
chrome.storage.sync.get({ services: [] }, function(data) { });
const newService = { name, adresse }; }
const updatedServices = [...data.services, newService];
chrome.storage.sync.set({ services: updatedServices }, () => { // --- Add service ---
renderServices(searchInput.value.trim()); function addService(name, adresse) {
renderPopupServerSelection(updatedServices); // Auch die Auswahl neu rendern if (!name || !adresse) return;
}); chrome.storage.sync.get({ services: [] }, function(data) {
}); const newService = { name, adresse };
} const updatedServices = [...data.services, newService];
chrome.storage.sync.set({ services: updatedServices }, () => {
serviceForm.addEventListener('submit', function(event) { renderServices(searchInput.value.trim());
event.preventDefault(); renderPopupServerSelection(updatedServices); // Auch die Auswahl neu rendern
const nameInput = document.getElementById('service-name'); });
const protocolSelect = document.getElementById('service-protocol'); });
const domainInput = document.getElementById('service-domain'); }
const fullAdresse = protocolSelect.value + domainInput.value.trim();
addService(nameInput.value.trim(), fullAdresse); serviceForm.addEventListener('submit', function(event) {
serviceForm.reset(); event.preventDefault();
nameInput.focus(); const nameInput = document.getElementById('service-name');
}); const protocolSelect = document.getElementById('service-protocol');
const domainInput = document.getElementById('service-domain');
// --- Settings load/save --- const fullAdresse = protocolSelect.value + domainInput.value.trim();
function loadSettings() { addService(nameInput.value.trim(), fullAdresse);
// NEU: discordWebhookUrl zu den abgerufenen Daten hinzufügen serviceForm.reset();
chrome.storage.sync.get({ checkInterval: 1, notifyOnline: false, discordWebhookUrl: '' }, function(data) { nameInput.focus();
intervalSelect.value = data.checkInterval; });
notifyOnlineCheckbox.checked = data.notifyOnline;
discordWebhookInput.value = data.discordWebhookUrl || ''; // NEU // --- Settings load/save ---
}); function loadSettings() {
} // NEU: discordWebhookUrl, telegramBotToken und telegramChatId zu den abgerufenen Daten hinzufügen
intervalSelect.addEventListener('change', () => { chrome.storage.sync.get({ checkInterval: 1, notifyOnline: false, discordWebhookUrl: '', telegramBotToken: '', telegramChatId: '' }, function(data) {
const newInterval = parseFloat(intervalSelect.value); intervalSelect.value = data.checkInterval;
chrome.storage.sync.set({ checkInterval: newInterval }, () => { chrome.runtime.sendMessage({ type: 'updateInterval' }); }); notifyOnlineCheckbox.checked = data.notifyOnline;
}); discordWebhookInput.value = data.discordWebhookUrl || '';
notifyOnlineCheckbox.addEventListener('change', () => { chrome.storage.sync.set({ notifyOnline: notifyOnlineCheckbox.checked }); }); telegramBotTokenInput.value = data.telegramBotToken || '';
telegramChatIdInput.value = data.telegramChatId || '';
// NEU: Event Listener für Discord Webhook URL });
discordWebhookInput.addEventListener('change', () => { }
chrome.storage.sync.set({ discordWebhookUrl: discordWebhookInput.value.trim() }); intervalSelect.addEventListener('change', () => {
}); const newInterval = parseFloat(intervalSelect.value);
chrome.storage.sync.set({ checkInterval: newInterval }, () => { chrome.runtime.sendMessage({ type: 'updateInterval' }); });
// --- Import/Export --- });
exportBtn.addEventListener('click', () => { notifyOnlineCheckbox.addEventListener('change', () => { chrome.storage.sync.set({ notifyOnline: notifyOnlineCheckbox.checked }); });
chrome.storage.sync.get({ services: [] }, (data) => {
const dataStr = JSON.stringify(data.services, null, 2); // NEU: Event Listener für Discord Webhook URL
const blob = new Blob([dataStr], { type: 'application/json' }); discordWebhookInput.addEventListener('change', () => {
const url = URL.createObjectURL(blob); const a = document.createElement('a'); chrome.storage.sync.set({ discordWebhookUrl: discordWebhookInput.value.trim() });
a.href = url; a.download = 'uptime-services.json'; });
document.body.appendChild(a); a.click();
document.body.removeChild(a); URL.revokeObjectURL(url); // NEU: Event Listener für Telegram
}); telegramBotTokenInput.addEventListener('change', () => {
}); chrome.storage.sync.set({ telegramBotToken: telegramBotTokenInput.value.trim() });
importBtn.addEventListener('click', () => importFileInput.click()); });
importFileInput.addEventListener('change', (event) => { telegramChatIdInput.addEventListener('change', () => {
const file = event.target.files[0]; if (!file) return; chrome.storage.sync.set({ telegramChatId: telegramChatIdInput.value.trim() });
const reader = new FileReader(); });
reader.onload = (e) => {
try { const importedServices = JSON.parse(e.target.result);
if (Array.isArray(importedServices)) { // --- ERWEITERTES Import/Export ---
chrome.storage.sync.set({ services: importedServices }, () => { exportBtn.addEventListener('click', () => {
renderServices(searchInput.value.trim()); // Rufe alle relevanten Daten aus dem Speicher ab, inklusive der neuen Telegram-Einstellungen
renderPopupServerSelection(importedServices); // Auch die Auswahl neu rendern chrome.storage.sync.get({
}); services: [],
} popupServers: [],
else { alert('Ungültiges Dateiformat.'); } checkInterval: 1,
} catch (error) { alert('Fehler beim Lesen der Datei.'); } notifyOnline: false,
}; discordWebhookUrl: '',
reader.readAsText(file); telegramBotToken: '',
}); telegramChatId: ''
}, (data) => {
// --- Statistik-Anzeige --- // Erstelle einen String aus den Daten für die JSON-Datei
function showStatsForService(service) { const dataStr = JSON.stringify(data, null, 2);
if (!service) return; const blob = new Blob([dataStr], { type: 'application/json' });
document.getElementById('no-service-selected').style.display = 'none'; const url = URL.createObjectURL(blob);
const chartCanvas = document.getElementById('uptimeChart'); const a = document.createElement('a');
chartCanvas.style.display = 'block'; a.href = url;
a.download = 'uptime-monitor-backup.json'; // Passenderer Dateiname
chrome.storage.local.get({ history: {} }, (data) => { document.body.appendChild(a);
const history = data.history[service.name] || {}; a.click();
const labels = Object.keys(history).sort().slice(-48); document.body.removeChild(a);
const uptimeData = labels.map(label => { URL.revokeObjectURL(url);
const h = history[label]; });
return h.checks > 0 ? (h.up_checks / h.checks * 100).toFixed(2) : 0; });
});
importBtn.addEventListener('click', () => importFileInput.click());
if (currentChart) currentChart.destroy(); importFileInput.addEventListener('change', (event) => {
const ctx = chartCanvas.getContext('2d'); const file = event.target.files[0];
if (!file) return;
if (labels.length === 0) {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); const reader = new FileReader();
ctx.font = "16px -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto"; reader.onload = (e) => {
ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--text-secondary'); try {
ctx.textAlign = 'center'; const importedData = JSON.parse(e.target.result);
ctx.fillText('Noch keine Daten verfügbar.', ctx.canvas.width / 2, ctx.canvas.height / 2);
return; // Prüfe, ob die importierten Daten ein Objekt sind
} if (typeof importedData === 'object' && importedData !== null) {
// Setze alle importierten Daten auf einmal
const formattedLabels = labels.map(l => { chrome.storage.sync.set(importedData, () => {
const parts = l.split(' '); alert('Backup erfolgreich wiederhergestellt! Die Seite wird neu geladen, um alle Änderungen zu übernehmen.');
return parts.length === 2 ? parts[1] : l; // Nach dem Import ist es am sichersten, die Seite neu zu laden
}); location.reload();
});
currentChart = new Chart(ctx, { } else {
type: 'line', alert('Ungültiges Dateiformat. Die Datei muss eine gültige Backup-Datei sein.');
data: { }
labels: formattedLabels, } catch (error) {
datasets: [{ console.error('Fehler beim Verarbeiten der Import-Datei:', error);
label: `Uptime für ${service.name} (%)`, alert('Fehler beim Lesen der Datei. Bitte stellen Sie sicher, dass es sich um eine gültige JSON-Datei handelt.');
data: uptimeData, }
borderColor: 'var(--accent-color)', };
backgroundColor: 'rgba(24, 119, 242, 0.1)', reader.readAsText(file);
fill: true, });
tension: 0.3
}]
}, // --- Statistik-Anzeige ---
options: { function showStatsForService(service) {
responsive: true, if (!service) return;
maintainAspectRatio: false, document.getElementById('no-service-selected').style.display = 'none';
scales: { const chartCanvas = document.getElementById('uptimeChart');
y: { beginAtZero: true, max: 100, ticks: { callback: value => value + '%' } } chartCanvas.style.display = 'block';
},
plugins: { legend: { display: false } } chrome.storage.local.get({ history: {} }, (data) => {
} const history = data.history[service.name] || {};
}); const labels = Object.keys(history).sort().slice(-48);
}); const uptimeData = labels.map(label => {
} const h = history[label];
return h.checks > 0 ? (h.up_checks / h.checks * 100).toFixed(2) : 0;
// --- Search --- });
searchInput.addEventListener('input', () => {
renderServices(searchInput.value.trim()); if (currentChart) currentChart.destroy();
}); const ctx = chartCanvas.getContext('2d');
// --- Helpers --- if (labels.length === 0) {
function escapeHtml(str) { if (!str) return ''; return String(str).replace(/[&<>"']/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s])); } ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
function escapeAttr(s) { return (s||'').replace(/"/g, '&quot;'); } ctx.font = "16px -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto";
ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--text-secondary');
// --- Init --- ctx.textAlign = 'center';
loadSettings(); ctx.fillText('Noch keine Daten verfügbar.', ctx.canvas.width / 2, ctx.canvas.height / 2);
renderServices(); return;
// Initiales Rendern der Popup-Auswahl }
chrome.storage.sync.get({ services: [] }, (data) => {
renderPopupServerSelection(data.services || []); const formattedLabels = labels.map(l => {
}); const parts = l.split(' ');
return parts.length === 2 ? parts[1] : l;
});
currentChart = new Chart(ctx, {
type: 'line',
data: {
labels: formattedLabels,
datasets: [{
label: `Uptime für ${service.name} (%)`,
data: uptimeData,
borderColor: 'var(--accent-color)',
backgroundColor: 'rgba(24, 119, 242, 0.1)',
fill: true,
tension: 0.3
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: { beginAtZero: true, max: 100, ticks: { callback: value => value + '%' } }
},
plugins: { legend: { display: false } }
}
});
});
}
// --- Search ---
searchInput.addEventListener('input', () => {
renderServices(searchInput.value.trim());
});
// --- Helpers ---
function escapeHtml(str) { if (!str) return ''; return String(str).replace(/[&<>"']/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s])); }
function escapeAttr(s) { return (s||'').replace(/"/g, '&quot;'); }
// --- Init ---
loadSettings();
renderServices();
// Initiales Rendern der Popup-Auswahl
chrome.storage.sync.get({ services: [] }, (data) => {
renderPopupServerSelection(data.services || []);
});
// --- ROBUSTE: Gitea Repository Widget ---
// Führt mehrere Suchen durch und kombiniert die Ergebnisse.
function fetchAndDisplayGiteaRepos() {
const list = document.getElementById('gitea-repos-list');
const loadingIndicator = document.getElementById('gitea-repos-loading');
const errorIndicator = document.getElementById('gitea-repos-error');
const searchKeywords = ["Gitea", "Themes", "Server", "Minecraft", "Webseite", "Wordpress", "Plugin", "chrome-erweiterung"];
loadingIndicator.style.display = 'block';
list.style.display = 'none';
errorIndicator.style.display = 'none';
// Erstelle eine Liste von Promises, eine für jede Suchanfrage
const searchPromises = searchKeywords.map(keyword => {
const apiUrl = `https://git.viper.ipv64.net/api/v1/repos/search?q=${encodeURIComponent(keyword)}&limit=50&sort=updated&order=desc`;
return fetch(apiUrl).then(response => {
if (!response.ok) {
// Wenn eine Anfrage fehlschlägt, geben wir ein leeres Array zurück, um die anderen nicht zu blockieren
console.warn(`Suche nach "${keyword}" fehlgeschlagen:`, response.status);
return { data: [] }; // Gib eine leere Antwort-Struktur zurück
}
return response.json();
});
});
// Führe alle Suchanfragen parallel aus
Promise.all(searchPromises)
.then(results => {
// Kombiniere alle Ergebnisse aus den einzelnen Suchen
const allRepos = results.flatMap(result => result.data || []);
// Entferne Duplikate anhand der einzigartigen ID des Repositories
const uniqueReposMap = new Map();
allRepos.forEach(repo => {
uniqueReposMap.set(repo.id, repo);
});
const uniqueRepos = Array.from(uniqueReposMap.values());
// Sortiere die kombinierten Repositories nach dem letzten Update-Datum
uniqueRepos.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
// Begrenze die Ergebnisse auf die 5 neuesten
const finalRepos = uniqueRepos.slice(0, 5);
loadingIndicator.style.display = 'none';
list.innerHTML = '';
if (finalRepos.length > 0) {
list.style.display = 'block';
finalRepos.forEach(repo => {
const li = document.createElement('li');
const link = document.createElement('a');
link.href = repo.html_url;
link.textContent = repo.name;
link.target = '_blank';
link.rel = 'noopener noreferrer';
li.appendChild(link);
list.appendChild(li);
});
} else {
list.style.display = 'block';
list.innerHTML = '<li>Keine passenden Repositories gefunden.</li>';
}
})
.catch(error => {
console.error('Fehler beim Abrufen der Gitea Repositories:', error);
loadingIndicator.style.display = 'none';
errorIndicator.style.display = 'block';
});
}
// Rufe die neue Funktion auf, wenn die Seite geladen wird.
fetchAndDisplayGiteaRepos();
}); });