Files
Docker-Proxy/hubcmdui/web/admin.html
T

1474 lines
55 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Docker 镜像代理加速 - 管理面板</title>
<link rel="icon" href="https://cdn.jsdelivr.net/gh/dqzboy/Blog-Image/BlogCourse/docker-proxy.png" type="image/png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/editor.md@1.5.0/css/editormd.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/editor.md@1.5.0/editormd.min.js"></script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Lato', 'Helvetica', 'Arial', sans-serif;
line-height: 1.6;
color: #24292e;
margin: 0;
padding: 20px;
background-color: #f6f8fa;
}
.container {
background: transparent;
box-shadow: none;
padding: 0;
}
h1, h2 {
border-bottom: 2px solid #eaecef;
padding-bottom: 0.5em;
margin-bottom: 1em;
color: #0366d6;
}
label {
display: block;
margin-top: 20px;
border-bottom: none;
padding-bottom: 0;
color: #24292e;
font-size: 20px;
}
input[type="text"], input[type="url"], input[type="password"], select {
width: 100%;
padding: 8px;
margin-top: 5px;
border: 1px solid #d1d5da;
border-radius: 4px;
box-sizing: border-box;
font-family: inherit;
font-size: inherit;
}
button {
background-color: #2ea44f;
color: white;
border: none;
padding: 10px 20px;
margin-top: 20px;
border-radius: 4px;
cursor: pointer;
font-family: inherit;
font-size: inherit;
}
button:hover {
background-color: #2c974b;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #d1d5da;
padding: 8px;
text-align: left;
}
th {
background-color: #f6f8fa;
font-weight: normal;
}
.action-btn {
background-color: #0366d6;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
font-family: inherit;
font-size: inherit;
}
.action-btn:hover {
background-color: #0256b9;
}
.add-btn {
background-color: #2ea44f;
color: white;
border: none;
padding: 10px 20px;
margin-top: 10px;
border-radius: 4px;
cursor: pointer;
font-family: inherit;
font-size: inherit;
}
.add-btn:hover {
background-color: #2c974b;
}
#menuPreview {
margin-top: 20px;
padding: 10px;
background-color: #f6f8fa;
border: 1px solid #d1d5da;
border-radius: 4px;
}
#menuPreview a {
margin-right: 15px;
color: #0366d6;
text-decoration: none;
}
#menuPreview a:hover {
text-decoration: underline;
}
.hidden {
display: none;
}
.login-modal {
display: flex;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
justify-content: center;
align-items: center;
}
.login-content {
background-color: rgba(255, 255, 255, 0.8);
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 300px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
position: relative;
}
.login-header h2 {
color: #333;
font-size: 28px;
margin-bottom: 20px;
text-align: center;
}
.login-form input[type="text"],
.login-form input[type="password"] {
width: 100%;
padding: 12px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
font-size: 16px;
}
.login-form button {
width: 100%;
padding: 12px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 18px;
margin-top: 20px;
}
.login-form button:hover {
background-color: #45a049;
}
.captcha-container {
display: flex;
align-items: center;
margin: 10px 0;
}
.captcha-container input {
flex: 1;
margin-right: 10px;
}
.captcha-container span {
padding: 12px;
background-color: #f1f1f1;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.user-management {
position: absolute;
top: 20px;
right: 20px;
cursor: pointer;
}
.user-management i {
font-size: 24px;
color: #0366d6;
}
.menu-label {
font-size: 20px;
color: #24292e;
}
.admin-title {
font-size: 24px;
color: #0366d6;
}
.password-hint {
color: gray;
font-size: 12px;
margin-top: 5px;
}
.admin-container {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 200px;
background-color: #f6f8fa;
border-right: 1px solid #e1e4e8;
padding-top: 20px;
}
.sidebar h2 {
padding: 0 20px;
margin-bottom: 20px;
font-size: 18px;
color: #24292e;
}
.sidebar ul {
list-style-type: none;
padding: 0;
margin: 0;
}
.sidebar li {
padding: 10px 20px;
cursor: pointer;
color: #0366d6;
}
.sidebar li:hover {
background-color: #f1f8ff;
}
.sidebar li.active {
background-color: #f1f8ff;
font-weight: bold;
border-right: 1px solid #e1e4e8;
}
.content-area {
flex-grow: 1;
padding: 20px 30px;
}
.content-section {
background-color: transparent;
box-shadow: none;
padding: 0;
margin-bottom: 30px;
display: none;
}
.content-section.active {
display: block;
}
/* 全局样式 */
.content-section {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
padding: 20px;
margin-bottom: 20px;
}
.content-section h1.admin-title {
font-size: 24px;
color: #24292e;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #e1e4e8;
}
.content-section h2.menu-label {
font-size: 18px;
color: #0366d6;
margin-top: 30px;
margin-bottom: 15px;
}
/* 表单元素样式 */
.content-section label {
display: block;
margin-top: 15px;
margin-bottom: 5px;
font-weight: 600;
color: #24292e;
}
.content-section input[type="text"],
.content-section input[type="url"],
.content-section input[type="password"] {
width: 100%;
padding: 8px 12px;
margin-bottom: 15px;
border: 1px solid #e1e4e8;
border-radius: 4px;
font-size: 14px;
}
.content-section input[type="text"],
.content-section input[type="url"],
.content-section input[type="password"] {
width: 100%;
max-width: 400px;
padding: 8px 12px;
margin-bottom: 15px;
border: 1px solid #e1e4e8;
border-radius: 4px;
font-size: 14px;
}
.content-section button {
background-color: #2ea44f;
color: white;
border: none;
padding: 10px 16px;
margin-top: 10px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s ease;
}
.content-section button:hover {
background-color: #2c974b;
}
/* 表格样式优化 */
.content-section table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
margin-top: 20px;
}
.content-section th,
.content-section td {
border: 1px solid #e1e4e8;
padding: 12px;
text-align: left;
}
.content-section th {
background-color: #f6f8fa;
font-weight: 600;
color: #24292e;
}
.content-section tr:nth-child(even) {
background-color: #f6f8fa;
}
/* 特定功能区域样式 */
#basic-config input[type="url"],
#basic-config input[type="text"] {
max-width: 400px;
}
#password-change .password-hint {
font-size: 12px;
color: #6a737d;
margin-top: 5px;
display: block;
}
#password-change #passwordStrength {
font-size: 14px;
margin-top: 5px;
display: block;
}
/* 响应式设计 */
@media (max-width: 768px) {
.content-section h1.admin-title {
font-size: 20px;
}
.content-section input[type="text"],
.content-section input[type="url"],
.content-section input[type="password"] {
max-width: 100%;
}
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 3px solid #0366d6;
animation: spin 1s linear infinite;
}
</style>
</head>
<body>
<div id="loadingIndicator" style="display: flex; justify-content: center; align-items: center; height: 100vh;">
<p>加载中...</p>
</div>
<div class="admin-container" id="adminContainer" style="display: none;">
<div class="sidebar">
<h2>管理面板</h2>
<ul>
<li class="active" data-section="basic-config">基本配置</li>
<li data-section="menu-management">菜单管理</li>
<li data-section="ad-management">广告管理</li>
<li data-section="documentation-management">文档管理</li>
<li data-section="password-change">修改密码</li>
<li data-section="docker-status">Docker 服务状态</li>
</ul>
</div>
<div class="content-area">
<div class="container">
<!-- 将原有的内容分成四个部分,每个部分对应一个侧边栏项目 -->
<div id="basic-config" class="content-section active">
<label for="logoUrl">Logo URL: (可选)</label>
<input type="url" id="logoUrl" name="logoUrl">
<button type="button" onclick="saveLogo()">保存 Logo</button>
<label for="proxyDomain">Docker镜像代理地址: (必填)</label>
<input type="text" id="proxyDomain" name="proxyDomain" required>
<button type="button" onclick="saveProxyDomain()">保存代理地址</button>
</div>
<div id="menu-management" class="content-section">
<h2 class="menu-label">菜单项管理</h2>
<table id="menuTable">
<thead>
<tr>
<th>文本</th>
<th>链接 (可选)</th>
<th>新标签页打开</th>
<th>操作</th>
</tr>
</thead>
<tbody id="menuTableBody">
<!-- 菜单项将在这里动态添加 -->
</tbody>
</table>
<button type="button" class="add-btn" onclick="showNewMenuItemRow()">添加菜单项</button>
</div>
<div id="ad-management" class="content-section">
<h2 class="menu-label">广告管理</h2>
<table id="adTable">
<thead>
<tr>
<th>广告图片URL</th>
<th>跳转URL</th>
<th>操作</th>
</tr>
</thead>
<tbody id="adTableBody">
<!-- 广告项将在这里动态添加 -->
</tbody>
</table>
<button type="button" class="add-btn" onclick="showNewAdRow()">添加广告</button>
</div>
<!-- 文档管理部分 -->
<div id="documentation-management" class="content-section">
<h2 class="menu-label">文档管理</h2>
<button type="button" onclick="newDocument()">新建文档</button>
<table id="documentTable">
<thead>
<tr>
<th>文章</th>
<th>操作</th>
</tr>
</thead>
<tbody id="documentTableBody">
<!-- 文档列表将在这里动态添加 -->
</tbody>
</table>
<div id="editorContainer" style="display: none;">
<input type="text" id="documentTitle" placeholder="文档标题">
<div id="editormd">
<textarea style="display:none;"></textarea>
</div>
<button type="button" onclick="saveDocument()">保存文档</button>
<button type="button" onclick="cancelEdit()">取消</button>
</div>
</div>
<!-- 修改密码部分 -->
<div id="password-change" class="content-section">
<h2 class="menu-label">修改密码</h2>
<label for="currentPassword">当前密码</label>
<input type="password" id="currentPassword" name="currentPassword">
<label for="newPassword">新密码</label>
<span class="password-hint" id="passwordHint">密码必须包含至少一个字母、一个数字和一个特殊字符,长度在8到16个字符之间</span>
<input type="password" id="newPassword" name="newPassword" oninput="checkPasswordStrength()">
<span id="passwordStrength" style="color: red;"></span>
<button type="button" onclick="changePassword()">修改密码</button>
</div>
<!-- Docker服务状态 -->
<div id="docker-status" class="content-section">
<h1 class="admin-title">Docker 服务状态</h1>
<table id="dockerStatusTable">
<thead>
<tr>
<th>容器 ID</th>
<th>名称</th>
<th>镜像</th>
<th>状态</th>
<th>CPU</th>
<th>内存</th>
<th>创建时间</th>
</tr>
</thead>
<tbody id="dockerStatusTableBody">
<!-- Docker 容器状态将在这里动态添加 -->
</tbody>
</table>
<button type="button" onclick="refreshDockerStatus()">刷新状态</button>
</div>
</div>
</div>
</div>
<div class="login-modal" id="loginModal" style="display: none;">
<div class="login-content">
<div class="login-header">
<h2>登入</h2>
</div>
<form class="login-form">
<input type="text" id="username" name="username" placeholder="用户名" required>
<input type="password" id="password" name="password" placeholder="密码" required>
<div class="captcha-container">
<input type="text" id="captcha" name="captcha" placeholder="验证码" required>
<span id="captchaText" onclick="refreshCaptcha()">点击刷新验证码</span>
</div>
<button type="button" onclick="login()">登录</button>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dragula/3.7.2/dragula.min.js"></script>
<script>
let menuItems = [];
let adImages = [];
let isLoggedIn = false;
let editingIndex = -1; // 用于记录当前编辑的菜单项索引
let editor;
let currentEditingDoc = null;
let documents = [];
// 初始化编辑器
function initEditor() {
if (editor) {
console.log('Editor already initialized');
return;
}
try {
editor = editormd("editormd", {
width: "100%",
height: 640,
path : "https://cdn.jsdelivr.net/npm/editor.md@1.5.0/lib/",
theme : "default",
previewTheme : "default",
editorTheme : "default",
markdown : "",
codeFold : true,
saveHTMLToTextarea : true,
searchReplace : true,
watch : true, // 开启实时预览
htmlDecode : "style,script,iframe|on*",
toolbar : true,
toolbarIcons : "full",
placeholder: "请输入Markdown格式的文档...",
emoji : true,
taskList : true,
tocm : true,
tex : true,
flowChart : true,
sequenceDiagram : true,
onload : function() {
console.log('Editor.md loaded successfully');
// 在加载完成后,立即切换到编辑模式
this.unwatch();
this.watch();
}
});
console.log('Editor initialized successfully');
} catch (error) {
console.error('Error initializing editor:', error);
}
}
function newDocument() {
currentEditingDoc = null;
document.getElementById('documentTitle').value = '';
editor.setMarkdown('');
showEditor();
}
function showEditor() {
document.getElementById('documentTable').style.display = 'none';
document.getElementById('editorContainer').style.display = 'block';
if (editor) {
// 确保每次显示编辑器时都切换到编辑模式
editor.unwatch();
editor.watch();
}
}
function hideEditor() {
document.getElementById('documentTable').style.display = 'table';
document.getElementById('editorContainer').style.display = 'none';
}
function cancelEdit() {
hideEditor();
}
async function saveDocument() {
const title = document.getElementById('documentTitle').value.trim();
const content = editor.getMarkdown();
if (!title) {
alert('请输入文档标题');
return;
}
try {
const response = await fetch('/api/documentation', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: currentEditingDoc ? currentEditingDoc.id : null,
title,
content
})
});
if (response.ok) {
alert('文档保存成功');
hideEditor();
loadDocumentList();
} else {
throw new Error('保存失败');
}
} catch (error) {
console.error('保存文档失败:', error);
alert('保存文档失败: ' + error.message);
}
}
async function loadDocumentList() {
try {
const response = await fetch('/api/documentation-list');
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.error}, details: ${errorData.details}`);
}
documents = await response.json();
console.log('Received documents:', documents);
renderDocumentList();
} catch (error) {
console.error('加载文档列表失败:', error);
alert('加载文档列表失败: ' + error.message);
}
}
function renderDocumentList() {
const tbody = document.getElementById('documentTableBody');
tbody.innerHTML = '';
if (documents.length === 0) {
tbody.innerHTML = '<tr><td colspan="2">没有找到文档</td></tr>';
return;
}
documents.forEach(doc => {
const row = `
<tr>
<td>${doc.title || 'Untitled Document'}</td>
<td>
<button onclick="editDocument('${doc.id}')">编辑</button>
<button onclick="deleteDocument('${doc.id}')">删除</button>
<button onclick="togglePublish('${doc.id}')">${doc.published ? '取消发布' : '发布'}</button>
</td>
</tr>
`;
tbody.innerHTML += row;
});
}
function editDocument(id) {
currentEditingDoc = documents.find(doc => doc.id === id);
document.getElementById('documentTitle').value = currentEditingDoc.title;
editor.setMarkdown(currentEditingDoc.content);
showEditor();
}
async function deleteDocument(id) {
if (confirm('确定要删除这个文档吗?')) {
try {
const response = await fetch(`/api/documentation/${id}`, { method: 'DELETE' });
if (response.ok) {
alert('文档删除成功');
loadDocumentList();
} else {
throw new Error('删除失败');
}
} catch (error) {
console.error('删除文档失败:', error);
alert('删除文档失败: ' + error.message);
}
}
}
async function togglePublish(id) {
try {
const response = await fetch(`/api/documentation/${id}/toggle-publish`, { method: 'POST' });
if (response.ok) {
loadDocumentList();
} else {
throw new Error('操作失败');
}
} catch (error) {
console.error('更改发布状态失败:', error);
alert('更改发布状态失败: ' + error.message);
}
}
function getMenuItems() {
return menuItems;
}
function setupMenuDeleteButtons() {
const deleteButtons = document.querySelectorAll('.menu-delete-btn');
deleteButtons.forEach((button) => {
button.addEventListener('click', () => {
const row = button.closest('tr');
const index = parseInt(row.getAttribute('data-index'));
const menuText = row.querySelector('.menu-text').value;
if (confirm(`确定要删除菜单项 "${menuText}" 吗?`)) {
deleteMenuItem(index);
}
});
});
}
function renderMenuItems() {
const tbody = document.getElementById('menuTableBody');
tbody.innerHTML = '';
menuItems.forEach((item, index) => {
const row = `
<tr data-index="${index}">
<td><input type="text" class="menu-text" value="${item.text}" disabled></td>
<td><input type="url" class="menu-link" value="${item.link || ''}" disabled></td>
<td>
<select class="menu-newtab" disabled>
<option value="false" ${item.newTab ? '' : 'selected'}>否</option>
<option value="true" ${item.newTab ? 'selected' : ''}>是</option>
</select>
</td>
<td>
<button type="button" class="action-btn edit-btn">编辑</button>
<button type="button" class="action-btn delete-btn menu-delete-btn">删除</button>
</td>
</tr>
`;
tbody.innerHTML += row;
});
setupEditButtons();
setupMenuDeleteButtons();
}
function setMenuItems(items) {
menuItems = items;
renderMenuItems();
}
function setupEditButtons() {
const editButtons = document.querySelectorAll('.edit-btn');
editButtons.forEach((button, index) => {
button.addEventListener('click', () => {
const row = button.closest('tr');
const textInput = row.querySelector('.menu-text');
const linkInput = row.querySelector('.menu-link');
const newTabSelect = row.querySelector('.menu-newtab');
if (textInput.disabled) {
textInput.disabled = false;
linkInput.disabled = false;
newTabSelect.disabled = false;
button.textContent = '保存';
} else {
const text = textInput.value;
const link = linkInput.value;
const newTab = newTabSelect.value === 'true';
if (text) {
const rowIndex = row.getAttribute('data-index');
menuItems[rowIndex] = { text, link, newTab };
saveMenuItem(rowIndex, { text, link, newTab });
renderMenuItems(); // 重新渲染菜单项
} else {
alert('请填写菜单项文本');
}
}
});
});
}
function showNewMenuItemRow() {
const tbody = document.getElementById('menuTableBody');
const newRow = `
<tr id="newMenuItemRow">
<td><input type="text" class="menu-text" placeholder="菜单项文本"></td>
<td><input type="url" class="menu-link" placeholder="菜单项链接 (可选)"></td>
<td>
<select class="menu-newtab">
<option value="false">否</option>
<option value="true">是</option>
</select>
</td>
<td>
<button type="button" class="action-btn" onclick="saveNewMenuItem()">保存</button>
<button type="button" class="action-btn" onclick="cancelNewMenuItem()">取消</button>
</td>
</tr>
`;
tbody.insertAdjacentHTML('beforeend', newRow);
}
function saveNewMenuItem() {
const newRow = document.getElementById('newMenuItemRow');
const textInput = newRow.querySelector('.menu-text');
const linkInput = newRow.querySelector('.menu-link');
const newTabSelect = newRow.querySelector('.menu-newtab');
const text = textInput.value;
const link = linkInput.value;
const newTab = newTabSelect.value === 'true';
if (text) {
const newItem = { text, link, newTab };
menuItems.push(newItem);
renderMenuItems(); // 先更新页面
saveMenuItem(menuItems.length - 1, newItem);
cancelNewMenuItem();
} else {
alert('请填写菜单项文本');
}
}
function cancelNewMenuItem() {
const newRow = document.getElementById('newMenuItemRow');
if (newRow) {
newRow.remove();
}
}
function showNewAdRow() {
const tbody = document.getElementById('adTableBody');
const newRow = `
<tr id="newAdRow">
<td><input type="url" id="newAdUrl" placeholder="广告图片URL"></td>
<td><input type="url" id="newAdLink" placeholder="跳转URL"></td>
<td>
<button type="button" class="action-btn" onclick="saveNewAd()">保存</button>
<button type="button" class="action-btn" onclick="cancelNewAd()">取消</button>
</td>
</tr>
`;
tbody.insertAdjacentHTML('beforeend', newRow);
}
function renderAdItems() {
console.log('Rendering ad items:', adImages);
const tbody = document.getElementById('adTableBody');
tbody.innerHTML = '';
adImages.forEach((ad, index) => {
const row = `
<tr data-index="${index}">
<td><input type="url" class="ad-url" value="${ad.url || ''}" disabled></td>
<td><input type="url" class="ad-link" value="${ad.link || ''}" disabled></td>
<td>
<button type="button" class="action-btn edit-btn">编辑</button>
<button type="button" class="action-btn delete-btn ad-delete-btn">删除</button>
</td>
</tr>
`;
tbody.innerHTML += row;
});
setupAdEditButtons();
setupAdDeleteButtons();
}
function setupAdEditButtons() {
const editButtons = document.querySelectorAll('.edit-btn');
editButtons.forEach((button) => {
button.addEventListener('click', () => {
const row = button.closest('tr');
const urlInput = row.querySelector('.ad-url');
const linkInput = row.querySelector('.ad-link');
if (urlInput.disabled) {
urlInput.disabled = false;
linkInput.disabled = false;
button.textContent = '保存';
} else {
const index = parseInt(row.getAttribute('data-index'));
const url = urlInput.value || '';
const link = linkInput.value || '';
if (url) {
adImages[index] = { url, link };
saveAd(index, { url, link });
urlInput.disabled = true;
linkInput.disabled = true;
button.textContent = '编辑';
} else {
alert('广告URL不能为空');
}
}
});
});
}
function setupAdDeleteButtons() {
const deleteButtons = document.querySelectorAll('.ad-delete-btn');
deleteButtons.forEach((button) => {
button.addEventListener('click', () => {
const row = button.closest('tr');
const index = parseInt(row.getAttribute('data-index'));
const adUrl = row.querySelector('.ad-url').value;
if (confirm(`确定要删除广告 "${adUrl}" 吗?`)) {
deleteAd(index);
}
});
});
}
function saveNewAd() {
const url = document.getElementById('newAdUrl').value || '';
const link = document.getElementById('newAdLink').value || '';
if (!url) {
alert('广告图片URL为必填项');
return;
}
const newAd = { url, link };
adImages.push(newAd);
saveAd(adImages.length - 1, newAd);
cancelNewAd();
}
function cancelNewAd() {
const newRow = document.getElementById('newAdRow');
if (newRow) {
newRow.remove();
}
}
async function saveLogo() {
const logoUrl = document.getElementById('logoUrl').value;
if (!logoUrl) {
alert('Logo URL 不可为空');
return;
}
try {
await saveConfig({ logo: logoUrl });
alert('Logo 保存成功');
} catch (error) {
alert('Logo 保存失败: ' + error.message);
}
}
async function saveProxyDomain() {
const proxyDomain = document.getElementById('proxyDomain').value;
if (!proxyDomain) {
alert('Docker镜像代理地址不可为空');
return;
}
try {
await saveConfig({ proxyDomain });
alert('代理地址保存成功');
} catch (error) {
alert('代理地址保存失败: ' + error.message);
}
}
async function saveMenuItem(index, item) {
const config = { menuItems: menuItems };
config.menuItems[index] = item;
await saveConfig(config);
}
async function deleteMenuItem(index) {
try {
menuItems.splice(index, 1);
const response = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ menuItems: menuItems })
});
if (response.ok) {
console.log('Menu item deleted successfully');
renderMenuItems(); // 重新渲染菜单项
} else {
throw new Error('Failed to delete menu item');
}
} catch (error) {
console.error('删除菜单项失败:', error);
alert('删除菜单项失败: ' + error.message);
}
}
async function saveAd(index, ad) {
console.log(`Saving ad at index ${index}:`, ad);
try {
const response = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ adImages: adImages })
});
if (response.ok) {
console.log('Ad saved successfully');
renderAdItems(); // 重新渲染广告项
} else {
throw new Error('Failed to save ad');
}
} catch (error) {
console.error('保存广告失败:', error);
alert('保存广告失败: ' + error.message);
}
}
async function deleteAd(index) {
try {
adImages.splice(index, 1);
const response = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ adImages: adImages })
});
if (response.ok) {
console.log('Ad deleted successfully');
renderAdItems(); // 重新渲染广告项
} else {
throw new Error('Failed to delete ad');
}
} catch (error) {
console.error('删除广告项失败:', error);
alert('删除广告项失败: ' + error.message);
}
}
async function saveConfig(partialConfig) {
try {
const response = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(partialConfig)
});
if (!response.ok) {
throw new Error('保存失败');
}
} catch (error) {
console.error('保存失败: ' + error.message);
throw error;
}
}
// 加载文档的函数
async function loadDocumentation() {
try {
const response = await fetch('/api/documentation');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const documents = await response.json();
console.log('Received documents from server:', documents);
if (documents.length > 0) {
const firstDocument = documents[0];
if (!editor) {
console.warn('Editor not initialized, initializing now');
initEditor();
}
// 等待一小段时间确保编辑器完全初始化
setTimeout(() => {
if (editor && typeof editor.setMarkdown === 'function') {
editor.setMarkdown(firstDocument.content);
console.log('Documentation loaded successfully');
} else {
throw new Error('Editor not properly initialized or setMarkdown method not found');
}
}, 500);
} else {
console.log('No documents found');
}
} catch (error) {
console.error('加载文档失败:', error);
alert('加载文档失败: ' + error.message);
}
}
// 保存文档的函数
async function saveDocumentation() {
if (!editor) {
console.error('Editor not initialized');
return;
}
const content = editor.getMarkdown();
try {
const response = await fetch('/api/documentation', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ content })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
alert('文档保存成功');
} else {
throw new Error('保存失败');
}
} catch (error) {
console.error('保存文档失败:', error);
alert('保存文档失败: ' + error.message);
}
}
async function loadConfig() {
try {
const response = await fetch('/api/config');
const config = await response.json();
document.getElementById('logoUrl').value = config.logo || '';
document.getElementById('proxyDomain').value = config.proxyDomain || '';
setMenuItems(config.menuItems || []);
adImages = config.adImages || [];
renderAdItems();
loadDocumentation(); // 新增:加载文档
} catch (error) {
console.error('加载配置失败:', error);
}
}
async function login() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captcha = document.getElementById('captcha').value;
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, captcha })
});
if (response.ok) {
isLoggedIn = true;
localStorage.setItem('isLoggedIn', 'true');
document.getElementById('loginModal').style.display = 'none';
document.getElementById('adminContainer').style.display = 'flex';
loadConfig();
} else {
const errorData = await response.json();
alert(errorData.error);
}
} catch (error) {
alert('登录失败: ' + error.message);
}
}
async function changePassword() {
const currentPassword = document.getElementById('currentPassword').value;
const newPassword = document.getElementById('newPassword').value;
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
if (!currentPassword || !newPassword) {
alert('请填写当前密码和新密码');
return;
}
if (!passwordRegex.test(newPassword)) {
alert('密码必须包含至少一个字母、一个数字和一个特殊字符,长度在8到16个字符之间');
return;
}
try {
const response = await fetch('/api/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ currentPassword, newPassword })
});
if (response.ok) {
alert('密码已修改');
// 清除当前会话并显示登录模态框
localStorage.removeItem('isLoggedIn');
isLoggedIn = false;
document.getElementById('loginModal').style.display = 'block';
document.getElementById('adminContainer').classList.add('hidden');
refreshCaptcha();
// 清除登录表单中的输入数据
document.getElementById('username').value = '';
document.getElementById('password').value = '';
document.getElementById('captcha').value = '';
} else {
alert('修改密码失败');
}
} catch (error) {
alert('修改密码失败: ' + error.message);
}
}
function checkPasswordStrength() {
const newPassword = document.getElementById('newPassword').value;
const passwordHint = document.getElementById('passwordHint');
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
if (!passwordRegex.test(newPassword)) {
passwordHint.style.display = 'block';
} else {
passwordHint.style.display = 'none';
}
}
// 页面加载时检查登录状态
window.onload = async function() {
try {
const response = await fetch('/api/check-session');
if (response.ok) {
isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
if (isLoggedIn) {
loadDocumentList(); // 加载文档列表
document.getElementById('adminContainer').style.display = 'flex';
await loadConfig();
initEditor(); // 初始化编辑器
} else {
document.getElementById('loginModal').style.display = 'flex';
refreshCaptcha();
}
} else {
throw new Error('Session check failed');
}
} catch (error) {
console.error('Error during initialization:', error);
localStorage.removeItem('isLoggedIn');
document.getElementById('loginModal').style.display = 'flex';
refreshCaptcha();
} finally {
document.getElementById('loadingIndicator').style.display = 'none';
}
};
function updateAdImage(adImages) {
const adContainer = document.getElementById('adContainer');
adContainer.innerHTML = '';
if (adImages && adImages.length > 0) {
adImages.forEach(ad => {
const adLink = document.createElement('a');
adLink.href = ad.link;
adLink.target = '_blank';
const adImage = document.createElement('img');
adImage.src = ad.url;
adImage.alt = ad.alt || '广告图片';
adLink.appendChild(adImage);
adContainer.appendChild(adLink);
});
// 轮播功能
let currentAdIndex = 0;
setInterval(() => {
currentAdIndex = (currentAdIndex + 1) % adImages.length;
adImages.forEach((ad, index) => {
const adImage = adContainer.children[index];
if (index === currentAdIndex) {
adImage.style.display = 'block';
} else {
adImage.style.display = 'none';
}
});
}, 5000); // 每5秒切换一次广告
}
}
async function refreshCaptcha() {
try {
const response = await fetch('/api/captcha');
const data = await response.json();
document.getElementById('captchaText').textContent = data.captcha;
} catch (error) {
console.error('刷新验证码失败:', error);
}
}
async function loadDockerStatus() {
try {
const response = await fetch('/api/docker-status');
if (!response.ok) {
if (response.status === 503) {
throw new Error('无法连接到 Docker 守护进程');
}
throw new Error('Failed to fetch Docker status');
}
const containerStatus = await response.json();
renderDockerStatus(containerStatus);
} catch (error) {
console.error('Error loading Docker status:', error);
alert('加载 Docker 状态失败: ' + error.message);
// 清空状态表格并显示错误信息
const tbody = document.getElementById('dockerStatusTableBody');
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: red;">${error.message}</td></tr>`;
}
}
function renderDockerStatus(containerStatus) {
const tbody = document.getElementById('dockerStatusTableBody');
tbody.innerHTML = '';
// 添加表头
const thead = document.getElementById('dockerStatusTable').getElementsByTagName('thead')[0];
thead.innerHTML = `
<tr>
<th>容器 ID</th>
<th>名称</th>
<th>镜像</th>
<th>状态</th>
<th>CPU</th>
<th>内存</th>
<th>创建时间</th>
<th>操作</th>
</tr>
`;
containerStatus.forEach(container => {
const row = `
<tr>
<td>${container.id}</td>
<td>${container.name}</td>
<td>${container.image}</td>
<td id="status-${container.id}">${container.state}</td>
<td>${container.cpu}</td>
<td>${container.memory}</td>
<td>${container.created}</td>
<td>
<button onclick="restartContainer('${container.id}')" class="action-btn">重启</button>
<button onclick="stopContainer('${container.id}')" class="action-btn">停止</button>
</td>
</tr>
`;
tbody.innerHTML += row;
});
}
async function restartContainer(id) {
if (confirm('确定要重启这个容器吗?')) {
try {
const statusCell = document.getElementById(`status-${id}`);
statusCell.innerHTML = '<div class="loading"></div>';
const response = await fetch(`/api/docker/restart/${id}`, { method: 'POST' });
if (response.ok) {
await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒,确保状态已更新
const newStatus = await getContainerStatus(id);
statusCell.textContent = newStatus;
} else {
throw new Error('重启失败');
}
} catch (error) {
console.error('重启容器失败:', error);
alert('重启容器失败: ' + error.message);
loadDockerStatus(); // 重新加载所有容器状态
}
}
}
async function stopContainer(id) {
if (confirm('确定要停止这个容器吗?')) {
try {
const statusCell = document.getElementById(`status-${id}`);
statusCell.innerHTML = '<div class="loading"></div>';
const response = await fetch(`/api/docker/stop/${id}`, { method: 'POST' });
if (response.ok) {
await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒,确保状态已更新
const newStatus = await getContainerStatus(id);
statusCell.textContent = newStatus;
} else {
throw new Error('停止失败');
}
} catch (error) {
console.error('停止容器失败:', error);
alert('停止容器失败: ' + error.message);
loadDockerStatus(); // 重新加载所有容器状态
}
}
}
async function getContainerStatus(id) {
const response = await fetch(`/api/docker/status/${id}`);
if (response.ok) {
const data = await response.json();
return data.state;
} else {
throw new Error('获取容器状态失败');
}
}
function refreshDockerStatus() {
loadDockerStatus();
}
document.addEventListener('DOMContentLoaded', function() {
const sidebarItems = document.querySelectorAll('.sidebar li');
const contentSections = document.querySelectorAll('.content-section');
if (isLoggedIn) {
initEditor();
}
if (isLoggedIn) {
loadDockerStatus();
}
function showSection(sectionId) {
contentSections.forEach(section => {
if (section.id === sectionId) {
section.classList.add('active');
} else {
section.classList.remove('active');
}
});
}
sidebarItems.forEach(item => {
item.addEventListener('click', function() {
const sectionId = this.getAttribute('data-section');
sidebarItems.forEach(si => si.classList.remove('active'));
this.classList.add('active');
showSection(sectionId);
});
});
// 初始化:显示第一个部分
showSection(sidebarItems[0].getAttribute('data-section'));
});
</script>
</body>
</html>