Przeniesienie JS do osobnych plików

This commit is contained in:
Andus 2025-04-13 18:43:46 +02:00
parent 8ee15c1928
commit ee189b7e72
8 changed files with 290 additions and 313 deletions

View file

@ -313,7 +313,7 @@ def modrinth_search():
f"https://api.modrinth.com/v2/search",
params={
"query": query,
"facets": f'[["project_type:{category}"],["versions:{version}"]]',
"facets": f'[["project_type:{category}"],["categories:{server_type}"],["versions:{version}"]]',
"limit": 10
}
)

View file

@ -89,6 +89,7 @@ def start_server(username):
environment = {
"EULA": "TRUE",
"SERVER_PORT": ports[0],
"ENABLE_RCON": "TRUE",
"MOTD": f"Serwer użytkownika §9{username}",
"TYPE": server_type,
"VERSION": server_version,

52
app/static/js/config.js Normal file
View file

@ -0,0 +1,52 @@
function loadConfig() {
fetch(`/api/config?username=${username}`)
.then(response => response.json())
.then(data => {
const cfg = data.config;
document.getElementById("server-type").value = data.type;
document.getElementById("server-version").value = data.version;
document.getElementById("max-players").value = cfg["max-players"];
document.getElementById("pvp").checked = cfg["pvp"];
document.getElementById("difficulty").value = cfg["difficulty"];
document.getElementById("online-mode").checked = cfg["online-mode"];
document.getElementById("spawn-monsters").checked = cfg["spawn-monsters"];
document.getElementById("spawn-animals").checked = cfg["spawn-animals"];
document.getElementById("allow-nether").checked = cfg["allow-nether"];
document.getElementById("max-build-height").value = cfg["max-build-height"];
document.getElementById("view-distance").value = cfg["view-distance"];
})
.catch(err => {
console.error("Błąd wczytywania konfiguracji: ", err);
alert("Nie udało się załadować konfiguracji serwera.");
});
}
document.querySelector('[onclick="showTab(\'config\')"]').addEventListener('click', loadConfig);
function saveConfig() {
const config = {
type: document.getElementById("server-type").value,
version: document.getElementById("server-version").value,
max_players: document.getElementById("max-players").value,
pvp: document.getElementById("pvp").checked,
difficulty: document.getElementById("difficulty").value,
online_mode: document.getElementById("online-mode").checked,
spawn_monsters: document.getElementById("spawn-monsters").checked,
spawn_animals: document.getElementById("spawn-animals").checked,
allow_nether: document.getElementById("allow-nether").checked,
max_build_height: document.getElementById("max-build-height").value,
view_distance: document.getElementById("view-distance").value
};
fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, config })
}).then(res => res.json()).then(data => {
if (data.success) {
alert("Konfiguracja została zapisana!");
} else {
alert("Błąd zapisywania konfiguracji.");
}
});
}

23
app/static/js/console.js Normal file
View file

@ -0,0 +1,23 @@
function sendCommand() {
const input = $("console-command");
const command = input.value.trim();
if (!command) return;
fetch('/api/command', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, command })
}).then(res => {
if (!res.ok) throw new Error("Nie udało się wysłać komendy.");
input.value = '';
}).catch(err => {
alert("Błąd wysyłania komendy.");
console.error(err);
});
}
function loadLogs() {
fetch(`/api/logs?username=${username}`)
.then(r => r.json())
.then(data => { $("console-log").textContent = data.logs; });
}

19
app/static/js/controls.js vendored Normal file
View file

@ -0,0 +1,19 @@
function sendAction(action) {
fetch(`/api/${action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
}).then(r => r.json()).then(console.log);
}
function deleteServer() {
if (!confirm("Na pewno chcesz usunąć swój serwer? Tej operacji nie można cofnąć!")) return;
fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
})
.then(res => res.ok ? res.json() : res.text().then(t => { throw new Error(t); }))
.then(data => { alert(data.message); location.reload(); })
.catch(err => { alert("Błąd usuwania serwera."); console.error(err); });
}

123
app/static/js/files.js Normal file
View file

@ -0,0 +1,123 @@
function loadFileList(path = '') {
currentPath = path;
$("current-path").textContent = "/" + path;
fetch(`/api/files?username=${username}&path=${encodeURIComponent(path)}`)
.then(r => r.json())
.then(data => {
const list = $("file-list");
list.innerHTML = '';
if (path) {
list.innerHTML += `<li><a class="non-link" href="#" onclick="loadFileList('${path.split('/').slice(0, -1).join('/')}')">⬅️ ..</a></li>`;
}
data.sort((a, b) => a.name.localeCompare(b.name));
data.forEach(entry => {
const itemPath = path ? `${path}/${entry.name}` : entry.name;
const html = entry.is_dir
? `<li>📁 <a class="non-link" href="#" onclick="loadFileList('${itemPath}')">${entry.name}</a>
<a class="non-link" onclick="deleteItem('${itemPath}')">
<i class="fa-solid fa-trash"></i>
</a>
</li>`
: `<li>📄 ${entry.name}
<a class="non-link" href="/api/files/download?username=${username}&path=${encodeURIComponent(itemPath)}" target="_blank">
<i class="fa-solid fa-download"></i>
</a>
<a class="non-link" onclick="deleteItem('${itemPath}')">
<i class="fa-solid fa-trash"></i>
</a>
</li>`;
list.innerHTML += html;
});
});
}
function deleteItem(path) {
if (!confirm(`Czy na pewno chcesz usunąć: ${path}?`)) return;
fetch('/api/files/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, path })
})
.then(res => res.json())
.then(data => {
if (data.success) {
loadFileList(currentPath);
} else {
alert("Błąd podczas usuwania: " + (data.error || "Nieznany"));
}
})
.catch(err => {
console.error(err);
alert("Błąd połączenia z serwerem.");
});
}
document.querySelector('[onclick="showTab(\'files\')"]').addEventListener('click', () => loadFileList());
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('progress-bar');
const progressWrapper = document.getElementById('upload-progress');
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', e => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', () => {
handleFiles(fileInput.files);
});
function handleFiles(files) {
if (!files.length) return;
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
}
formData.append('username', username);
formData.append('path', currentPath);
progressWrapper.classList.remove('hidden');
progressBar.style.width = '0%';
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/files/upload?username=${username}&path=${encodeURIComponent(currentPath)}`);
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.style.width = `${percent}%`;
}
});
xhr.onload = () => {
progressWrapper.classList.add('hidden');
if (xhr.status === 200) {
loadFileList(currentPath);
} else {
alert("Upload się nie udał.");
}
};
xhr.onerror = () => {
progressWrapper.classList.add('hidden');
alert("Upload się nie udał.");
};
xhr.send(formData);
}

View file

@ -1,52 +1,51 @@
function searchMods() {
const query = document.getElementById("mod-search").value;
fetch('/api/config')
.then(response => response.json())
.then(configData => {
console.log(configData);
if (configData.success) {
const serverType = configData.type;
const serverVersion = configData.version;
if (serverType && serverVersion) {
fetch(`/api/modrinth/search?query=${encodeURIComponent(query)}&type=${serverType}&version=${serverVersion}`)
.then(r => r.json())
.then(data => {
const results = document.getElementById("mod-results");
results.innerHTML = "";
data.hits.forEach(mod => {
const modEl = document.createElement("div");
modEl.innerHTML = `
<strong>${mod.title}</strong> - <a onclick="installMod('${mod.project_id}')">Zainstaluj</a><hr>`;
results.appendChild(modEl);
});
function searchMods() {
const query = document.getElementById("mod-search").value;
fetch('/api/config')
.then(response => response.json())
.then(configData => {
console.log(configData);
if (configData.success) {
const serverType = configData.type;
const serverVersion = configData.version;
if (serverType && serverVersion) {
fetch(`/api/modrinth/search?query=${encodeURIComponent(query)}&type=${serverType}&version=${serverVersion}`)
.then(r => r.json())
.then(data => {
const results = document.getElementById("mod-results");
results.innerHTML = "";
data.hits.forEach(mod => {
const modEl = document.createElement("div");
modEl.innerHTML = `
<strong>${mod.title}</strong> - <a onclick="installMod('${mod.project_id}')">Zainstaluj</a><hr>`;
results.appendChild(modEl);
});
} else {
console.error('Server type or version not available');
}
});
} else {
console.error('Server config not found');
console.error('Server type or version not available');
}
})
.catch(err => {
console.error('Error fetching server config:', err);
});
}
function installMod(projectId) {
const serverType = document.getElementById("server-type").value;
const username = "{{ username }}";
fetch('/api/modrinth/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ project_id: projectId, username, type: serverType })
})
.then(r => r.json())
.then(data => {
if (data.success) {
alert(`Zainstalowano: ${data.file}`);
loadFileList();
} else {
alert("Nie udało się zainstalować moda.");
console.error('Server config not found');
}
})
.catch(err => {
console.error('Error fetching server config:', err);
});
}
}
function installMod(projectId) {
const serverType = document.getElementById("server-type").value;
fetch('/api/modrinth/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ project_id: projectId, username, type: serverType })
})
.then(r => r.json())
.then(data => {
if (data.success) {
alert(`Zainstalowano: ${data.file}`);
loadFileList();
} else {
alert("Nie udało się zainstalować moda.");
}
});
}

View file

@ -1,17 +1,16 @@
{% extends "layout.html" %}
{% block content %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<h2>Twój serwer Minecraft</h2>
<div class="tabs">
<button class="tab-button" onclick="showTab('controls')">Sterowanie 🎛️</button>
<button class="tab-button" onclick="showTab('console')">Konsola 📟</button>
<button class="tab-button" onclick="showTab('files')">Pliki 📁</button>
<button class="tab-button" onclick="showTab('config')">Konfiguracja 🛠️</button>
<button class="tab-button" onclick="showTab('statistics')">Statystyki 📈</button>
</div>
<div class="tabs">
<button class="tab-button" onclick="showTab('config')">Konfiguracja 🛠️</button>
<button class="tab-button" onclick="showTab('statistics')">Statystyki 📈</button>
<button class="tab-button" onclick="showTab('mods')">Mody/Pluginy 🧩</button>
</div>
@ -117,7 +116,6 @@
<div class="charts-row">
<div class="chart-container"><canvas id="cpuChart"></canvas></div>
<div class="chart-container"><canvas id="ramChart"></canvas></div>
<div class="chart-container"><canvas id="diskChart"></canvas></div>
</div>
</div>
@ -128,6 +126,12 @@
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="/static/js/controls.js"></script>
<script src="/static/js/console.js"></script>
<script src="/static/js/files.js"></script>
<script src="/static/js/config.js"></script>
<script src="/static/js/mods.js"></script>
<script>
const username = "{{ username }}";
@ -142,229 +146,32 @@
$(id).classList.add('active');
}
function sendAction(action) {
fetch(`/api/${action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
}).then(r => r.json()).then(console.log);
}
function sendCommand() {
const input = $("console-command");
const command = input.value.trim();
if (!command) return;
fetch('/api/command', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, command })
}).then(res => {
if (!res.ok) throw new Error("Nie udało się wysłać komendy.");
input.value = '';
}).catch(err => {
alert("Błąd wysyłania komendy.");
console.error(err);
});
}
function deleteServer() {
if (!confirm("Na pewno chcesz usunąć swój serwer? Tej operacji nie można cofnąć!")) return;
fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
})
.then(res => res.ok ? res.json() : res.text().then(t => { throw new Error(t); }))
.then(data => { alert(data.message); location.reload(); })
.catch(err => { alert("Błąd usuwania serwera."); console.error(err); });
}
function loadLogs() {
fetch(`/api/logs?username=${username}`)
.then(r => r.json())
.then(data => { $("console-log").textContent = data.logs; });
}
let currentPath = '';
function loadFileList(path = '') {
currentPath = path;
$("current-path").textContent = "/" + path;
fetch(`/api/files?username=${username}&path=${encodeURIComponent(path)}`)
function checkServerStatus() {
fetch(`/api/status?username=${username}`)
.then(r => r.json())
.then(data => {
const list = $("file-list");
list.innerHTML = '';
if (path) {
list.innerHTML += `<li><a class="non-link" href="#" onclick="loadFileList('${path.split('/').slice(0, -1).join('/')}')">⬅️ ..</a></li>`;
const statusEl = $("server-status");
if (data.running) {
statusEl.textContent = "Online";
statusEl.style.color = "#2ecc71";
if (currentStatus !== true) {
startStats();
currentStatus = true;
}
} else {
statusEl.textContent = "Offline";
statusEl.style.color = "#e74c3c";
if (currentStatus !== false) {
stopStats();
currentStatus = false;
}
}
data.sort((a, b) => a.name.localeCompare(b.name));
data.forEach(entry => {
const itemPath = path ? `${path}/${entry.name}` : entry.name;
const html = entry.is_dir
? `<li>📁 <a class="non-link" href="#" onclick="loadFileList('${itemPath}')">${entry.name}</a>
<a class="non-link" onclick="deleteItem('${itemPath}')">
<i class="fa-solid fa-trash"></i>
</a>
</li>`
: `<li>📄 ${entry.name}
<a class="non-link" href="/api/files/download?username=${username}&path=${encodeURIComponent(itemPath)}" target="_blank">
<i class="fa-solid fa-download"></i>
</a>
<a class="non-link" onclick="deleteItem('${itemPath}')">
<i class="fa-solid fa-trash"></i>
</a>
</li>`;
list.innerHTML += html;
});
});
}
function deleteItem(path) {
if (!confirm(`Czy na pewno chcesz usunąć: ${path}?`)) return;
fetch('/api/files/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, path })
})
.then(res => res.json())
.then(data => {
if (data.success) {
loadFileList(currentPath);
} else {
alert("Błąd podczas usuwania: " + (data.error || "Nieznany"));
}
})
.catch(err => {
console.error(err);
alert("Błąd połączenia z serwerem.");
});
}
document.querySelector('[onclick="showTab(\'files\')"]').addEventListener('click', () => loadFileList());
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('progress-bar');
const progressWrapper = document.getElementById('upload-progress');
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', e => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', () => {
handleFiles(fileInput.files);
});
function handleFiles(files) {
if (!files.length) return;
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
}
formData.append('username', username);
formData.append('path', currentPath);
progressWrapper.classList.remove('hidden');
progressBar.style.width = '0%';
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/files/upload?username=${username}&path=${encodeURIComponent(currentPath)}`);
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.style.width = `${percent}%`;
}
});
xhr.onload = () => {
progressWrapper.classList.add('hidden');
if (xhr.status === 200) {
loadFileList(currentPath);
} else {
alert("Upload failed.");
}
};
xhr.onerror = () => {
progressWrapper.classList.add('hidden');
alert("Upload failed.");
};
xhr.send(formData);
}
function loadConfig() {
fetch(`/api/config?username=${username}`)
.then(response => response.json())
.then(data => {
const cfg = data.config;
document.getElementById("server-type").value = data.type;
document.getElementById("server-version").value = data.version;
document.getElementById("max-players").value = cfg["max-players"];
document.getElementById("pvp").checked = cfg["pvp"];
document.getElementById("difficulty").value = cfg["difficulty"];
document.getElementById("online-mode").checked = cfg["online-mode"];
document.getElementById("spawn-monsters").checked = cfg["spawn-monsters"];
document.getElementById("spawn-animals").checked = cfg["spawn-animals"];
document.getElementById("allow-nether").checked = cfg["allow-nether"];
document.getElementById("max-build-height").value = cfg["max-build-height"];
document.getElementById("view-distance").value = cfg["view-distance"];
})
.catch(err => {
console.error("Błąd wczytywania konfiguracji: ", err);
alert("Nie udało się załadować konfiguracji serwera.");
});
}
document.querySelector('[onclick="showTab(\'config\')"]').addEventListener('click', loadConfig);
function saveConfig() {
const config = {
type: document.getElementById("server-type").value,
version: document.getElementById("server-version").value,
max_players: document.getElementById("max-players").value,
pvp: document.getElementById("pvp").checked,
difficulty: document.getElementById("difficulty").value,
online_mode: document.getElementById("online-mode").checked,
spawn_monsters: document.getElementById("spawn-monsters").checked,
spawn_animals: document.getElementById("spawn-animals").checked,
allow_nether: document.getElementById("allow-nether").checked,
max_build_height: document.getElementById("max-build-height").value,
view_distance: document.getElementById("view-distance").value
};
fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, config })
}).then(res => res.json()).then(data => {
if (data.success) {
alert("Konfiguracja została zapisana!");
} else {
alert("Błąd zapisywania konfiguracji.");
}
});
}
function startStats() {
if (!statsInterval) {
statsInterval = setInterval(updateStats, 4000);
@ -404,33 +211,6 @@
chart.data.datasets[0].data.push(values[i]);
chart.update();
});
diskChart.data.datasets[0].data[0] = data.disk;
diskChart.update();
});
}
function checkServerStatus() {
fetch(`/api/status?username=${username}`)
.then(r => r.json())
.then(data => {
const statusEl = $("server-status");
if (data.running) {
statusEl.textContent = "Online";
statusEl.style.color = "#2ecc71";
if (currentStatus !== true) {
startStats();
currentStatus = true;
}
} else {
statusEl.textContent = "Offline";
statusEl.style.color = "#e74c3c";
if (currentStatus !== false) {
stopStats();
currentStatus = false;
}
}
});
}
@ -486,26 +266,6 @@
options: chartOptions
});
const diskChart = new Chart($("diskChart"), {
type: 'bar',
data: {
labels: ['Dysk (GB)'],
datasets: [{
label: 'Dysk (GB)',
data: [0],
backgroundColor: '#f39c12',
borderColor: '#f39c12',
borderWidth: 1
}]
},
options: {
...chartOptions,
scales: { ...chartOptions.scales, y: { min: 0, max: 15, ticks: { color: '#aaa' } } }
}
});
checkServerStatus();
setInterval(checkServerStatus, 5000);
</script>