Jasne! To świetny pomysł na domowy pulpit nawigacyjny. Zbudujemy go jako prostą aplikację webową (single-page application) z frontendem (HTML, CSS, JavaScript) i prostym backendem (Python Flask) do zbierania danych o zużyciu zasobów.
Cechy, które zaimplementujemy:
- Kafelki z linkami: Możliwość dodawania/usuwania linków do aplikacji (np. Portainer, Pi-hole, Plex).
- Wykresy zużycia zasobów: CPU, RAM, dysk (zbierane z serwera).
- Notatki: Prosty obszar do dodawania krótkich notatek.
- Responsywny design: Strona będzie dobrze wyglądać na różnych urządzeniach.
- Persistence: Notatki i linki będą zapisywane w pliku JSON na serwerze (dzięki Flask).
Technologia
- Frontend: HTML5, CSS3, JavaScript (Vanilla JS)
- Wykresy: Chart.js (łatwa biblioteka do wykresów)
- Backend: Python 3 + Flask (lekki framework do serwowania API i plików statycznych)
- Monitoring Systemu:
psutil (biblioteka Pythona do dostępu do informacji o systemie)
Struktura Projektu
Stwórz folder o nazwie np. domowy_serwer_dashboard. W środku będą następujące pliki i foldery:
domowy_serwer_dashboard/
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── script.js
├── templates/
│ └── index.html
├── data/
│ ├── links.json (utwórz pusty plik lub z początkową zawartością [])
│ └── notes.json (utwórz pusty plik lub z początkową zawartością [])
├── app.py
├── requirements.txt
Krok 1: Backend (Python Flask)
Backend będzie odpowiedzialny za:
- Serwowanie plików HTML, CSS, JS.
- Udostępnianie API do pobierania danych o zużyciu zasobów serwera.
- Udostępnianie API do zapisywania/ładowania linków i notatek.
1. requirements.txt
Utwórz ten plik w głównym katalogu projektu:
Flask
psutil
Zainstaluj zależności:
pip install -r requirements.txt
2. app.py
Utwórz ten plik w głównym katalogu projektu:
import json
import os
import psutil
from flask import Flask, render_template, jsonify, request
app = Flask(__name__, static_folder='static', template_folder='templates')
# Utwórz katalog 'data', jeśli nie istnieje
DATA_DIR = 'data'
os.makedirs(DATA_DIR, exist_ok=True)
LINKS_FILE = os.path.join(DATA_DIR, 'links.json')
NOTES_FILE = os.path.join(DATA_DIR, 'notes.json')
# Helper do ładowania/zapisywania danych
def load_json(filepath, default_value=[]):
if not os.path.exists(filepath):
with open(filepath, 'w') as f:
json.dump(default_value, f)
return default_value
with open(filepath, 'r', encoding='utf-8') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return default_value
def save_json(filepath, data):
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
# Inicjalizacja plików JSON, jeśli ich nie ma
load_json(LINKS_FILE)
load_json(NOTES_FILE)
@app.route('/')
def index():
return render_template('index.html')
# --- API do danych systemowych ---
@app.route('/api/system_info')
def system_info():
cpu_percent = psutil.cpu_percent(interval=1) # 1s pomiar
ram = psutil.virtual_memory()
disk = psutil.disk_usage('/') # Dysk główny
info = {
'cpu_percent': cpu_percent,
'ram_total_gb': round(ram.total / (1024**3), 2),
'ram_used_gb': round(ram.used / (1024**3), 2),
'ram_percent': ram.percent,
'disk_total_gb': round(disk.total / (1024**3), 2),
'disk_used_gb': round(disk.used / (1024**3), 2),
'disk_percent': disk.percent,
}
return jsonify(info)
# --- API do linków ---
@app.route('/api/links', methods=['GET'])
def get_links():
links = load_json(LINKS_FILE)
return jsonify(links)
@app.route('/api/links', methods=['POST'])
def add_link():
links = load_json(LINKS_FILE)
new_link = request.json
new_link['id'] = len(links) + 1 # Proste ID
links.append(new_link)
save_json(LINKS_FILE, links)
return jsonify({'message': 'Link added', 'link': new_link}), 201
@app.route('/api/links/<int:link_id>', methods=['DELETE'])
def delete_link(link_id):
links = load_json(LINKS_FILE)
links = [link for link in links if link.get('id') != link_id]
save_json(LINKS_FILE, links)
return jsonify({'message': 'Link deleted'}), 200
# --- API do notatek ---
@app.route('/api/notes', methods=['GET'])
def get_notes():
notes = load_json(NOTES_FILE)
return jsonify(notes)
@app.route('/api/notes', methods=['POST'])
def add_note():
notes = load_json(NOTES_FILE)
new_note = request.json
new_note['id'] = len(notes) + 1 # Proste ID
notes.append(new_note)
save_json(NOTES_FILE, notes)
return jsonify({'message': 'Note added', 'note': new_note}), 201
@app.route('/api/notes/<int:note_id>', methods=['PUT'])
def update_note(note_id):
notes = load_json(NOTES_FILE)
updated_data = request.json
for i, note in enumerate(notes):
if note.get('id') == note_id:
notes[i]['content'] = updated_data['content']
save_json(NOTES_FILE, notes)
return jsonify({'message': 'Note updated', 'note': notes[i]}), 200
return jsonify({'message': 'Note not found'}), 404
@app.route('/api/notes/<int:note_id>', methods=['DELETE'])
def delete_note(note_id):
notes = load_json(NOTES_FILE)
notes = [note for note in notes if note.get('id') != note_id]
save_json(NOTES_FILE, notes)
return jsonify({'message': 'Note deleted'}), 200
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
Ważne:
host='0.0.0.0' pozwoli na dostęp do dashboardu z innych urządzeń w sieci lokalnej (np. http://IP_TWOJEGO_SERWERA:5000).
debug=True jest dobre do rozwoju, ale wyłącz to na produkcji (zmień na debug=False).
- Pliki
links.json i notes.json będą tworzone automatycznie w katalogu data/ przy pierwszym uruchomieniu, jeśli nie istnieją.
Krok 2: Frontend (HTML, CSS, JavaScript)
Frontend będzie wyświetlał dane i pozwalał na interakcję.
1. templates/index.html
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard Domowego Serwera</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ctext x='0' y='14' font-size='16'%3E🏠%3C/text%3E%3C/svg%3E">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<header>
<h1>🏠 Dashboard Domowego Serwera</h1>
<p>Twoje centrum dowodzenia w domu.</p>
</header>
<main>
<section class="dashboard-section" id="links-section">
<h2>🔗 Moje Aplikacje / Usługi</h2>
<button class="add-button" id="addLinkBtn">Dodaj Nowy Link</button>
<div class="tiles-grid" id="linksGrid">
<!-- Kafelki z linkami zostaną wstrzyknięte tutaj przez JS -->
</div>
</section>
<section class="dashboard-section" id="resources-section">
<h2>📊 Zużycie Zasobów</h2>
<div class="charts-container">
<div class="chart-card">
<h3>CPU</h3>
<canvas id="cpuChart"></canvas>
<p id="cpuInfo"></p>
</div>
<div class="chart-card">
<h3>RAM</h3>
<canvas id="ramChart"></canvas>
<p id="ramInfo"></p>
</div>
<div class="chart-card">
<h3>Dysk</h3>
<canvas id="diskChart"></canvas>
<p id="diskInfo"></p>
</div>
</div>
</section>
<section class="dashboard-section" id="notes-section">
<h2>📝 Notatki</h2>
<button class="add-button" id="addNoteBtn">Dodaj Nową Notatkę</button>
<div class="notes-container" id="notesContainer">
<!-- Notatki zostaną wstrzyknięte tutaj przez JS -->
</div>
</section>
</main>
<footer>
<p>© 2023 Twój Domowy Serwer. Wszystkie prawa zastrzeżone.</p>
</footer>
<!-- Modale -->
<div id="addLinkModal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h2>Dodaj Nowy Link</h2>
<label for="linkName">Nazwa:</label>
<input type="text" id="linkName" required>
<label for="linkUrl">URL:</label>
<input type="url" id="linkUrl" placeholder="http://twoj_serwer:port" required>
<button id="saveLinkBtn">Zapisz Link</button>
</div>
</div>
<div id="addNoteModal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h2>Dodaj Nową Notatkę</h2>
<textarea id="noteContent" rows="5" placeholder="Wpisz swoją notatkę..." required></textarea>
<button id="saveNoteBtn">Zapisz Notatkę</button>
</div>
</div>
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
2. static/css/style.css
/* style.css */
:root {
--bg-color: #282c34;
--text-color: #abb2bf;
--card-bg: #3c4048;
--accent-color: #61afef;
--button-bg: #56b6c2;
--button-hover-bg: #4fb3bd;
--border-color: #4b525d;
--danger-color: #e06c75;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
margin: 0;
padding: 0;
line-height: 1.6;
display: flex;
flex-direction: column;
min-height: 100vh;
}
header {
background-color: var(--card-bg);
padding: 20px;
text-align: center;
border-bottom: 1px solid var(--border-color);
}
header h1 {
margin: 0;
color: var(--accent-color);
font-size: 2.5em;
}
header p {
font-size: 1.1em;
color: #888;
}
main {
flex-grow: 1;
padding: 20px;
max-width: 1200px;
margin: 20px auto;
display: grid;
gap: 30px;
grid-template-columns: 1fr; /* Domyślnie jedna kolumna */
}
@media (min-width: 768px) {
main {
grid-template-columns: 1fr 1fr; /* Dwie kolumny na większych ekranach */
}
}
@media (min-width: 1024px) {
main {
grid-template-columns: 1fr 1.5fr 1fr; /* Trzy kolumny na bardzo dużych ekranach (links, charts, notes) */
}
}
.dashboard-section {
background-color: var(--card-bg);
border-radius: 8px;
padding: 25px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
border: 1px solid var(--border-color);
}
.dashboard-section h2 {
color: var(--accent-color);
margin-top: 0;
border-bottom: 1px solid var(--border-color);
padding-bottom: 10px;
margin-bottom: 20px;
}
/* Przyciski */
.add-button {
background-color: var(--button-bg);
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
margin-bottom: 20px;
transition: background-color 0.3s ease;
}
.add-button:hover {
background-color: var(--button-hover-bg);
}
/* Kafelki z linkami */
.tiles-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 15px;
}
.tile {
background-color: var(--bg-color);
border-radius: 8px;
padding: 15px;
text-align: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
position: relative;
border: 1px solid var(--border-color);
}
.tile:hover {
transform: translateY(-5px);
}
.tile a {
color: var(--text-color);
text-decoration: none;
font-weight: bold;
font-size: 1.1em;
display: block; /* Umożliwia kliknięcie całego obszaru */
padding: 10px 0;
width: 100%;
}
.tile .delete-button {
position: absolute;
top: 5px;
right: 5px;
background-color: var(--danger-color);
color: white;
border: none;
border-radius: 50%;
width: 25px;
height: 25px;
font-size: 0.8em;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
opacity: 0.7;
transition: opacity 0.3s ease;
}
.tile .delete-button:hover {
opacity: 1;
}
/* Wykresy zasobów */
.charts-container {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
@media (min-width: 600px) {
.charts-container {
grid-template-columns: 1fr 1fr; /* Dwa wykresy obok siebie */
}
}
@media (min-width: 1024px) {
.charts-container {
grid-template-columns: 1fr; /* Na dużych ekranach wracamy do jednej kolumny dla wykresów (bo główna siatka ma 3) */
}
}
.chart-card {
background-color: var(--bg-color);
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
border: 1px solid var(--border-color);
}
.chart-card h3 {
color: var(--accent-color);
margin-top: 0;
}
/* Notatki */
.notes-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
}
.note-card {
background-color: var(--bg-color);
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
position: relative;
border: 1px solid var(--border-color);
display: flex;
flex-direction: column;
}
.note-card p {
margin: 0;
white-space: pre-wrap; /* Zachowuje łamanie linii z textarea */
flex-grow: 1;
}
.note-actions {
display: flex;
gap: 5px;
margin-top: 10px;
justify-content: flex-end;
}
.note-actions button {
background-color: var(--button-bg);
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 0.85em;
transition: background-color 0.3s ease;
}
.note-actions button:hover {
background-color: var(--button-hover-bg);
}
.note-actions button.delete {
background-color: var(--danger-color);
}
.note-actions button.delete:hover {
background-color: #c75a64;
}
/* Modale */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
}
.modal-content {
background-color: var(--card-bg);
margin: auto;
padding: 30px;
border-radius: 8px;
width: 90%;
max-width: 500px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
position: relative;
border: 1px solid var(--border-color);
}
.modal-content h2 {
color: var(--accent-color);
margin-top: 0;
margin-bottom: 20px;
text-align: center;
}
.modal-content label {
display: block;
margin-bottom: 8px;
color: var(--text-color);
font-weight: bold;
}
.modal-content input[type="text"],
.modal-content input[type="url"],
.modal-content textarea {
width: calc(100% - 20px);
padding: 10px;
margin-bottom: 15px;
border: 1px solid var(--border-color);
border-radius: 4px;
background-color: var(--bg-color);
color: var(--text-color);
font-size: 1em;
}
.modal-content input[type="text"]:focus,
.modal-content input[type="url"]:focus,
.modal-content textarea:focus {
outline: none;
border-color: var(--accent-color);
box-shadow: 0 0 0 2px rgba(97, 175, 239, 0.3);
}
.modal-content button {
display: block;
width: 100%;
padding: 12px;
background-color: var(--button-bg);
color: white;
border: none;
border-radius: 5px;
font-size: 1.1em;
cursor: pointer;
transition: background-color 0.3s ease;
}
.modal-content button:hover {
background-color: var(--button-hover-bg);
}
.close-button {
position: absolute;
top: 15px;
right: 20px;
color: var(--text-color);
font-size: 28px;
font-weight: bold;
cursor: pointer;
transition: color 0.3s ease;
}
.close-button:hover,
.close-button:focus {
color: var(--danger-color);
text-decoration: none;
cursor: pointer;
}
footer {
background-color: var(--card-bg);
color: var(--text-color);
text-align: center;
padding: 15px;
font-size: 0.9em;
border-top: 1px solid var(--border-color);
margin-top: 30px;
}
3. static/js/script.js
// script.js
document.addEventListener('DOMContentLoaded', () => {
// --- Elementy DOM ---
const linksGrid = document.getElementById('linksGrid');
const addLinkBtn = document.getElementById('addLinkBtn');
const addLinkModal = document.getElementById('addLinkModal');
const linkNameInput = document.getElementById('linkName');
const linkUrlInput = document.getElementById('linkUrl');
const saveLinkBtn = document.getElementById('saveLinkBtn');
const notesContainer = document.getElementById('notesContainer');
const addNoteBtn = document.getElementById('addNoteBtn');
const addNoteModal = document.getElementById('addNoteModal');
const noteContentInput = document.getElementById('noteContent');
const saveNoteBtn = document.getElementById('saveNoteBtn');
const closeModalButtons = document.querySelectorAll('.modal .close-button');
// --- Wykresy Chart.js ---
let cpuChart, ramChart, diskChart;
// Inicjalizacja wykresów
const initCharts = () => {
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 0 // Wyłącz animacje dla płynniejszych aktualizacji
},
scales: {
y: {
beginAtZero: true,
max: 100,
title: {
display: true,
text: '%'
},
grid: {
color: 'rgba(255, 255, 255, 0.1)' // Jasne linie siatki
},
ticks: {
color: 'rgba(255, 255, 255, 0.7)'
}
},
x: {
grid: {
color: 'rgba(255, 255, 255, 0.1)'
},
ticks: {
color: 'rgba(255, 255, 255, 0.7)'
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
return context.raw + '%';
}
}
}
}
};
const ctxCpu = document.getElementById('cpuChart').getContext('2d');
cpuChart = new Chart(ctxCpu, {
type: 'line',
data: {
labels: Array(10).fill(''), // 10 punktów danych
datasets: [{
label: 'CPU',
data: Array(10).fill(0),
borderColor: '#61afef',
backgroundColor: 'rgba(97, 175, 239, 0.2)',
fill: true,
tension: 0.4
}]
},
options: chartOptions
});
const ctxRam = document.getElementById('ramChart').getContext('2d');
ramChart = new Chart(ctxRam, {
type: 'line',
data: {
labels: Array(10).fill(''),
datasets: [{
label: 'RAM',
data: Array(10).fill(0),
borderColor: '#98c379',
backgroundColor: 'rgba(152, 195, 121, 0.2)',
fill: true,
tension: 0.4
}]
},
options: chartOptions
});
const ctxDisk = document.getElementById('diskChart').getContext('2d');
diskChart = new Chart(ctxDisk, {
type: 'line',
data: {
labels: Array(10).fill(''),
datasets: [{
label: 'Dysk',
data: Array(10).fill(0),
borderColor: '#e5c07b',
backgroundColor: 'rgba(229, 192, 123, 0.2)',
fill: true,
tension: 0.4
}]
},
options: chartOptions
});
};
// --- Funkcje do linków ---
const fetchLinks = async () => {
try {
const response = await fetch('/api/links');
const links = await response.json();
renderLinks(links);
} catch (error) {
console.error('Błąd podczas pobierania linków:', error);
}
};
const renderLinks = (links) => {
linksGrid.innerHTML = ''; // Wyczyść istniejące kafelki
links.forEach(link => {
const tile = document.createElement('div');
tile.className = 'tile';
tile.innerHTML = `
<a href="${link.url}" target="_blank" rel="noopener noreferrer">${link.name}</a>
<button class="delete-button" data-id="${link.id}">×</button>
`;
linksGrid.appendChild(tile);
});
// Dodaj słuchacze do przycisków usuwania
document.querySelectorAll('.tile .delete-button').forEach(button => {
button.addEventListener('click', async (e) => {
const linkId = e.target.dataset.id;
if (confirm('Czy na pewno chcesz usunąć ten link?')) {
try {
const response = await fetch(`/api/links/${linkId}`, {
method: 'DELETE'
});
if (response.ok) {
fetchLinks(); // Odśwież listę
} else {
console.error('Błąd podczas usuwania linku');
}
} catch (error) {
console.error('Błąd sieci podczas usuwania linku:', error);
}
}
});
});
};
const addLink = async () => {
const name = linkNameInput.value.trim();
let url = linkUrlInput.value.trim();
if (!name || !url) {
alert('Proszę podać nazwę i URL linku.');
return;
}
// Dodaj http:// jeśli brakuje protokołu
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'http://' + url;
}
try {
const response = await fetch('/api/links', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, url })
});
if (response.ok) {
linkNameInput.value = '';
linkUrlInput.value = '';
addLinkModal.style.display = 'none';
fetchLinks(); // Odśwież listę
} else {
console.error('Błąd podczas dodawania linku');
}
} catch (error) {
console.error('Błąd sieci podczas dodawania linku:', error);
}
};
// --- Funkcje do notatek ---
const fetchNotes = async () => {
try {
const response = await fetch('/api/notes');
const notes = await response.json();
renderNotes(notes);
} catch (error) {
console.error('Błąd podczas pobierania notatek:', error);
}
};
const renderNotes = (notes) => {
notesContainer.innerHTML = '';
notes.forEach(note => {
const noteCard = document.createElement('div');
noteCard.className = 'note-card';
noteCard.setAttribute('data-id', note.id);
noteCard.innerHTML = `
<p contenteditable="false">${note.content}</p>
<div class="note-actions">
<button class="edit-note-btn">Edytuj</button>
<button class="delete-note-btn delete">Usuń</button>
</div>
`;
notesContainer.appendChild(noteCard);
});
// Dodaj słuchacze do notatek
document.querySelectorAll('.note-card').forEach(card => {
const contentP = card.querySelector('p');
const editBtn = card.querySelector('.edit-note-btn');
const deleteBtn = card.querySelector('.delete-note-btn');
const noteId = card.dataset.id;
editBtn.addEventListener('click', async () => {
if (contentP.contentEditable === 'true') {
// Tryb zapisu
contentP.contentEditable = 'false';
editBtn.textContent = 'Edytuj';
contentP.style.border = 'none';
contentP.style.padding = '0';
const newContent = contentP.textContent;
try {
const response = await fetch(`/api/notes/${noteId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: newContent })
});
if (!response.ok) {
console.error('Błąd podczas aktualizacji notatki');
}
} catch (error) {
console.error('Błąd sieci podczas aktualizacji notatki:', error);
}
} else {
// Tryb edycji
contentP.contentEditable = 'true';
contentP.focus();
editBtn.textContent = 'Zapisz';
contentP.style.border = '1px solid var(--accent-color)';
contentP.style.padding = '5px';
}
});
deleteBtn.addEventListener('click', async () => {
if (confirm('Czy na pewno chcesz usunąć tę notatkę?')) {
try {
const response = await fetch(`/api/notes/${noteId}`, {
method: 'DELETE'
});
if (response.ok) {
fetchNotes();
} else {
console.error('Błąd podczas usuwania notatki');
}
} catch (error) {
console.error('Błąd sieci podczas usuwania notatki:', error);
}
}
});
});
};
const addNote = async () => {
const content = noteContentInput.value.trim();
if (!content) {
alert('Notatka nie może być pusta.');
return;
}
try {
const response = await fetch('/api/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ content })
});
if (response.ok) {
noteContentInput.value = '';
addNoteModal.style.display = 'none';
fetchNotes();
} else {
console.error('Błąd podczas dodawania notatki');
}
} catch (error) {
console.error('Błąd sieci podczas dodawania notatki:', error);
}
};
// --- Funkcje do danych systemowych ---
const updateSystemInfo = async () => {
try {
const response = await fetch('/api/system_info');
const data = await response.json();
// Aktualizuj CPU
cpuChart.data.labels.push('');
cpuChart.data.datasets[0].data.push(data.cpu_percent);
cpuChart.data.labels.shift();
cpuChart.data.datasets[0].data.shift();
cpuChart.update();
document.getElementById('cpuInfo').textContent = `Użycie: ${data.cpu_percent.toFixed(1)}%`;
// Aktualizuj RAM
ramChart.data.labels.push('');
ramChart.data.datasets[0].data.push(data.ram_percent);
ramChart.data.labels.shift();
ramChart.data.datasets[0].data.shift();
ramChart.update();
document.getElementById('ramInfo').textContent = `Użycie: ${data.ram_used_gb.toFixed(2)}GB / ${data.ram_total_gb.toFixed(2)}GB (${data.ram_percent.toFixed(1)}%)`;
// Aktualizuj Dysk
diskChart.data.labels.push('');
diskChart.data.datasets[0].data.push(data.disk_percent);
diskChart.data.labels.shift();
diskChart.data.datasets[0].data.shift();
diskChart.update();
document.getElementById('diskInfo').textContent = `Użycie: ${data.disk_used_gb.toFixed(2)}GB / ${data.disk_total_gb.toFixed(2)}GB (${data.disk_percent.toFixed(1)}%)`;
} catch (error) {
console.error('Błąd podczas pobierania informacji o systemie:', error);
// Można dodać informację dla użytkownika, że nie udało się pobrać danych
}
};
// --- Obsługa Modali ---
const openModal = (modal) => {
modal.style.display = 'flex'; // Używamy flex, żeby wyśrodkować
};
const closeAllModals = () => {
addLinkModal.style.display = 'none';
addNoteModal.style.display = 'none';
};
// --- Event Listenery ---
addLinkBtn.addEventListener('click', () => openModal(addLinkModal));
saveLinkBtn.addEventListener('click', addLink);
addNoteBtn.addEventListener('click', () => openModal(addNoteModal));
saveNoteBtn.addEventListener('click', addNote);
closeModalButtons.forEach(button => {
button.addEventListener('click', closeAllModals);
});
window.addEventListener('click', (event) => {
if (event.target == addLinkModal || event.target == addNoteModal) {
closeAllModals();
}
});
// --- Inicjalizacja przy ładowaniu strony ---
initCharts();
fetchLinks();
fetchNotes();
updateSystemInfo(); // Pierwsze pobranie danych
setInterval(updateSystemInfo, 5000); // Odświeżaj co 5 sekund
});
Krok 3: Uruchomienie Serwera
- Otwórz terminal w katalogu
domowy_serwer_dashboard.
- Upewnij się, że masz zainstalowany Python i wszystkie zależności (przez
pip install -r requirements.txt).
- Uruchom aplikację Flask:
python app.py
- Powinieneś zobaczyć komunikat podobny do:
* Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Running on http://0.0.0.0:5000
Press CTRL+C to quit
- Otwórz przeglądarkę i przejdź pod adres
http://localhost:5000 (jeśli uruchamiasz na tym samym komputerze) lub http://IP_TWOJEGO_SERWERA:5000 (jeśli uruchamiasz na serwerze i chcesz uzyskać dostęp z innego urządzenia w sieci).
Dalsze Ulepszenia
- Autoryzacja: Obecnie każdy, kto zna adres IP i port, ma dostęp. Rozważ dodanie prostej autoryzacji (np. za pomocą Flask-Login).
- Więcej danych systemowych: Dodaj monitorowanie sieci, temperatury (jeśli dostępne z
psutil lub innych narzędzi).
- Powiadomienia: Jeśli zasoby osiągną krytyczny poziom (np. RAM > 90%), możesz wyświetlić powiadomienie na stronie.
- Konfigurowalność: Stwórz interfejs do zarządzania linkami i notatkami bez edycji plików JSON bezpośrednio. (Już to zrobiliśmy, ale możesz to rozszerzyć).
- Dockerizacja: Spakuj aplikację w kontener Docker, co ułatwi wdrożenie i zarządzanie.
- Zaawansowane wykresy: Jeśli potrzebujesz bardziej rozbudowanych opcji, rozważ użycie
Grafana z Prometheus do monitorowania i wizualizacji danych, a ten dashboard mógłby być tylko ich frontendem.
- Ikony dla linków: Dodaj możliwość dodawania ikon (np. z Font Awesome lub własnych plików) do kafelków.
- Tryb ciemny/jasny: Możliwość przełączania motywów. (Obecnie jest tylko ciemny).
- Edycja notatek: Możliwość edycji istniejących notatek (dodana w kodzie JS i Flask).
- Sortowanie/Filtrowanie: Dla dużej liczby linków/notatek.
To solidna podstawa do Twojego domowego pulpitu nawigacyjnego! Powodzenia w jego rozbudowie!