Compare commits

...

9 Commits

6 changed files with 488 additions and 11 deletions

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
# Build stage
FROM node:20-alpine as build-stage
WORKDIR /app
COPY package*.json ./
# Используем npm ci для надежной установки зависимостей из package-lock.json
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

21
nginx.conf Normal file
View File

@@ -0,0 +1,21 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Gzip сжатие для ускорения загрузки
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Для SPA: все запросы, которые не соответствуют файлу, перенаправляются на index.html
location / {
try_files $uri $uri/ /index.html;
}
# Кэширование статических файлов
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}

View File

@@ -21,8 +21,15 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from "vue";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
const authStore = useAuthStore(); const authStore = useAuthStore();
// Восстанавливаем сессию при загрузке приложения
onMounted(() => {
authStore.checkAuth();
});
</script> </script>
<style scoped> <style scoped>

View File

@@ -92,11 +92,19 @@ export const useAuthStore = defineStore("auth", () => {
} }
async function checkAuth() { async function checkAuth() {
isLoading.value = true;
if (token.value) { if (token.value) {
if (user.value) { try {
apiClient.defaults.headers.common["Authorization"] = `Bearer ${token.value}`;
const response = await apiClient.get("/api/user/me");
user.value = response.data;
await fetchUserProfile(); await fetchUserProfile();
} catch (e) {
console.error("Session restoration failed:", e);
handleLogout();
} }
} }
isLoading.value = false;
} }
return { return {
// State // State

View File

@@ -26,6 +26,9 @@
<span v-else>N/A</span> <span v-else>N/A</span>
</div> </div>
<div class="version">{{ server.version_name }}</div> <div class="version">{{ server.version_name }}</div>
<div v-if="server.bluemap_url" class="bluemap-link">
<a :href="server.bluemap_url" target="_blank" rel="noopener noreferrer">Карта мира</a>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -44,6 +47,7 @@ interface GameServer {
max_players: number | null; max_players: number | null;
version_name: string | null; version_name: string | null;
ping_proxy_server: number | null; ping_proxy_server: number | null;
bluemap_url: string | null;
} }
const servers = ref<GameServer[]>([]); const servers = ref<GameServer[]>([]);
@@ -140,4 +144,20 @@ onUnmounted(() => {
margin-bottom: 1rem; margin-bottom: 1rem;
font-weight: bold; font-weight: bold;
} }
.bluemap-link {
margin-top: 0.5rem;
text-align: right;
}
.bluemap-link a {
display: inline-block;
padding: 0.25rem 0.5rem;
background-color: #3eaf7c;
color: white;
text-decoration: none;
border-radius: 4px;
font-size: 0.9em;
}
.bluemap-link a:hover {
background-color: #339265;
}
</style> </style>

View File

@@ -10,7 +10,7 @@
<select v-model="form.importerType"> <select v-model="form.importerType">
<option value="simple">Простой ZIP</option> <option value="simple">Простой ZIP</option>
<option value="curseforge">CurseForge</option> <option value="curseforge">CurseForge</option>
<option value="modrinth" disabled>Modrinth (в разработке)</option> <option value="modrinth">Modrinth (.mrpack)</option>
</select> </select>
</div> </div>
@@ -41,29 +41,139 @@
<!-- Поля для источника --> <!-- Поля для источника -->
<div v-if="form.importMethod === 'file'" class="form-group"> <div v-if="form.importMethod === 'file'" class="form-group">
<label for="modpack-file">Файл модпака (.zip)</label> <label for="modpack-file">Файл модпака (.zip, .mrpack)</label>
<input id="modpack-file" type="file" @change="onFileSelected" :required="form.importMethod === 'file'" accept=".zip" /> <input id="modpack-file" type="file" @change="onFileSelected" :required="form.importMethod === 'file'" accept=".zip,.mrpack" />
</div> </div>
<div v-if="form.importMethod === 'url'" class="form-group"> <div v-if="form.importMethod === 'url'" class="form-group">
<label for="sourceUrl">URL страницы модпака на CurseForge</label> <label for="sourceUrl">URL страницы модпака на CurseForge</label>
<input id="sourceUrl" v-model="form.sourceUrl" type="url" :required="form.importMethod === 'url'" /> <input id="sourceUrl" v-model="form.sourceUrl" type="url" :required="form.importMethod === 'url'" />
</div> </div>
<div v-if="error" class="error-message">{{ error }}</div> <div v-if="importJob.jobId" class="job-status">
<div v-if="successMessage" class="success-message">{{ successMessage }}</div> <h3>Статус импорта</h3>
<div class="progress-bar">
<div class="progress" :style="{ width: importJob.progress + '%' }"></div>
</div>
<p>{{ importJob.message }} ({{ importJob.progress }}%)</p>
<div v-if="importJob.status === 'failed'" class="error-message">Ошибка: {{ importJob.message }}</div>
<div v-if="importJob.status === 'completed'" class="success-message">Импорт успешно завершен!</div>
</div>
<button type="submit" :disabled="isLoading"> <div v-if="error && !importJob.jobId" class="error-message">{{ error }}</div>
{{ isLoading ? "Импорт..." : "Импортировать" }} <!-- <div v-if="successMessage" class="success-message">{{ successMessage }}</div> -->
<button type="submit" :disabled="isLoading || (importJob.jobId !== null && importJob.status !== 'completed' && importJob.status !== 'failed')">
{{ isLoading ? "Запуск..." : "Импортировать" }}
</button> </button>
</form> </form>
</div> </div>
<!-- СПИСОК МОДПАКОВ -->
<div class="modpacks-section">
<h2>Существующие модпаки</h2>
<div v-if="modpacksLoading">Загрузка...</div>
<table v-else-if="modpacks.length > 0" class="modpacks-table">
<thead>
<tr>
<th>Имя</th>
<th>Отображаемое имя</th>
<th>MC Version</th>
<th>Обновлено</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<tr v-for="m in modpacks" :key="m.id">
<td>{{ m.name }}</td>
<td>{{ m.display_name }}</td>
<td>{{ m.minecraft_version }}</td>
<td>{{ formatDate(m.updated_at) }}</td>
<td>
<button @click="openUpdateModal(m)" class="btn-small">Обновить</button>
</td>
</tr>
</tbody>
</table>
<p v-else>Нет модпаков</p>
</div>
<!-- МОДАЛЬНОЕ ОКНО ОБНОВЛЕНИЯ -->
<div v-if="updateModal.show" class="modal-overlay" @click.self="closeUpdateModal">
<div class="modal-content">
<h3>Обновить модпак: {{ updateModal.modpack?.name }}</h3>
<form @submit.prevent="handleUpdate" class="import-form">
<div class="form-group">
<label>Тип сборки</label>
<select v-model="updateForm.importerType">
<option value="simple">Простой ZIP</option>
<option value="curseforge">CurseForge</option>
<option value="modrinth">Modrinth (.mrpack)</option>
</select>
</div>
<div class="form-group">
<label>Метод импорта</label>
<div class="radio-group">
<label><input type="radio" v-model="updateForm.importMethod" value="file" /> Файл</label>
<label><input type="radio" v-model="updateForm.importMethod" value="url" :disabled="updateForm.importerType !== 'curseforge'" /> URL</label>
</div>
</div>
<div class="form-group">
<label>Версия Minecraft (опционально)</label>
<input v-model="updateForm.mcVersion" type="text" :placeholder="updateModal.modpack?.minecraft_version" />
</div>
<div v-if="updateForm.importMethod === 'file'" class="form-group">
<label>Файл модпака</label>
<input type="file" @change="onUpdateFileSelected" accept=".zip,.mrpack" />
</div>
<div v-if="updateForm.importMethod === 'url'" class="form-group">
<label>URL страницы модпака</label>
<input v-model="updateForm.sourceUrl" type="url" />
</div>
<div v-if="updateJob.jobId" class="job-status">
<div class="progress-bar">
<div class="progress" :style="{ width: updateJob.progress + '%' }"></div>
</div>
<p>{{ updateJob.message }} ({{ updateJob.progress }}%)</p>
<div v-if="updateJob.status === 'failed'" class="error-message">Ошибка: {{ updateJob.message }}</div>
<div v-if="updateJob.status === 'completed'" class="success-message">Обновление завершено!</div>
</div>
<div class="modal-actions">
<button type="submit" :disabled="updateLoading || (updateJob.jobId !== null && updateJob.status !== 'completed' && updateJob.status !== 'failed')">
{{ updateLoading ? "Запуск..." : "Обновить" }}
</button>
<button type="button" @click="closeUpdateModal" class="btn-secondary">Отмена</button>
</div>
</form>
</div>
</div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, watch } from "vue"; import { ref, reactive, watch, onMounted, onUnmounted } from "vue";
import apiClient from "@/api/axios"; import apiClient from "@/api/axios";
import { useAuthStore } from "@/stores/auth";
const authStore = useAuthStore();
// ===== Интерфейсы =====
interface Modpack {
id: number;
name: string;
display_name: string;
minecraft_version: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
// ===== Состояние списка модпаков =====
const modpacks = ref<Modpack[]>([]);
const modpacksLoading = ref(true);
// ===== Форма импорта =====
const form = reactive({ const form = reactive({
name: "", name: "",
displayName: "", displayName: "",
@@ -78,6 +188,39 @@ const isLoading = ref(false);
const error = ref<string | null>(null); const error = ref<string | null>(null);
const successMessage = ref<string | null>(null); const successMessage = ref<string | null>(null);
// Состояние задачи импорта
const importJob = reactive({
jobId: null as number | null,
status: "" as string,
progress: 0,
message: "" as string,
});
// ===== Модальное окно обновления =====
const updateModal = reactive({
show: false,
modpack: null as Modpack | null,
});
const updateForm = reactive({
importerType: "simple",
importMethod: "file",
mcVersion: "",
sourceUrl: "",
file: null as File | null,
});
const updateLoading = ref(false);
const updateJob = reactive({
jobId: null as number | null,
status: "" as string,
progress: 0,
message: "" as string,
});
let ws: WebSocket | null = null;
// ===== Watchers =====
watch( watch(
() => form.importerType, () => form.importerType,
(newType) => { (newType) => {
@@ -87,6 +230,45 @@ watch(
}, },
); );
watch(
() => updateForm.importerType,
(newType) => {
if (newType !== "curseforge" && updateForm.importMethod === "url") {
updateForm.importMethod = "file";
}
},
);
// ===== Helpers =====
const formatDate = (dateStr: string) => {
return new Date(dateStr).toLocaleString();
};
const getStatusMessage = (status: string) => {
switch (status) {
case 'pending': return 'Ожидание очереди...';
case 'downloading': return 'Скачивание файлов...';
case 'processing': return 'Обработка...';
case 'completed': return 'Готово';
case 'failed': return 'Ошибка';
default: return status;
}
};
// ===== Fetching =====
const fetchModpacks = async () => {
modpacksLoading.value = true;
try {
const response = await apiClient.get<Modpack[]>("/admin/modpacks");
modpacks.value = response.data || [];
} catch (e) {
console.error("Failed to fetch modpacks", e);
} finally {
modpacksLoading.value = false;
}
};
// ===== File handlers =====
const onFileSelected = (event: Event) => { const onFileSelected = (event: Event) => {
const target = event.target as HTMLInputElement; const target = event.target as HTMLInputElement;
if (target.files && target.files[0]) { if (target.files && target.files[0]) {
@@ -94,6 +276,73 @@ const onFileSelected = (event: Event) => {
} }
}; };
const onUpdateFileSelected = (event: Event) => {
const target = event.target as HTMLInputElement;
if (target.files && target.files[0]) {
updateForm.file = target.files[0];
}
};
// ===== WebSocket =====
const connectWebSocket = (targetJob: { jobId: number | null; status: string; progress: number; message: string }, onComplete?: () => void) => {
if (ws) {
ws.close();
}
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const host = window.location.host;
const url = `${protocol}//${host}/api/admin/ws/jobs?token=${authStore.token}`;
ws = new WebSocket(url);
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.job_id === targetJob.jobId) {
targetJob.status = data.status;
targetJob.progress = data.progress;
targetJob.message = data.error_message || getStatusMessage(data.status);
if (data.status === 'completed') {
isLoading.value = false;
updateLoading.value = false;
if (onComplete) onComplete();
} else if (data.status === 'failed') {
isLoading.value = false;
updateLoading.value = false;
}
}
} catch (e) {
console.error("WS parse error", e);
}
};
ws.onclose = () => {
console.log("WS closed");
};
};
// ===== Modal handlers =====
const openUpdateModal = (modpack: Modpack) => {
updateModal.show = true;
updateModal.modpack = modpack;
updateForm.importerType = "simple";
updateForm.importMethod = "file";
updateForm.mcVersion = "";
updateForm.sourceUrl = "";
updateForm.file = null;
updateJob.jobId = null;
updateJob.status = "";
updateJob.progress = 0;
updateJob.message = "";
};
const closeUpdateModal = () => {
updateModal.show = false;
updateModal.modpack = null;
};
// ===== Import handler =====
const handleImport = async () => { const handleImport = async () => {
if (form.importMethod === "file" && !form.file) { if (form.importMethod === "file" && !form.file) {
error.value = "Пожалуйста, выберите файл для импорта."; error.value = "Пожалуйста, выберите файл для импорта.";
@@ -107,6 +356,11 @@ const handleImport = async () => {
isLoading.value = true; isLoading.value = true;
error.value = null; error.value = null;
successMessage.value = null; successMessage.value = null;
importJob.jobId = null;
importJob.status = "";
importJob.progress = 0;
importJob.message = "";
const formData = new FormData(); const formData = new FormData();
formData.append("name", form.name); formData.append("name", form.name);
@@ -127,13 +381,88 @@ const handleImport = async () => {
"Content-Type": "multipart/form-data", "Content-Type": "multipart/form-data",
}, },
}); });
successMessage.value = response.data;
if (response.status === 202 && response.data.job_id) {
importJob.jobId = response.data.job_id;
importJob.status = 'pending';
importJob.message = 'Задача создана...';
connectWebSocket(importJob, fetchModpacks);
} else {
successMessage.value = response.data;
isLoading.value = false;
fetchModpacks();
}
} catch (e: any) { } catch (e: any) {
error.value = e.response?.data || "Произошла ошибка при импорте."; error.value = e.response?.data || "Произошла ошибка при импорте.";
} finally {
isLoading.value = false; isLoading.value = false;
} }
}; };
// ===== Update handler =====
const handleUpdate = async () => {
if (!updateModal.modpack) return;
if (updateForm.importMethod === "file" && !updateForm.file) {
return;
}
if (updateForm.importMethod === "url" && !updateForm.sourceUrl) {
return;
}
updateLoading.value = true;
updateJob.jobId = null;
updateJob.status = "";
updateJob.progress = 0;
updateJob.message = "";
const formData = new FormData();
formData.append("modpackName", updateModal.modpack.name);
formData.append("importerType", updateForm.importerType);
formData.append("importMethod", updateForm.importMethod);
if (updateForm.mcVersion) {
formData.append("mcVersion", updateForm.mcVersion);
}
if (updateForm.importMethod === "file" && updateForm.file) {
formData.append("file", updateForm.file);
} else if (updateForm.importMethod === "url") {
formData.append("sourceUrl", updateForm.sourceUrl);
}
try {
const response = await apiClient.post("/admin/modpacks/update", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
if (response.status === 202 && response.data.job_id) {
updateJob.jobId = response.data.job_id;
updateJob.status = 'pending';
updateJob.message = 'Задача создана...';
connectWebSocket(updateJob, () => {
fetchModpacks();
});
} else {
updateLoading.value = false;
fetchModpacks();
}
} catch (e: any) {
console.error("Update error", e);
updateLoading.value = false;
}
};
// ===== Lifecycle =====
onMounted(() => {
fetchModpacks();
});
onUnmounted(() => {
if (ws) ws.close();
});
</script> </script>
<style scoped> <style scoped>
@@ -189,4 +518,81 @@ button {
button:disabled { button:disabled {
background-color: #ccc; background-color: #ccc;
} }
/* Modpacks List Section */
.modpacks-section {
margin-top: 2rem;
}
.modpacks-table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
.modpacks-table th,
.modpacks-table td {
border: 1px solid #ddd;
padding: 0.75rem;
text-align: left;
}
.modpacks-table th {
background-color: #f5f5f5;
}
.btn-small {
padding: 0.4rem 0.8rem;
font-size: 0.9em;
}
/* Modal Overlay */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 2rem;
border-radius: 8px;
max-width: 500px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
.modal-actions {
display: flex;
gap: 1rem;
margin-top: 1rem;
}
.btn-secondary {
background-color: #6c757d;
}
.btn-secondary:hover {
background-color: #5a6268;
}
/* Progress bar */
.progress-bar {
height: 20px;
background: #eee;
border-radius: 4px;
overflow: hidden;
margin-bottom: 0.5rem;
}
.progress {
height: 100%;
background: #42b983;
transition: width 0.3s;
}
.job-status {
margin-top: 1rem;
padding: 1rem;
border: 1px solid #ddd;
border-radius: 4px;
}
</style> </style>