refactor: CSP nonce替代unsafe-inline, HSTS始终启用, router/api拆分, 管理后台+用户设置页拆分, DB健康降级, 时区配置, UID统一解析, CI接入
Some checks failed
CI / Lint + Build (push) Has been cancelled
Some checks failed
CI / Lint + Build (push) Has been cancelled
审计修复: - CSP: unsafe-inline移除, nonce替代; unsafe-eval保留供Vditor使用 - HSTS: 始终启用(不再依赖release模式) - Controller Exp: common.GetGinExp包装, 不再直接读context - UID解析: common.ParseUIDParam统一, follow/admin controller改用 重构: - router/api.go(198行)拆为7个域文件: auth/settings/posts/comments/reactions/social/studio - 管理后台站点设置: 单页拆为4个子页(brand/security/registration/content)+子菜单 - 前台用户设置页: 1201行拆为6个独立模板+6个独立JS文件 新增: - DB健康检测中间件(middleware/db_health.go): 5s ping+降级页面 - 时区配置: config.yaml server.timezone→time.Local初始化 - .gitea/workflows/ci.yml: strict模式CI流水线
This commit is contained in:
111
templates/MetaLab-2026/static/js/settings-account.js
Normal file
111
templates/MetaLab-2026/static/js/settings-account.js
Normal file
@ -0,0 +1,111 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// 修改密码
|
||||
// ---- 修改密码 ----
|
||||
var currentPwd = document.getElementById('currentPassword');
|
||||
var newPwd = document.getElementById('newPassword');
|
||||
var changePwdBtn = document.getElementById('changePwdBtn');
|
||||
if (currentPwd && newPwd && changePwdBtn) {
|
||||
changePwdBtn.addEventListener('click', function () {
|
||||
if (!currentPwd.value) {
|
||||
showSettingsToast('请输入当前密码', true);
|
||||
return;
|
||||
}
|
||||
if (!newPwd.value || !/[a-z]/.test(newPwd.value) || !/[A-Z]/.test(newPwd.value) || !/\d/.test(newPwd.value) || newPwd.value.length < 8) {
|
||||
showSettingsToast('新密码至少 8 位,包含大小写字母和数字', true);
|
||||
return;
|
||||
}
|
||||
changePwdBtn.disabled = true;
|
||||
changePwdBtn.textContent = '修改中...';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('PUT', '/api/settings/password', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
changePwdBtn.disabled = false;
|
||||
changePwdBtn.textContent = '修改密码';
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast('密码已修改,请重新登录');
|
||||
currentPwd.value = '';
|
||||
newPwd.value = '';
|
||||
setTimeout(function () {
|
||||
window.location.href = '/';
|
||||
}, 2000);
|
||||
} else {
|
||||
showSettingsToast(res.message || '修改失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('修改失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send(JSON.stringify({
|
||||
current_password: currentPwd.value,
|
||||
new_password: newPwd.value
|
||||
}));
|
||||
});
|
||||
}
|
||||
// 注销账号
|
||||
// ---- 注销账号 ----
|
||||
var deletePwd = document.getElementById('deletePassword');
|
||||
var deleteReason = document.getElementById('deleteReason');
|
||||
var deleteAccountBtn = document.getElementById('deleteAccountBtn');
|
||||
if (deletePwd && deleteAccountBtn) {
|
||||
deleteAccountBtn.addEventListener('click', function () {
|
||||
if (!deletePwd.value) {
|
||||
showSettingsToast('请输入密码确认', true);
|
||||
return;
|
||||
}
|
||||
showConfirm('注销账号', '确定要注销账号吗?\n\n注销后 7 天内重新登录可撤销注销,期满后将永久删除。').then(function(ok) {
|
||||
if (!ok) return;
|
||||
deleteAccountBtn.disabled = true;
|
||||
deleteAccountBtn.textContent = '注销中...';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', '/api/settings/delete-account', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
deleteAccountBtn.disabled = false;
|
||||
deleteAccountBtn.textContent = '确认注销';
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast(res.message || '账号已注销');
|
||||
setTimeout(function () {
|
||||
window.location.href = '/';
|
||||
}, 2000);
|
||||
} else {
|
||||
showSettingsToast(res.message || '操作失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('操作失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send(JSON.stringify({
|
||||
password: deletePwd.value,
|
||||
reason: deleteReason ? deleteReason.value : ''
|
||||
}));
|
||||
});
|
||||
});
|
||||
}
|
||||
})();
|
||||
91
templates/MetaLab-2026/static/js/settings-energy.js
Normal file
91
templates/MetaLab-2026/static/js/settings-energy.js
Normal file
@ -0,0 +1,91 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// ===== 域能 Tab =====
|
||||
(function () {
|
||||
var balanceEl = document.getElementById('energyBalance');
|
||||
var expEl = document.getElementById('energyExp');
|
||||
var levelEl = document.getElementById('energyLevel');
|
||||
var logListEl = document.getElementById('energyLogList');
|
||||
if (!balanceEl || !logListEl) return;
|
||||
|
||||
// 获取域能信息
|
||||
fetch('/api/energy/info')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (d) {
|
||||
if (d.success && d.data) {
|
||||
balanceEl.textContent = d.data.energy_display + ' 域能';
|
||||
} else {
|
||||
balanceEl.textContent = '获取失败';
|
||||
}
|
||||
})
|
||||
.catch(function () { balanceEl.textContent = '获取失败'; });
|
||||
|
||||
// 获取经验和等级
|
||||
if (expEl && levelEl) {
|
||||
fetch('/api/level/info')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (d) {
|
||||
if (d.success && d.data) {
|
||||
expEl.textContent = d.data.exp;
|
||||
levelEl.textContent = 'Lv' + d.data.level;
|
||||
} else {
|
||||
expEl.textContent = '获取失败';
|
||||
levelEl.textContent = '获取失败';
|
||||
}
|
||||
})
|
||||
.catch(function () {
|
||||
expEl.textContent = '获取失败';
|
||||
levelEl.textContent = '获取失败';
|
||||
});
|
||||
}
|
||||
|
||||
// 获取域能流水
|
||||
fetch('/api/energy/logs?days=7&page=1&page_size=50')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (d) {
|
||||
if (!d.success || !d.data || !d.data.items || d.data.items.length === 0) {
|
||||
logListEl.innerHTML = '<div class="energy-log-empty">近7天无变更记录</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
d.data.items.forEach(function (item) {
|
||||
var cls = item.amount > 0 ? 'energy-log-plus' : 'energy-log-minus';
|
||||
var sign = item.amount > 0 ? '+' : '';
|
||||
html += '<div class="energy-log-item ' + cls + '">'
|
||||
+ '<div class="energy-log-meta">'
|
||||
+ '<span class="energy-log-type">' + escapeHtml(item.type_name) + '</span>'
|
||||
+ '<span class="energy-log-time">' + formatTime(item.created_at) + '</span>'
|
||||
+ '</div>'
|
||||
+ '<div class="energy-log-info">'
|
||||
+ '<span class="energy-log-desc">' + escapeHtml(item.description) + '</span>'
|
||||
+ '<span class="energy-log-amount">' + sign + item.amount_display + ' 域能</span>'
|
||||
+ '</div>'
|
||||
+ '</div>';
|
||||
});
|
||||
logListEl.innerHTML = html;
|
||||
})
|
||||
.catch(function () {
|
||||
logListEl.innerHTML = '<div class="energy-log-empty">加载失败</div>';
|
||||
});
|
||||
|
||||
// escapeHtml / formatTime 由 shared/utils.js 统一提供
|
||||
})();
|
||||
})();
|
||||
108
templates/MetaLab-2026/static/js/settings-favorites.js
Normal file
108
templates/MetaLab-2026/static/js/settings-favorites.js
Normal file
@ -0,0 +1,108 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// ===== 收藏夹 Tab =====
|
||||
(function () {
|
||||
var listEl = document.getElementById('favFolderList');
|
||||
var createBtn = document.getElementById('createFolderBtn');
|
||||
if (!listEl) return;
|
||||
|
||||
// escapeHtml / api 由 shared/utils.js 统一提供
|
||||
|
||||
function loadFolders() {
|
||||
listEl.innerHTML = '<div class="energy-log-empty">加载中...</div>';
|
||||
api('GET', '/api/folders')
|
||||
.then(function (d) {
|
||||
if (!d.success) {
|
||||
listEl.innerHTML = '<div class="energy-log-empty">' + escapeHtml(d.message || '加载失败') + '</div>';
|
||||
return;
|
||||
}
|
||||
if (!d.data || !d.data.folders || d.data.folders.length === 0) {
|
||||
listEl.innerHTML = '<div class="energy-log-empty">暂无收藏夹</div>';
|
||||
return;
|
||||
}
|
||||
var html = '';
|
||||
d.data.folders.forEach(function (f) {
|
||||
var isDefault = f.is_default ? ' (默认)' : '';
|
||||
var pub = f.is_public ? '公开' : '私密';
|
||||
html += '<div class="fav-folder-card">'
|
||||
+ '<div class="fav-folder-info">'
|
||||
+ '<span class="fav-folder-name">' + escapeHtml(f.name) + isDefault + '</span>'
|
||||
+ '<span class="fav-folder-meta">' + (f.item_count || 0) + ' 篇文章 · ' + pub + '</span>'
|
||||
+ '</div>'
|
||||
+ '<div class="fav-folder-actions">'
|
||||
+ (f.is_default ? '' : '<button class="fav-folder-del" data-id="' + f.id + '">删除</button>')
|
||||
+ '</div>'
|
||||
+ '</div>';
|
||||
});
|
||||
listEl.innerHTML = html;
|
||||
|
||||
listEl.querySelectorAll('.fav-folder-del').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var id = btn.getAttribute('data-id');
|
||||
showConfirm('确认', '确定要删除此收藏夹?其中的收藏内容也将被清除。').then(function(ok) {
|
||||
if (!ok) return;
|
||||
api('DELETE', '/api/folders/' + id)
|
||||
.then(function (r) {
|
||||
if (r.success) {
|
||||
showSettingsToast('收藏夹已删除');
|
||||
loadFolders();
|
||||
} else {
|
||||
showSettingsToast(r.message || '删除失败', true);
|
||||
}
|
||||
})
|
||||
.catch(function () {
|
||||
showSettingsToast('删除失败', true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(function () {
|
||||
listEl.innerHTML = '<div class="energy-log-empty">加载失败,请刷新页面重试</div>';
|
||||
});
|
||||
}
|
||||
|
||||
if (createBtn) {
|
||||
createBtn.addEventListener('click', function () {
|
||||
showPrompt('请输入收藏夹名称(最多50个字符):').then(function(name) {
|
||||
if (!name || !name.trim()) return;
|
||||
if (name.trim().length > 50) {
|
||||
showSettingsToast('收藏夹名称不能超过 50 个字符', true);
|
||||
return;
|
||||
}
|
||||
api('POST', '/api/folders', { name: name.trim(), description: '', is_public: false })
|
||||
.then(function (r) {
|
||||
if (r.success) {
|
||||
showSettingsToast('收藏夹已创建');
|
||||
loadFolders();
|
||||
} else {
|
||||
showSettingsToast(r.message || '创建失败', true);
|
||||
}
|
||||
})
|
||||
.catch(function () {
|
||||
showSettingsToast('创建失败', true);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
loadFolders();
|
||||
})();
|
||||
})();
|
||||
90
templates/MetaLab-2026/static/js/settings-notify.js
Normal file
90
templates/MetaLab-2026/static/js/settings-notify.js
Normal file
@ -0,0 +1,90 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// ===== 通知偏好 Tab =====
|
||||
(function () {
|
||||
var bodyEl = document.getElementById('notifyPrefsBody');
|
||||
if (!bodyEl) return;
|
||||
|
||||
function loadPrefs() {
|
||||
fetch('/api/settings/notify-prefs')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (d) {
|
||||
if (!d.success || !d.data) {
|
||||
bodyEl.innerHTML = '<div class="energy-log-empty">加载失败</div>';
|
||||
return;
|
||||
}
|
||||
var prefs = d.data;
|
||||
var items = [
|
||||
{ key: 'comment', label: '评论通知', desc: '有人评论我的文章时通知我' },
|
||||
{ key: 'comment_reply', label: '回复通知', desc: '有人回复我的评论时通知我' },
|
||||
{ key: 'like_aggregated', label: '点赞通知', desc: '每日汇总的点赞通知' },
|
||||
{ key: 'follow', label: '关注通知', desc: '有人关注我时通知我' }
|
||||
];
|
||||
var html = '';
|
||||
items.forEach(function (item) {
|
||||
var checked = prefs[item.key] ? 'checked' : '';
|
||||
html += '<div class="notify-pref-row">'
|
||||
+ '<div class="notify-pref-info">'
|
||||
+ '<span class="notify-pref-label">' + item.label + '</span>'
|
||||
+ '<span class="notify-pref-desc">' + item.desc + '</span>'
|
||||
+ '</div>'
|
||||
+ '<label class="notify-pref-toggle">'
|
||||
+ '<input type="checkbox" class="notify-pref-cb" data-key="' + item.key + '" ' + checked + '>'
|
||||
+ '<span class="notify-pref-slider"></span>'
|
||||
+ '</label>'
|
||||
+ '</div>';
|
||||
});
|
||||
bodyEl.innerHTML = html;
|
||||
|
||||
// 绑定切换事件
|
||||
bodyEl.querySelectorAll('.notify-pref-cb').forEach(function (cb) {
|
||||
cb.addEventListener('change', function () {
|
||||
var key = cb.getAttribute('data-key');
|
||||
var enabled = cb.checked;
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('PUT', '/api/settings/notify-prefs', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
try {
|
||||
var r = JSON.parse(xhr.responseText);
|
||||
if (r.success) {
|
||||
showSettingsToast('通知偏好已更新');
|
||||
} else {
|
||||
showSettingsToast(r.message || '更新失败', true);
|
||||
cb.checked = !enabled;
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('更新失败', true);
|
||||
cb.checked = !enabled;
|
||||
}
|
||||
};
|
||||
xhr.send(JSON.stringify({ key: key, enabled: enabled }));
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(function () {
|
||||
bodyEl.innerHTML = '<div class="energy-log-empty">加载失败</div>';
|
||||
});
|
||||
}
|
||||
|
||||
loadPrefs();
|
||||
})();
|
||||
})();
|
||||
413
templates/MetaLab-2026/static/js/settings-profile.js
Normal file
413
templates/MetaLab-2026/static/js/settings-profile.js
Normal file
@ -0,0 +1,413 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// ===== 个人资料 Tab =====
|
||||
(function () {
|
||||
var usernameInput = document.getElementById('usernameInput');
|
||||
var bioInput = document.getElementById('bioInput');
|
||||
var btn = document.getElementById('saveProfileBtn');
|
||||
if (!usernameInput || !bioInput || !btn) return;
|
||||
|
||||
// ---- 字符计数器 ----
|
||||
var usernameCounter = document.getElementById('usernameCounter');
|
||||
var bioCounterEl = document.getElementById('bioCounter');
|
||||
|
||||
function updateCounters() {
|
||||
if (usernameCounter) {
|
||||
usernameCounter.textContent = usernameInput.value.length + '/16';
|
||||
}
|
||||
if (bioCounterEl) {
|
||||
bioCounterEl.textContent = bioInput.value.length + '/128';
|
||||
}
|
||||
}
|
||||
|
||||
usernameInput.addEventListener('input', updateCounters);
|
||||
bioInput.addEventListener('input', updateCounters);
|
||||
updateCounters();
|
||||
|
||||
// ---- 原始值(用于判断是否变更) ----
|
||||
var origUsername = usernameInput.value.trim();
|
||||
var origBio = bioInput.value;
|
||||
var hasCompletedRename = usernameInput.getAttribute('data-has-completed-rename') === 'true';
|
||||
|
||||
// 与后端一致的合法字符集:中文、英文大小写、数字、下划线、连字符
|
||||
var usernameRe = /^[\u4e00-\u9fffa-zA-Z0-9_-]+$/;
|
||||
|
||||
btn.addEventListener('click', function () {
|
||||
var username = usernameInput.value.trim();
|
||||
var bio = bioInput.value;
|
||||
|
||||
// 用户名校验
|
||||
if (!username) {
|
||||
showSettingsToast('用户名不能为空', true);
|
||||
return;
|
||||
}
|
||||
if (username.length > 16) {
|
||||
showSettingsToast('用户名不能超过 16 个字符', true);
|
||||
return;
|
||||
}
|
||||
if (!usernameRe.test(username)) {
|
||||
showSettingsToast('用户名仅支持中英文、数字、下划线、连字符', true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 个性签名校验
|
||||
if (bio.length > 128) {
|
||||
showSettingsToast('个性签名不能超过 128 个字符', true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 无变更判断
|
||||
if (username === origUsername && bio === origBio) {
|
||||
showSettingsToast('内容未变更,无需保存');
|
||||
return;
|
||||
}
|
||||
|
||||
// 用户名有变更时弹出消耗确认
|
||||
if (username !== origUsername) {
|
||||
var confirmMsg = hasCompletedRename
|
||||
? '确认修改用户名?\n\n本次将消耗 6 域能,是否继续?'
|
||||
: '确认修改用户名?\n\n首次更名无需消耗域能。';
|
||||
showConfirm('修改用户名', confirmMsg).then(function(ok) {
|
||||
if (ok) doSave(username, bio);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
doSave(username, bio);
|
||||
});
|
||||
|
||||
function doSave(username, bio) {
|
||||
btn.disabled = true;
|
||||
btn.textContent = '保存中...';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('PUT', '/api/settings/profile', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
btn.disabled = false;
|
||||
btn.textContent = '保存';
|
||||
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast(res.message || '个人资料已更新');
|
||||
origUsername = username;
|
||||
origBio = bio;
|
||||
} else {
|
||||
showSettingsToast(res.message || '保存失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('保存失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send(JSON.stringify({ username: username, bio: bio }));
|
||||
}
|
||||
|
||||
// ---- 头像裁切上传 ----
|
||||
var avatarWrap = document.getElementById('avatarWrap');
|
||||
var avatarInput = document.getElementById('avatarInput');
|
||||
var avatarPreview = document.getElementById('avatarPreview');
|
||||
var cropOverlay = document.getElementById('cropOverlay');
|
||||
var cropStage = document.getElementById('cropStage');
|
||||
var cropImageEl = document.getElementById('cropImageEl');
|
||||
var cropFrame = document.getElementById('cropFrame');
|
||||
var cropMask = document.getElementById('cropMask');
|
||||
var cropCancelBtn = document.getElementById('cropCancelBtn');
|
||||
var cropConfirmBtn = document.getElementById('cropConfirmBtn');
|
||||
|
||||
var pendingFile = null;
|
||||
var imgNW, imgNH; // 原图像素尺寸
|
||||
var imgDW, imgDH; // 图片缩放后显示尺寸(zoom=1 基准)
|
||||
var zoom = 1; // 图片缩放系数
|
||||
var minZoom = 1; // 最小缩放系数(超大图限制选区不超过 3840px)
|
||||
var panX = 0, panY = 0; // 图片平移偏移量
|
||||
var fSize, fLeft, fTop; // 裁切框的固定屏幕像素:边长、左、顶
|
||||
var CROP_MAX_PX = 3840; // 选区最大像素限制
|
||||
|
||||
// 更新裁切框固定参数(图片加载时计算一次,之后不变)
|
||||
function initFrame() {
|
||||
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
|
||||
fSize = Math.min(imgDW, imgDH); // 短边长度填满可见区域
|
||||
fLeft = Math.round((sw - fSize) / 2);
|
||||
fTop = Math.round((sh - fSize) / 2);
|
||||
}
|
||||
|
||||
// 约束 panX/panY,确保裁切框始终在图片范围内
|
||||
function clampPan() {
|
||||
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
|
||||
var iw = imgDW * zoom, ih = imgDH * zoom;
|
||||
var cx = Math.round((sw - iw) / 2); // 图片居中时的基准偏移
|
||||
var cy = Math.round((sh - ih) / 2);
|
||||
panX = Math.max(fLeft + fSize - cx - iw, Math.min(panX, fLeft - cx));
|
||||
panY = Math.max(fTop + fSize - cy - ih, Math.min(panY, fTop - cy));
|
||||
}
|
||||
|
||||
function renderCrop() {
|
||||
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
|
||||
var iw = imgDW * zoom, ih = imgDH * zoom;
|
||||
var ox = Math.round((sw - iw) / 2) + panX;
|
||||
var oy = Math.round((sh - ih) / 2) + panY;
|
||||
|
||||
cropImageEl.style.width = iw + 'px';
|
||||
cropImageEl.style.height = ih + 'px';
|
||||
cropImageEl.style.left = ox + 'px';
|
||||
cropImageEl.style.top = oy + 'px';
|
||||
|
||||
cropFrame.style.left = fLeft + 'px';
|
||||
cropFrame.style.top = fTop + 'px';
|
||||
cropFrame.style.width = fSize + 'px';
|
||||
cropFrame.style.height = fSize + 'px';
|
||||
|
||||
cropMask.style.left = fLeft + 'px';
|
||||
cropMask.style.top = fTop + 'px';
|
||||
cropMask.style.width = fSize + 'px';
|
||||
cropMask.style.height = fSize + 'px';
|
||||
|
||||
// 实时显示选区像素尺寸
|
||||
var p = getCropParams();
|
||||
var infoEl = document.getElementById('cropInfo');
|
||||
if (infoEl) infoEl.textContent = p.size + ' × ' + p.size + ' px';
|
||||
}
|
||||
|
||||
function openCrop(file) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = function (e) {
|
||||
cropImageEl.src = e.target.result;
|
||||
cropImageEl.onload = function () {
|
||||
imgNW = cropImageEl.naturalWidth;
|
||||
imgNH = cropImageEl.naturalHeight;
|
||||
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
|
||||
var fit = Math.min(sw / imgNW, sh / imgNH);
|
||||
imgDW = Math.round(imgNW * fit);
|
||||
imgDH = Math.round(imgNH * fit);
|
||||
// 限制选框最大像素:原图短边超过 3840 时,抬高最小缩放
|
||||
minZoom = Math.min(imgNW, imgNH) > CROP_MAX_PX
|
||||
? Math.min(imgNW, imgNH) / CROP_MAX_PX
|
||||
: 1;
|
||||
zoom = minZoom;
|
||||
panX = 0;
|
||||
panY = 0;
|
||||
initFrame();
|
||||
renderCrop();
|
||||
};
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
cropOverlay.classList.add('active');
|
||||
}
|
||||
|
||||
function closeCrop() {
|
||||
cropOverlay.classList.remove('active');
|
||||
avatarInput.value = '';
|
||||
pendingFile = null;
|
||||
}
|
||||
|
||||
function getCropParams() {
|
||||
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
|
||||
var iw = imgDW * zoom, ih = imgDH * zoom;
|
||||
var ox = Math.round((sw - iw) / 2) + panX;
|
||||
var oy = Math.round((sh - ih) / 2) + panY;
|
||||
var cx = (fLeft + fSize / 2 - ox) / zoom;
|
||||
var cy = (fTop + fSize / 2 - oy) / zoom;
|
||||
var cs = fSize / zoom;
|
||||
var sx = imgNW / imgDW, sy = imgNH / imgDH;
|
||||
return {
|
||||
x: Math.round((cx - cs / 2) * sx),
|
||||
y: Math.round((cy - cs / 2) * sy),
|
||||
size: Math.round(cs * sx)
|
||||
};
|
||||
}
|
||||
|
||||
// ---- 图片平移 ----
|
||||
var panning = false, panStartX = 0, panStartY = 0, panInitX = 0, panInitY = 0;
|
||||
|
||||
function startPan(clientX, clientY) {
|
||||
panning = true;
|
||||
panStartX = clientX;
|
||||
panStartY = clientY;
|
||||
panInitX = panX;
|
||||
panInitY = panY;
|
||||
cropStage.style.cursor = 'grabbing';
|
||||
}
|
||||
|
||||
function movePan(clientX, clientY) {
|
||||
panX = panInitX + (clientX - panStartX);
|
||||
panY = panInitY + (clientY - panStartY);
|
||||
clampPan();
|
||||
renderCrop();
|
||||
}
|
||||
|
||||
cropStage.addEventListener('mousedown', function (e) {
|
||||
e.preventDefault();
|
||||
startPan(e.clientX, e.clientY);
|
||||
});
|
||||
document.addEventListener('mousemove', function (e) {
|
||||
if (!panning) return;
|
||||
movePan(e.clientX, e.clientY);
|
||||
});
|
||||
document.addEventListener('mouseup', function () {
|
||||
panning = false;
|
||||
cropStage.style.cursor = 'grab';
|
||||
});
|
||||
|
||||
cropStage.addEventListener('touchstart', function (e) {
|
||||
e.preventDefault();
|
||||
var t = e.touches[0];
|
||||
startPan(t.clientX, t.clientY);
|
||||
});
|
||||
document.addEventListener('touchmove', function (e) {
|
||||
if (!panning) return;
|
||||
var t = e.touches[0];
|
||||
movePan(t.clientX, t.clientY);
|
||||
}, { passive: true });
|
||||
document.addEventListener('touchend', function () {
|
||||
panning = false;
|
||||
cropStage.style.cursor = 'grab';
|
||||
});
|
||||
|
||||
cropStage.addEventListener('wheel', function (e) {
|
||||
e.preventDefault();
|
||||
if (panning) return;
|
||||
var newZoom = Math.max(minZoom, Math.min(zoom * (e.deltaY < 0 ? 1.1 : 1 / 1.1), 3));
|
||||
if (newZoom === zoom) return;
|
||||
zoom = newZoom;
|
||||
clampPan();
|
||||
renderCrop();
|
||||
}, { passive: false });
|
||||
|
||||
cropCancelBtn.addEventListener('click', closeCrop);
|
||||
cropOverlay.addEventListener('click', function (e) {
|
||||
if (e.target === cropOverlay) closeCrop();
|
||||
});
|
||||
|
||||
// 客户端裁剪 + 压缩:Canvas 裁出选区并一步到位缩放到 512px,上传体积最小
|
||||
function cropOnClient(file, x, y, size) {
|
||||
return new Promise(function (resolve) {
|
||||
var url = URL.createObjectURL(file);
|
||||
var img = new Image();
|
||||
img.onload = function () {
|
||||
URL.revokeObjectURL(url);
|
||||
var out = 512; // 直接缩放到服务端目标输出尺寸
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = out;
|
||||
canvas.height = out;
|
||||
var ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(img, x, y, size, size, 0, 0, out, out);
|
||||
canvas.toBlob(function (blob) {
|
||||
resolve({
|
||||
file: new File([blob], 'avatar.jpg', { type: blob.type || 'image/jpeg' }),
|
||||
cropX: 0,
|
||||
cropY: 0,
|
||||
cropSize: out
|
||||
});
|
||||
}, 'image/jpeg', 0.88);
|
||||
};
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(url);
|
||||
// Canvas 处理失败时回退:直接上传原文件 + 原坐标
|
||||
resolve({ file: file, cropX: x, cropY: y, cropSize: size });
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
cropConfirmBtn.addEventListener('click', function () {
|
||||
if (!pendingFile) return;
|
||||
var params = getCropParams();
|
||||
|
||||
cropConfirmBtn.disabled = true;
|
||||
cropConfirmBtn.textContent = '处理中...';
|
||||
showSettingsToast('上传中...');
|
||||
|
||||
cropOnClient(pendingFile, params.x, params.y, params.size).then(function (result) {
|
||||
var formData = new FormData();
|
||||
formData.append('avatar', result.file, result.file.name);
|
||||
formData.append('crop_x', result.cropX);
|
||||
formData.append('crop_y', result.cropY);
|
||||
formData.append('crop_size', result.cropSize);
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', '/api/settings/avatar', true);
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
cropConfirmBtn.disabled = false;
|
||||
cropConfirmBtn.textContent = '确认';
|
||||
closeCrop();
|
||||
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast(res.message || '头像已更新');
|
||||
var newAvatarUrl = res.data && res.data.url && (res.data.url + '?t=' + Date.now());
|
||||
if (newAvatarUrl && avatarPreview.tagName === 'IMG') {
|
||||
avatarPreview.src = newAvatarUrl;
|
||||
}
|
||||
// 同步更新 NAV 头像
|
||||
if (newAvatarUrl) {
|
||||
var navLink = document.querySelector('.nav-avatar-link');
|
||||
if (navLink) {
|
||||
var navImg = navLink.querySelector('img.nav-avatar');
|
||||
if (navImg) {
|
||||
navImg.src = newAvatarUrl;
|
||||
navImg.style.display = '';
|
||||
var fb = navLink.querySelector('.nav-avatar-default');
|
||||
if (fb) fb.style.display = 'none';
|
||||
} else {
|
||||
var fb2 = navLink.querySelector('.nav-avatar-default');
|
||||
if (fb2) {
|
||||
var img = document.createElement('img');
|
||||
img.src = newAvatarUrl;
|
||||
img.alt = '';
|
||||
img.className = 'nav-avatar';
|
||||
img.onerror = function() { this.style.display = 'none'; this.nextElementSibling.style.display = 'flex'; };
|
||||
navLink.insertBefore(img, fb2);
|
||||
fb2.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
showSettingsToast(res.message || '上传失败', true);
|
||||
}
|
||||
} catch (err) {
|
||||
showSettingsToast('上传失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send(formData);
|
||||
}).catch(function () {
|
||||
cropConfirmBtn.disabled = false;
|
||||
cropConfirmBtn.textContent = '确认';
|
||||
showSettingsToast('处理失败,请重试', true);
|
||||
});
|
||||
});
|
||||
|
||||
if (avatarWrap && avatarInput) {
|
||||
avatarWrap.addEventListener('click', function () {
|
||||
avatarInput.click();
|
||||
});
|
||||
avatarInput.addEventListener('change', function () {
|
||||
var file = avatarInput.files[0];
|
||||
if (!file) return;
|
||||
pendingFile = file;
|
||||
openCrop(file);
|
||||
});
|
||||
}
|
||||
})(); // 结束个人资料 Tab 子 IIFE
|
||||
})();
|
||||
151
templates/MetaLab-2026/static/js/settings-sessions.js
Normal file
151
templates/MetaLab-2026/static/js/settings-sessions.js
Normal file
@ -0,0 +1,151 @@
|
||||
(function(){'use strict';
|
||||
<script nonce="{{.CSPNonce}}">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var toastEl = document.getElementById('settingsToast');
|
||||
var toastTimer = null;
|
||||
|
||||
function showSettingsToast(msg, isError) {
|
||||
if (!toastEl) return;
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
|
||||
void toastEl.offsetWidth;
|
||||
toastEl.classList.add('show');
|
||||
toastTimer = setTimeout(function () {
|
||||
toastEl.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
// ===== 登录管理 Tab =====
|
||||
(function () {
|
||||
var kickBtns = document.querySelectorAll('.session-kick-btn');
|
||||
var kickOthersBtn = document.getElementById('kickOthersBtn');
|
||||
var remarkInputs = document.querySelectorAll('.session-remark-input');
|
||||
if (!kickBtns.length && !kickOthersBtn && !remarkInputs.length) return;
|
||||
|
||||
// ---- 踢出单个设备 ----
|
||||
kickBtns.forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var sid = btn.getAttribute('data-sid');
|
||||
if (!sid) return;
|
||||
showConfirm('确认', '确定要踢出该设备吗?').then(function(ok) {
|
||||
if (!ok) return;
|
||||
btn.disabled = true;
|
||||
btn.textContent = '踢出中...';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('DELETE', '/api/settings/sessions/' + encodeURIComponent(sid), true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
btn.disabled = false;
|
||||
btn.textContent = '踢出';
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast(res.message || '已踢出该设备');
|
||||
var item = btn.closest('.session-item');
|
||||
if (item) {
|
||||
item.style.transition = 'opacity .3s ease, transform .3s ease';
|
||||
item.style.opacity = '0';
|
||||
item.style.transform = 'translateX(20px)';
|
||||
setTimeout(function () { item.remove(); }, 300);
|
||||
}
|
||||
} else {
|
||||
showSettingsToast(res.message || '操作失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('操作失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---- 一键踢出其他设备 ----
|
||||
if (kickOthersBtn) {
|
||||
kickOthersBtn.addEventListener('click', function () {
|
||||
var otherCount = document.querySelectorAll('.session-item:not(.session-current)').length;
|
||||
if (otherCount === 0) {
|
||||
showSettingsToast('没有其他在线设备');
|
||||
return;
|
||||
}
|
||||
showConfirm('确认', '确定要踢出所有其他设备(共 ' + otherCount + ' 台)吗?').then(function(ok) {
|
||||
if (!ok) return;
|
||||
kickOthersBtn.disabled = true;
|
||||
kickOthersBtn.textContent = '处理中...';
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', '/api/settings/sessions/destroy-others', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
kickOthersBtn.disabled = false;
|
||||
kickOthersBtn.textContent = '一键踢出其他设备';
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast(res.message || '已踢出所有其他设备');
|
||||
var others = document.querySelectorAll('.session-item:not(.session-current)');
|
||||
others.forEach(function (item, i) {
|
||||
setTimeout(function () {
|
||||
item.style.transition = 'opacity .3s ease, transform .3s ease';
|
||||
item.style.opacity = '0';
|
||||
item.style.transform = 'translateX(20px)';
|
||||
setTimeout(function () { item.remove(); }, 300);
|
||||
}, i * 100);
|
||||
});
|
||||
} else {
|
||||
showSettingsToast(res.message || '操作失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('操作失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 备注保存 ----
|
||||
var remarkTimers = {};
|
||||
remarkInputs.forEach(function (input) {
|
||||
input.addEventListener('blur', function () {
|
||||
var sid = input.getAttribute('data-sid');
|
||||
var remark = input.value.trim();
|
||||
if (!sid) return;
|
||||
saveRemark(sid, remark);
|
||||
});
|
||||
input.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
input.blur();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function saveRemark(sid, remark) {
|
||||
if (remarkTimers[sid]) clearTimeout(remarkTimers[sid]);
|
||||
remarkTimers[sid] = setTimeout(function () {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('PUT', '/api/settings/sessions/' + encodeURIComponent(sid) + '/remark', true);
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState !== 4) return;
|
||||
try {
|
||||
var res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
showSettingsToast('备注已保存');
|
||||
} else {
|
||||
showSettingsToast(res.message || '保存失败', true);
|
||||
}
|
||||
} catch (e) {
|
||||
showSettingsToast('保存失败', true);
|
||||
}
|
||||
};
|
||||
xhr.send(JSON.stringify({ remark: remark }));
|
||||
}, 500);
|
||||
}
|
||||
})();
|
||||
})();
|
||||
Reference in New Issue
Block a user