Instalowanie modów/pluginów z panelu

Kocham Modrinth :3
Dodaje #15
This commit is contained in:
Andus 2025-04-13 17:37:14 +02:00
parent 3b689196a0
commit 8ee15c1928
4 changed files with 112 additions and 3 deletions

View file

@ -4,6 +4,7 @@ import shutil
import subprocess import subprocess
import docker import docker
import requests
from flask import Blueprint, jsonify, request, send_from_directory, abort from flask import Blueprint, jsonify, request, send_from_directory, abort
from .auth import oidc from .auth import oidc
@ -214,7 +215,8 @@ def get_config():
with open(server_info_path, 'r') as f: with open(server_info_path, 'r') as f:
server_info = json.load(f) server_info = json.load(f)
return jsonify({"success": True, "config": server_info["config"], "version": server_info["version"], "type": server_info["type"]}) return jsonify({"success": True, "config": server_info["config"], "version": server_info["version"],
"type": server_info["type"]})
@api.route('/config', methods=['POST']) @api.route('/config', methods=['POST'])
@ -292,3 +294,52 @@ def stats():
}) })
except docker.errors.NotFound: except docker.errors.NotFound:
return jsonify({"error": "Container not found"}), 404 return jsonify({"error": "Container not found"}), 404
# Modrinth
@api.route('/modrinth/search')
def modrinth_search():
query = request.args.get("query")
server_type = request.args.get("type") # 'fabric', 'paper', etc.
version = request.args.get("version")
categories = {
'fabric': 'mod',
'paper': 'plugin'
}
category = categories.get(server_type, 'mod') # fallback
response = requests.get(
f"https://api.modrinth.com/v2/search",
params={
"query": query,
"facets": f'[["project_type:{category}"],["versions:{version}"]]',
"limit": 10
}
)
return jsonify(response.json())
@api.route('/modrinth/download', methods=['POST'])
@oidc.require_login
def download_mod():
data = request.json
project_id = data['project_id']
username = data['username']
server_type = data['type']
version_response = requests.get(f"https://api.modrinth.com/v2/project/{project_id}/version")
version_data = version_response.json()
file_url = version_data[0]['files'][0]['url']
file_name = version_data[0]['files'][0]['filename']
folder = 'plugins' if server_type == 'paper' else 'mods'
file_path = f"./servers/mc-{username}/{folder}/{file_name}"
with requests.get(file_url, stream=True) as r:
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return jsonify({"success": True, "file": file_name})

View file

@ -55,8 +55,6 @@ def get_server_config(username):
server_info["config"] = server_config server_info["config"] = server_config
with open(server_info_path, "w") as f: with open(server_info_path, "w") as f:
json.dump(server_info, f, indent=4) json.dump(server_info, f, indent=4)
print(f"Loaded config: {server_config}")
return server_config, server_type, server_version return server_config, server_type, server_version

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

@ -0,0 +1,52 @@
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');
}
})
.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.");
}
});
}

View file

@ -120,6 +120,12 @@
<div class="chart-container"><canvas id="diskChart"></canvas></div> <div class="chart-container"><canvas id="diskChart"></canvas></div>
</div> </div>
</div> </div>
<div class="tab-panel" id="mods">
<h2>Zainstaluj mody/pluginy z Modrinth</h2>
<input type="text" id="mod-search" placeholder="Wyszukaj mod/plugin..." oninput="searchMods()">
<div id="mod-results"></div>
</div>
</div> </div>
<script> <script>
@ -498,6 +504,8 @@
} }
}); });
checkServerStatus(); checkServerStatus();
setInterval(checkServerStatus, 5000); setInterval(checkServerStatus, 5000);
</script> </script>