From 98427fc4d1a66397280b66303ffd2abbe79ecb3f Mon Sep 17 00:00:00 2001 From: Loshop Wu Date: Sun, 22 Nov 2026 09:43:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20ColumnEdit.user.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ColumnEdit.user.js | 302 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 ColumnEdit.user.js diff --git a/ColumnEdit.user.js b/ColumnEdit.user.js new file mode 100644 index 0000000..327230e --- /dev/null +++ b/ColumnEdit.user.js @@ -0,0 +1,302 @@ +// ==UserScript== +// @name sxz.school Article HTML editor +// @namespace local.sxz.article-editor +// @version 1.0.0 +// @description Add an HTML editor to article pages and submit updates through the site's API. +// @match http://sxz.school.zykj.org/index.html* +// @match https://sxz.school.zykj.org/index.html* +// @run-at document-idle +// @grant GM_xmlhttpRequest +// @connect sxz.api.zykj.org +// ==/UserScript== + +(function () { + 'use strict'; + + const API_ROOT = '/api/services/app/appWebSite'; + const BUTTON_ID = 'tm-sxz-article-edit-button'; + const MODAL_ID = 'tm-sxz-article-edit-modal'; + const STYLE_ID = 'tm-sxz-article-edit-style'; + + function currentArticleId() { + const [route, query = ''] = location.hash.slice(1).split('?', 2); + if (!route.includes('ArticlePage')) return ''; + const id = new URLSearchParams(query).get('id') || ''; + return /^\d+$/.test(id) ? id : ''; + } + + function readCookie(name) { + const prefix = `${name}=`; + const entry = document.cookie + .split(';') + .map((part) => part.trim()) + .find((part) => part.startsWith(prefix)); + + if (!entry) return ''; + + let value = entry.slice(prefix.length); + try { + value = decodeURIComponent(value); + } catch (_) { + // Keep the original value if it is not valid URI encoding. + } + return value.replace(/^Bearer\s+/i, '').replace(/^"|"$/g, '').trim(); + } + + function randomHex() { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + } + + async function requestJson(path, options = {}) { + const token = readCookie('apiToken'); + if (!token) { + throw new Error('没有读取到 apiToken Cookie;请确认该 Cookie 对当前页面可见。'); + } + + const headers = { + accept: 'application/json, text/plain, */*', + 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', + appname: 'WebClient', + appversion: '0', + authorization: `Bearer ${token}`, + clientcode: 'null', + ...(options.headers || {}) + }; + + return new Promise((resolve, reject) => { + GM_xmlhttpRequest({ + method: options.method || 'GET', + url: `${location.protocol}//sxz.api.zykj.org${path}`, + headers, + data: options.body, + anonymous: false, + timeout: 30000, + onload(response) { + const responseText = response.responseText || ''; + let result = null; + try { + result = responseText ? JSON.parse(responseText) : null; + } catch (_) { + // Keep non-JSON response text for the error message below. + } + + if (response.status < 200 || response.status >= 300 || result?.success === false) { + const message = result?.error?.message || result?.message || responseText || `HTTP ${response.status}`; + reject(new Error(message)); + return; + } + resolve(result); + }, + onerror() { + reject(new Error('Tampermonkey 跨域请求失败,请确认已启用对 sxz.api.zykj.org 的访问权限。')); + }, + ontimeout() { + reject(new Error('接口请求超时。')); + }, + onabort() { + reject(new Error('接口请求已取消。')); + } + }); + }); + } + + function addStyles() { + if (document.getElementById(STYLE_ID)) return; + const style = document.createElement('style'); + style.id = STYLE_ID; + style.textContent = ` + #${BUTTON_ID} { margin-left: 12px; } + #${MODAL_ID} { position: fixed; inset: 0; z-index: 100000; } + #${MODAL_ID} .tm-sxz-mask { position: absolute; inset: 0; background: rgba(0,0,0,.45); } + #${MODAL_ID} .tm-sxz-wrap { position: relative; z-index: 1; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; padding: 16px; box-sizing: border-box; } + #${MODAL_ID} .tm-sxz-dialog { width: min(760px, 100%); max-height: 90vh; overflow: auto; background: #fff; border-radius: 2px; box-shadow: 0 3px 6px -4px rgba(0,0,0,.12), 0 6px 16px 0 rgba(0,0,0,.08), 0 9px 28px 8px rgba(0,0,0,.05); } + #${MODAL_ID} .tm-sxz-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 24px; border-bottom: 1px solid #f0f0f0; font-size: 16px; font-weight: 600; } + #${MODAL_ID} .tm-sxz-close { border: 0; background: transparent; color: rgba(0,0,0,.45); font-size: 22px; line-height: 1; cursor: pointer; } + #${MODAL_ID} .tm-sxz-body { padding: 20px 24px 8px; } + #${MODAL_ID} .tm-sxz-label { display: block; margin: 0 0 6px; color: rgba(0,0,0,.85); } + #${MODAL_ID} .tm-sxz-input { display: block; width: 100%; box-sizing: border-box; margin: 0 0 16px; padding: 8px 11px; border: 1px solid #d9d9d9; border-radius: 2px; color: rgba(0,0,0,.85); font: inherit; outline: none; } + #${MODAL_ID} .tm-sxz-input:focus { border-color: #40a9ff; box-shadow: 0 0 0 2px rgba(24,144,255,.2); } + #${MODAL_ID} textarea.tm-sxz-input { min-height: 280px; resize: vertical; font-family: Consolas, Monaco, monospace; font-size: 13px; } + #${MODAL_ID} .tm-sxz-status { min-height: 22px; margin: 0 0 10px; color: rgba(0,0,0,.65); overflow-wrap: anywhere; } + #${MODAL_ID} .tm-sxz-status[data-error="true"] { color: #cf1322; } + #${MODAL_ID} .tm-sxz-footer { display: flex; justify-content: flex-end; gap: 8px; padding: 10px 24px 20px; } + #${MODAL_ID} .tm-sxz-btn { height: 32px; padding: 4px 15px; border: 1px solid #d9d9d9; border-radius: 2px; background: #fff; color: rgba(0,0,0,.85); cursor: pointer; font: inherit; } + #${MODAL_ID} .tm-sxz-btn:hover { border-color: #40a9ff; color: #40a9ff; } + #${MODAL_ID} .tm-sxz-btn-primary { border-color: #1890ff; background: #1890ff; color: #fff; } + #${MODAL_ID} .tm-sxz-btn-primary:hover { border-color: #40a9ff; background: #40a9ff; color: #fff; } + #${MODAL_ID} .tm-sxz-btn:disabled { cursor: not-allowed; opacity: .6; } + @media (max-width: 600px) { #${MODAL_ID} .tm-sxz-wrap { padding: 8px; } #${MODAL_ID} .tm-sxz-body { padding: 16px 16px 4px; } #${MODAL_ID} .tm-sxz-footer { padding: 8px 16px 16px; } } + `; + document.head.appendChild(style); + } + + function setStatus(status, text, isError) { + status.textContent = text; + status.dataset.error = isError ? 'true' : 'false'; + } + + function closeModal() { + document.getElementById(MODAL_ID)?.remove(); + } + + function openModal() { + if (document.getElementById(MODAL_ID)) return; + addStyles(); + + const root = document.createElement('div'); + root.id = MODAL_ID; + root.innerHTML = ` +
+ `; + + document.body.appendChild(root); + + const titleInput = root.querySelector('#tm-sxz-title'); + const htmlInput = root.querySelector('#tm-sxz-html'); + const status = root.querySelector('.tm-sxz-status'); + const uploadButton = root.querySelector('[data-upload]'); + let loadedArticleId = ''; + let pageData = null; + + titleInput.disabled = true; + htmlInput.disabled = true; + uploadButton.disabled = true; + setStatus(status, '正在读取当前文章…', false); + + root.addEventListener('click', (event) => { + if (event.target.closest('[data-close]')) closeModal(); + }); + + root.addEventListener('keydown', (event) => { + if (event.key === 'Escape') closeModal(); + }); + + uploadButton.addEventListener('click', async () => { + const title = titleInput.value.trim(); + const content = htmlInput.value; + const articleId = currentArticleId(); + + if (!pageData || !loadedArticleId || articleId !== loadedArticleId) { + setStatus(status, '文章页面已变化或尚未读取完成,请关闭窗口后重新打开。', true); + return; + } + if (!title) { + setStatus(status, '请填写文章标题。', true); + titleInput.focus(); + return; + } + if (!content.trim()) { + setStatus(status, '请填写要上传的 HTML。', true); + htmlInput.focus(); + return; + } + + if (pageData.specialColId == null) { + setStatus(status, '读取到的文章数据中没有 specialColId,已取消上传。', true); + return; + } + + uploadButton.disabled = true; + setStatus(status, '正在上传…', false); + + try { + await requestJson(`${API_ROOT}/CreateOrEditPageAsync`, { + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ + title, + allowReply: pageData.allowReply ?? true, + content, + specialColId: pageData.specialColId, + publishTime: pageData.publishTime ?? null, + id: Number(loadedArticleId) + }) + }); + pageData.title = title; + pageData.content = content; + setStatus(status, '上传成功。', false); + } catch (error) { + setStatus(status, `上传失败:${error?.message || error}`, true); + } finally { + uploadButton.disabled = !pageData; + } + }); + + const articleId = currentArticleId(); + if (!articleId) { + setStatus(status, '当前路由中没有有效的文章 ID。', true); + return; + } + + const query = new URLSearchParams({ id: articleId, ran: randomHex() }); + requestJson(`${API_ROOT}/GetPageAsync?${query.toString()}`, { method: 'GET' }) + .then((response) => { + if (currentArticleId() !== articleId) throw new Error('文章页面已切换,请重新打开编辑窗口。'); + if (!response?.result) throw new Error('接口没有返回文章数据。'); + pageData = response.result; + loadedArticleId = articleId; + titleInput.value = pageData.title || ''; + htmlInput.value = pageData.content || ''; + titleInput.disabled = false; + htmlInput.disabled = false; + uploadButton.disabled = false; + setStatus(status, `已读取文章 ${articleId}(栏目 ${pageData.specialColId ?? '未知'}),修改后可上传。`, false); + titleInput.focus(); + }) + .catch((error) => { + setStatus(status, `读取文章失败:${error?.message || error}`, true); + }); + } + + function ensureButton() { + const existing = document.getElementById(BUTTON_ID); + if (!currentArticleId()) { + existing?.remove(); + return; + } + + const footer = document.querySelector('.fix-bottom-div'); + if (!footer) return; + if (existing && existing.parentElement === footer) return; + existing?.remove(); + + const button = document.createElement('button'); + button.id = BUTTON_ID; + button.type = 'button'; + button.className = 'ant-btn ant-btn-primary'; + button.textContent = '编辑'; + button.setAttribute('aria-label', '编辑文章 HTML'); + button.addEventListener('click', openModal); + footer.appendChild(button); + addStyles(); + } + + ensureButton(); + window.addEventListener('hashchange', ensureButton); + new MutationObserver(ensureButton).observe(document.documentElement, { + childList: true, + subtree: true + }); +})();