diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..716976f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 XIGE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 37b9fc9..0cac6a0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,30 @@ -# Discuz-Publisher +# Discuz Publisher +> 仓库:`Discuz-Publisher` · 类型:Obsidian 插件 · 版本:`1.0.0` · 作者:XIGE + +将 Obsidian 笔记发布到 Discuz X5 论坛。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `manifest.json` +- `src/` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..de243ed --- /dev/null +++ b/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "discuz-publisher", + "name": "Discuz Publisher", + "version": "1.0.0", + "minAppVersion": "1.0.0", + "description": "将笔记发布到 Discuz X5 论坛", + "author": "you", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..4547176 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,64 @@ +import { Notice, Plugin } from "obsidian"; +import { PushModal } from "./view/push"; +import { DiscuzSettingTab } from "./setting/setting_tab"; +import { DiscuzSettings, DEFAULT_SETTINGS } from "./setting/plugin_settings"; +import { HttpUtils } from "./utils/request"; + +export default class DiscuzPublisher extends Plugin { + settings: DiscuzSettings; + + async onload() { + await this.loadSettings(); + + const active = + this.settings.sites.find((s) => s.id === this.settings.activeSiteId) || + this.settings.sites[0]; + if (active) HttpUtils.setSite(active); + + this.addSettingTab(new DiscuzSettingTab(this.app, this)); + + this.addRibbonIcon("send", "发布到 Discuz", () => { + if (this.settings.sites.length === 0) { + new Notice("请先在设置中添加站点"); + return; + } + new PushModal(this.app, this.settings).open(); + }); + + this.addCommand({ + id: "publish-to-discuz", + name: "发布当前笔记到 Discuz", + callback: () => { + new PushModal(this.app, this.settings).open(); + }, + }); + } + + async loadSettings() { + const loaded = await this.loadData(); + this.settings = Object.assign({}, DEFAULT_SETTINGS, loaded); + + if (loaded && (loaded as any).apiBase && !this.settings.sites?.length) { + const old = loaded as any; + this.settings.sites = [ + { + id: "site_migrated", + name: "默认站点", + apiBase: old.apiBase || "", + siteUrl: old.siteUrl || "", + appid: old.appid || "", + secret: old.secret || "", + username: old.username || "", + password: old.password || "", + defaultFid: old.defaultFid || 2, + }, + ]; + this.settings.activeSiteId = this.settings.sites[0].id; + await this.saveSettings(); + } + } + + async saveSettings() { + await this.saveData(this.settings); + } +} \ No newline at end of file diff --git a/src/setting/plugin_settings.ts b/src/setting/plugin_settings.ts new file mode 100644 index 0000000..c440f53 --- /dev/null +++ b/src/setting/plugin_settings.ts @@ -0,0 +1,68 @@ +export interface SiteConfig { + id: string; + name: string; + apiBase: string; // https://xxx/api/restful/ + siteUrl: string; // https://xxx + appid: string; + secret: string; + username: string; + password: string; + defaultFid: number; + // 运行时缓存 + token?: string | null; + tokenExpiry?: number; + uid?: number; + // 登录态 + userInfo?: any; // 登录后缓存完整 user 对象 + isAdmin?: boolean; // 是否超管 + // 马甲:格式 "用户名:密码,用户名:密码" + aliases?: string; + enableAlias?: boolean; // 手动开关(兜底) +} + +export interface DiscuzSettings { + sites: SiteConfig[]; + activeSiteId: string; +} + +export const DEFAULT_SETTINGS: DiscuzSettings = { + sites: [], + activeSiteId: "", +}; + +export function generateSiteId(): string { + return "site_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8); +} + +export function createDefaultSite(name = "新站点"): SiteConfig { + return { + id: generateSiteId(), + name, + apiBase: "", + siteUrl: "", + appid: "", + secret: "", + username: "", + password: "", + defaultFid: 2, + aliases: "", + enableAlias: false, + }; +} + +/** 解析马甲字符串为 [{username, password}] */ +export function parseAliases(aliases: string | undefined): { username: string; password: string }[] { + if (!aliases) return []; + return aliases + .split(",") + .map((s) => s.trim()) + .filter(Boolean) + .map((pair) => { + const idx = pair.indexOf(":"); + if (idx === -1) return { username: pair, password: "" }; + return { + username: pair.slice(0, idx).trim(), + password: pair.slice(idx + 1).trim(), + }; + }); +} \ No newline at end of file diff --git a/src/setting/setting_tab.ts b/src/setting/setting_tab.ts new file mode 100644 index 0000000..0ed3b18 --- /dev/null +++ b/src/setting/setting_tab.ts @@ -0,0 +1,269 @@ +import { App, PluginSettingTab, Setting, Notice } from "obsidian"; +import DiscuzPublisher from "../main"; +import { + SiteConfig, + createDefaultSite, + parseAliases, +} from "./plugin_settings"; +import { HttpUtils } from "../utils/request"; + +export class DiscuzSettingTab extends PluginSettingTab { + plugin: DiscuzPublisher; + + constructor(app: App, plugin: DiscuzPublisher) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("h2", { + text: "Discuz 发布设置", + attr: { style: "padding-left: 0; margin-left: 0;" }, + }); + + const settings = this.plugin.settings; + + containerEl.createEl("h3", { + text: "站点列表", + attr: { style: "padding-left: 0; margin-left: 0;" }, + }); + + settings.sites.forEach((site, index) => { + const siteBox = containerEl.createDiv({ + attr: { + style: + "border: 1px solid var(--background-modifier-border); padding: 12px; border-radius: 6px; margin-bottom: 12px;", + }, + }); + + // ===== 标题行 ===== + const header = siteBox.createDiv({ + attr: { + style: + "display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; gap: 8px;", + }, + }); + + const titleWrap = header.createDiv({ + attr: { style: "display: flex; align-items: center; gap: 8px; flex: 1;" }, + }); + titleWrap.createEl("strong", { + text: site.name || `站点 ${index + 1}`, + attr: { style: "font-size: 14px;" }, + }); + + if (site.userInfo?.username) { + titleWrap.createEl("span", { + text: `👤 ${site.userInfo.username}`, + attr: { style: "font-size: 12px; color: var(--text-muted);" }, + }); + if (site.isAdmin) { + titleWrap.createEl("span", { + text: "超管", + attr: { + style: + "font-size: 11px; color: var(--text-success); padding: 0; border: none;", + }, + }); + } + } + + const btnGroup = header.createDiv({ + attr: { style: "display: flex; gap: 6px; align-items: center;" }, + }); + + const isActive = settings.activeSiteId === site.id; + const activeBtn = btnGroup.createEl("button", { + text: isActive ? "✓ 当前" : "设为当前", + }); + if (isActive) activeBtn.disabled = true; + activeBtn.addEventListener("click", async () => { + settings.activeSiteId = site.id; + await this.plugin.saveSettings(); + this.display(); + }); + + if (site.userInfo?.username) { + const logoutBtn = btnGroup.createEl("button", { text: "退出" }); + logoutBtn.addEventListener("click", async () => { + HttpUtils.setSite(site); + HttpUtils.logout(); + delete site.userInfo; + delete site.isAdmin; + delete site.token; + delete site.tokenExpiry; + await this.plugin.saveSettings(); + new Notice("已退出登录"); + this.display(); + }); + } else { + const loginBtn = btnGroup.createEl("button", { text: "登录" }); + loginBtn.addEventListener("click", async () => { + try { + HttpUtils.setSite(site); + await HttpUtils.login(); + await this.plugin.saveSettings(); + new Notice("✅ 登录成功:" + (site.userInfo?.username || "")); + this.display(); + } catch (e) { + new Notice("❌ " + (e instanceof Error ? e.message : String(e))); + } + }); + } + + const delBtn = btnGroup.createEl("button", { text: "删除" }); + delBtn.addEventListener("click", async () => { + if (!confirm(`确定删除站点 "${site.name}"?`)) return; + settings.sites.splice(index, 1); + if (settings.activeSiteId === site.id) { + settings.activeSiteId = settings.sites[0]?.id || ""; + } + await this.plugin.saveSettings(); + this.display(); + }); + + // 折叠按钮 + const toggleBtn = btnGroup.createEl("button", { + text: "▼", + attr: { + style: "width: 28px; padding: 0; font-size: 11px;", + title: "展开/收起设置", + }, + }); + + // ===== 可折叠的设置内容 ===== + const detailWrap = siteBox.createDiv({ + attr: { style: "display: none; margin-top: 10px;" }, + }); + + toggleBtn.addEventListener("click", () => { + const expanded = detailWrap.style.display !== "none"; + detailWrap.style.display = expanded ? "none" : "block"; + toggleBtn.setText(expanded ? "▼" : "▲"); + }); + + // ===== 基础字段 ===== + const fields: [keyof SiteConfig, string, boolean][] = [ + ["name", "站点名称", false], + ["apiBase", "API 地址(末尾带 /)", false], + ["siteUrl", "站点地址", false], + ["appid", "AppID", false], + ["secret", "Secret", true], + ["username", "用户名", false], + ["password", "密码", true], + ]; + + for (const [key, label, isPwd] of fields) { + new Setting(detailWrap).setName(label).addText((t) => { + if (isPwd) t.inputEl.type = "password"; + t.setValue(String(site[key] ?? "")).onChange(async (v) => { + (site as any)[key] = v; + await this.plugin.saveSettings(); + }); + }); + } + + new Setting(detailWrap) + .setName("默认版块 ID") + .addText((t) => + t.setValue(String(site.defaultFid)).onChange(async (v) => { + site.defaultFid = parseInt(v) || 2; + await this.plugin.saveSettings(); + }) + ); + + new Setting(detailWrap) + .setName("测试连接") + .addButton((b) => + b.setButtonText("测试").onClick(async () => { + try { + HttpUtils.setSite(site); + const r = await HttpUtils.testToken(); + new Notice("✅ Token 获取成功: " + r.token); + } catch (e) { + new Notice("❌ " + (e instanceof Error ? e.message : String(e))); + } + }) + ); + + // ===== 马甲设置:仅超管可见 ===== + if (site.isAdmin) { + detailWrap.createEl("hr", { attr: { style: "margin: 12px 0;" } }); + detailWrap.createEl("div", { + text: "马甲设置", + attr: { + style: + "font-weight: bold; font-size: 13px; margin-bottom: 6px; padding-left: 0; margin-left: 0;", + }, + }); + + new Setting(detailWrap) + .setName("马甲列表") + .setDesc("格式:用户名:密码,用户名:密码(英文逗号分隔)") + .addTextArea((t) => { + t.setValue(site.aliases || "").onChange(async (v) => { + site.aliases = v; + await this.plugin.saveSettings(); + }); + t.inputEl.style.width = "100%"; + t.inputEl.style.minHeight = "60px"; + }); + + new Setting(detailWrap) + .setName("测试马甲登录") + .setDesc("逐个测试马甲账号是否能登录(实时读取当前输入)") + .addButton((b) => + b.setButtonText("测试全部").onClick(async () => { + const currentAliases = parseAliases(site.aliases); + console.log("[Discuz] 测试马甲,当前 aliases:", currentAliases); + + if (currentAliases.length === 0) { + new Notice("未配置马甲"); + return; + } + + HttpUtils.setSite(site); + try { + if (!site.token) await HttpUtils.testToken(); + } catch (e) { + new Notice("❌ Token 获取失败,请先测试连接"); + return; + } + + const results: string[] = []; + for (const a of currentAliases) { + try { + await HttpUtils.loginAs(a.username, a.password); + results.push(`✅ ${a.username}`); + } catch (e) { + console.error(`马甲 ${a.username} 登录失败:`, e); + results.push(`❌ ${a.username}`); + } + } + + // 测试完恢复主账号 + try { + await HttpUtils.loginAs(site.username, site.password); + } catch (e) { + console.error("[Discuz] 恢复主账号失败:", e); + } + + new Notice("马甲测试结果:\n" + results.join("\n"), 8000); + }) + ); + } + }); + + new Setting(containerEl).addButton((b) => + b.setButtonText("+ 添加站点").onClick(async () => { + const newSite = createDefaultSite(`站点 ${settings.sites.length + 1}`); + settings.sites.push(newSite); + if (!settings.activeSiteId) settings.activeSiteId = newSite.id; + await this.plugin.saveSettings(); + this.display(); + }) + ); + } +} \ No newline at end of file diff --git a/src/utils/converter.ts b/src/utils/converter.ts new file mode 100644 index 0000000..1b3c89f --- /dev/null +++ b/src/utils/converter.ts @@ -0,0 +1,58 @@ +export function markdownToBBCode(md: string): string { + let r = md; + + // 代码块 + r = r.replace(/```(\w*)\n([\s\S]*?)```/g, (_, _lang, code) => + `[code]${code.trim()}[/code]` + ); + + // 图片 + r = r.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, "[img]$2[/img]"); + + // 链接 + r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "[url=$2]$1[/url]"); + + // 标题 + r = r.replace(/^### (.+)$/gm, "[size=3][b]$1[/b][/size]"); + r = r.replace(/^## (.+)$/gm, "[size=4][b]$1[/b][/size]"); + r = r.replace(/^# (.+)$/gm, "[size=5][b]$1[/b][/size]"); + + // 粗体 / 斜体 + r = r.replace(/\*\*(.+?)\*\*/g, "[b]$1[/b]"); + r = r.replace(/\*(.+?)\*/g, "[i]$1[/i]"); + + // 行内代码 + r = r.replace(/`([^`]+)`/g, "[code]$1[/code]"); + + // 引用 + r = r.replace(/^> (.+)$/gm, "[quote]$1[/quote]"); + + // 无序列表 + r = r.replace(/^- (.+)$/gm, "[*]$1"); + + return r; +} + +export function stripFrontmatter(content: string): string { + return content.replace(/^---\s*[\s\S]*?---\s*/, ""); +} + +export function extractTitle(content: string, fileName: string): string { + const fm = content.match(/^---\n([\s\S]*?)\n---/); + if (fm) { + const m = fm[1].match(/^title:\s*(.+)$/m); + if (m) return m[1].trim().replace(/^["']|["']$/g, ""); + } + const h1 = content.match(/^#\s+(.+)$/m); + if (h1) return h1[1].trim(); + return fileName.replace(/\.md$/, ""); +} + +export function extractFid(content: string, defaultFid: number): number { + const fm = content.match(/^---\n([\s\S]*?)\n---/); + if (fm) { + const m = fm[1].match(/^discuz_fid:\s*(\d+)$/m); + if (m) return parseInt(m[1]); + } + return defaultFid; +} \ No newline at end of file diff --git a/src/utils/request.ts b/src/utils/request.ts new file mode 100644 index 0000000..39cdc98 --- /dev/null +++ b/src/utils/request.ts @@ -0,0 +1,234 @@ +import { requestUrl } from "obsidian"; +import { SiteConfig } from "../setting/plugin_settings"; + +export class HttpUtils { + private static site: SiteConfig | null = null; + private static token: string | null = null; + private static tokenExpiry = 0; + private static loggedIn = false; + private static uid = 0; + private static userInfo: any = null; + + static setSite(site: SiteConfig) { + this.site = site; + this.token = site.token || null; + this.tokenExpiry = site.tokenExpiry || 0; + this.uid = site.uid || 0; + this.userInfo = site.userInfo || null; + this.loggedIn = false; + } + + static getSite(): SiteConfig | null { + return this.site; + } + + static getUid(): number { + return this.uid; + } + + static getUserInfo(): any { + return this.userInfo; + } + + static isLoggedIn(): boolean { + return this.loggedIn && !!this.userInfo; + } + + private static async sign(nonce: string, t: number, secret: string): Promise { + const raw = nonce + t + secret; + const buf = new TextEncoder().encode(raw); + const hashBuf = await crypto.subtle.digest("SHA-256", buf); + const hex = Array.from(new Uint8Array(hashBuf)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + return btoa(hex); + } + + private static capitalize(name: string): string { + return name + .split("-") + .map((s) => s.charAt(0).toUpperCase() + s.slice(1)) + .join("-"); + } + + private static async buildHeaders( + appid: string, + secret: string, + token?: string | null + ): Promise> { + const t = Math.floor(Date.now() / 1000); + const nonce = Math.random().toString(36).substring(2, 10); + const s = await this.sign(nonce, t, secret); + + const raw: Record = { + "Content-Type": "application/json", + appid, + nonce, + t: String(t), + sign: s, + }; + if (token) raw.token = token; + + const headers: Record = {}; + for (const [k, v] of Object.entries(raw)) { + headers[this.capitalize(k)] = v; + } + return headers; + } + + private static async ensureToken(): Promise { + if (!this.site) throw new Error("未设置站点"); + if (this.token && Date.now() < this.tokenExpiry) return; + + const headers = await this.buildHeaders(this.site.appid, this.site.secret); + const res = await requestUrl({ + url: `${this.site.apiBase}?/token`, + method: "POST", + headers, + body: "{}", + }); + + const json = res.json; + if (json.ret > 0 || !json.token) { + throw new Error("Token 获取失败: " + JSON.stringify(json)); + } + this.token = json.token; + this.tokenExpiry = Date.now() + 50 * 60 * 1000; + this.site.token = this.token; + this.site.tokenExpiry = this.tokenExpiry; + console.log("[Discuz] 获取新 Token:", this.token); + } + + static async post(path: string, body: Record): Promise { + if (!this.site) throw new Error("未设置站点"); + await this.ensureToken(); + const headers = await this.buildHeaders(this.site.appid, this.site.secret, this.token); + + const res = await requestUrl({ + url: `${this.site.apiBase}?${path}`, + method: "POST", + headers, + body: JSON.stringify(body), + }); + + return res.json; + } + + static async login(): Promise { + if (this.loggedIn) return { ret: 0, user: this.userInfo }; + if (!this.site) throw new Error("未设置站点"); + + const res = await this.post("/member/login", { + username: this.site.username, + password: this.site.password, + }); + + if (res.ret > 0) { + throw new Error( + "登录失败: " + (res.msg?.message || res.msg || JSON.stringify(res)) + ); + } + this.loggedIn = true; + const user = res.user || res.data?.user || null; + this.userInfo = user; + this.site.userInfo = user; + + console.log("[Discuz] 登录 user 对象:", JSON.stringify(user, null, 2)); + + const isAdmin = + user?.adminid === 1 || + user?.adminid === "1" || + user?.group?.radminid === "1" || + user?.group?.radminid === 1 || + user?.groupid === 1 || + user?.groupid === "1"; + this.site.isAdmin = isAdmin; + console.log("[Discuz] 是否超管:", isAdmin); + + if (res.uid) { + this.uid = res.uid; + this.site.uid = res.uid; + } else if (user?.uid) { + this.uid = user.uid; + this.site.uid = user.uid; + } + return res; + } + + /** + * 用指定账号登录(马甲) + * 方案 A:登录成功后清空当前 token,重新获取,让 token 绑定到新用户 + */ + static async loginAs(username: string, password: string): Promise { + if (!this.site) throw new Error("未设置站点"); + + console.log("[Discuz] loginAs 请求:", { username, password: "***" }); + + // 1) 先用旧 token 调登录接口 + const res = await this.post("/member/login", { username, password }); + console.log("[Discuz] loginAs 登录返回 user:", JSON.stringify(res.user || res.data?.user, null, 2)); + + if (res.ret > 0) { + throw new Error( + `马甲 ${username} 登录失败: ` + + (res.msg?.message || res.msg || JSON.stringify(res)) + ); + } + + // 2) 关键:清空当前 token,强制重新获取 + this.token = null; + this.tokenExpiry = 0; + this.site.token = null; + this.site.tokenExpiry = 0; + this.loggedIn = false; + this.userInfo = null; + this.site.userInfo = null; + + console.log("[Discuz] loginAs: 已清空 token,准备重新获取"); + + // 3) 重新获取 token(此时服务端应该记住新用户) + await this.ensureToken(); + + // 4) 再登录一次,用新 token 验证当前用户 + const verify = await this.post("/member/login", { username, password }); + console.log("[Discuz] loginAs 验证返回 user:", JSON.stringify(verify.user || verify.data?.user, null, 2)); + + const verifyUser = verify.user || verify.data?.user; + if (verifyUser?.username && verifyUser.username !== username) { + console.warn( + `[Discuz] ⚠️ 警告:期望用户 ${username},实际返回 ${verifyUser.username}` + ); + } + + // 5) 更新当前用户信息 + this.loggedIn = true; + this.userInfo = verifyUser; + this.site.userInfo = verifyUser; + if (verifyUser?.uid) { + this.uid = verifyUser.uid; + this.site.uid = verifyUser.uid; + } + + return verify; + } + + static logout() { + this.loggedIn = false; + this.userInfo = null; + this.token = null; + this.tokenExpiry = 0; + this.uid = 0; + if (this.site) { + this.site.token = null; + this.site.tokenExpiry = 0; + this.site.uid = 0; + this.site.userInfo = null; + this.site.isAdmin = false; + } + } + + static async testToken(): Promise { + await this.ensureToken(); + return { token: this.token }; + } +} \ No newline at end of file diff --git a/src/view/push.ts b/src/view/push.ts new file mode 100644 index 0000000..85fd6b9 --- /dev/null +++ b/src/view/push.ts @@ -0,0 +1,410 @@ +import { App, Modal, Notice } from "obsidian"; +import { HttpUtils } from "../utils/request"; +import { + DiscuzSettings, + SiteConfig, + parseAliases, +} from "../setting/plugin_settings"; +import { + markdownToBBCode, + stripFrontmatter, + extractTitle, + extractFid, +} from "../utils/converter"; + +export class PushModal extends Modal { + settings: DiscuzSettings; + notice: Notice; + title = ""; + content = ""; + activeFilePath = ""; + selectedFid: number; + forums: any[] = []; + forumsDom: HTMLElement; + currentSite: SiteConfig; + // 马甲选择:空字符串 = 用登录账号 + selectedAlias = ""; + // 马甲下拉容器 + aliasDom: HTMLElement | null = null; + + constructor(app: App, settings: DiscuzSettings) { + super(app); + this.settings = settings; + const active = + settings.sites.find((s) => s.id === settings.activeSiteId) || + settings.sites[0]; + this.currentSite = active; + this.selectedFid = active?.defaultFid || 2; + } + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "发布到 Discuz" }); + + // 站点选择器 + if (this.settings.sites.length > 1) { + const siteDiv = contentEl.createDiv({ attr: { style: "margin-bottom: 15px;" } }); + siteDiv.createEl("label", { text: "选择站点:", attr: { style: "margin-right: 10px;" } }); + const siteSelect = siteDiv.createEl("select"); + for (const s of this.settings.sites) { + const opt = siteSelect.createEl("option", { text: s.name, value: s.id }); + if (s.id === this.currentSite?.id) opt.selected = true; + } + siteSelect.addEventListener("change", async () => { + const selected = this.settings.sites.find((s) => s.id === siteSelect.value); + if (selected) { + this.currentSite = selected; + this.selectedFid = selected.defaultFid || 2; + this.selectedAlias = ""; + HttpUtils.setSite(selected); + + // 重新登录新站点 + try { + if (!HttpUtils.isLoggedIn()) { + await HttpUtils.login(); + } + } catch (e) { + console.error("[Discuz] 切换站点后登录失败:", e); + } + + // 重绘马甲下拉 + this.renderAliasSelect(); + + // 重载版块列表 + await this.getForums(contentEl); + new Notice("已切换到:" + selected.name); + } + }); + } + + if (this.currentSite) HttpUtils.setSite(this.currentSite); + + // 登录(如未登录) + try { + if (!HttpUtils.isLoggedIn()) { + await HttpUtils.login(); + } + } catch (e) { + console.error("[Discuz] 自动登录失败:", e); + } + + // 马甲下拉容器(放在站点选择器之后、版块列表之前) + this.aliasDom = contentEl.createDiv({ attr: { style: "margin-bottom: 15px;" } }); + this.renderAliasSelect(); + + await this.getForums(contentEl); + + // 文件选择 + const files = this.app.vault.getFiles(); + const activeFile = this.app.workspace.getActiveFile(); + this.activeFilePath = activeFile?.path || ""; + + const selectEl = contentEl.createEl("select", { + attr: { + style: + "width: 100%; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);", + }, + }); + for (const file of files) { + if (!file.path.endsWith(".md")) continue; + const opt = selectEl.createEl("option", { text: file.path, value: file.path }); + if (file.path === this.activeFilePath) opt.selected = true; + } + if (this.activeFilePath) { + await this.readFileAndSetContent(this.activeFilePath); + this.setTitleFromFile(this.activeFilePath); + } + selectEl.addEventListener("change", async (e) => { + const p = (e.target as HTMLSelectElement).value; + await this.readFileAndSetContent(p); + this.setTitleFromFile(p); + }); + + // 标题输入 + const titleInput = contentEl.createEl("input", { + attr: { + type: "text", + placeholder: "标题", + style: + "width: 100%; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);", + }, + }); + titleInput.value = this.title; + titleInput.addEventListener("input", () => { + this.title = titleInput.value; + }); + + // 发布按钮 + const btn = contentEl.createEl("button", { + text: "发布", + attr: { + style: + "margin-top: 15px; padding: 8px 16px; border: none; border-radius: 4px; color: var(--text-normal); cursor: pointer;", + }, + }); + btn.addEventListener("click", () => this.publish()); + } + + /** 根据当前站点重绘马甲下拉 */ + private renderAliasSelect() { + if (!this.aliasDom) return; + this.aliasDom.empty(); + + const aliases = parseAliases(this.currentSite.aliases); + const showAlias = this.currentSite.isAdmin && aliases.length > 0; + + if (!showAlias) return; + + this.aliasDom.createEl("label", { + text: "发帖身份:", + attr: { style: "margin-right: 10px;" }, + }); + const aliasSelect = this.aliasDom.createEl("select"); + const defaultOpt = aliasSelect.createEl("option", { + text: `(默认)${this.currentSite.userInfo?.username || this.currentSite.username}`, + value: "", + }); + defaultOpt.selected = true; + for (const a of aliases) { + aliasSelect.createEl("option", { text: a.username, value: a.username }); + } + aliasSelect.addEventListener("change", () => { + this.selectedAlias = aliasSelect.value; + console.log("[Discuz] 选择发帖身份:", this.selectedAlias || "(默认)"); + }); + } + + async getForums(contentEl: HTMLElement) { + if (this.forumsDom) this.forumsDom.empty(); + else this.forumsDom = contentEl.createDiv({ attr: { style: "margin-bottom: 15px;" } }); + + this.notice = new Notice("获取版块列表..."); + try { + if (!HttpUtils.isLoggedIn()) await HttpUtils.login(); + const res = await HttpUtils.post("/index/forumlist", {}); + const raw = res.data?.forumlist || res.forumlist || []; + this.forums = Array.isArray(raw) ? raw : Object.values(raw); + } catch (e) { + console.error("[Discuz] 获取版块失败:", e); + this.forums = []; + } + this.notice.hide(); + this.createForumCheckboxes(); + } + + private createForumCheckboxes() { + this.forumsDom.empty(); + const group = this.forumsDom.createDiv({ + attr: { + style: + "border: 1px solid var(--background-modifier-border); padding: 10px; border-radius: 5px; max-height: 280px; overflow-y: auto;", + }, + }); + group.createEl("h4", { + text: "选择版块", + attr: { style: "margin: 0 0 8px 0; font-size: 14px; font-weight: bold;" }, + }); + + if (this.forums.length === 0) { + group.createDiv({ + text: "暂无版块", + attr: { style: "color: var(--text-muted); font-size: 13px; text-align: center;" }, + }); + return; + } + + const render = (forums: any[], container: HTMLElement, depth = 0) => { + for (const f of forums) { + const isGroup = f.type === "group"; + const hasSub = f.subforums && f.subforums.length > 0; + + if (isGroup) { + container.createDiv({ + text: f.name, + attr: { + style: `font-weight: bold; color: var(--text-normal); font-size: 13px; margin: ${ + depth > 0 ? "8px" : "4px" + } 0 4px 0; padding-left: ${depth * 12}px;`, + }, + }); + if (hasSub) render(f.subforums, container, depth + 1); + } else { + const row = container.createDiv({ + attr: { + style: `display: flex; align-items: center; padding: 2px 4px; padding-left: ${ + depth * 12 + 8 + }px;`, + }, + }); + const cb = row.createEl("input", { + type: "checkbox", + attr: { + id: `forum-${f.fid}`, + style: "margin-right: 6px; accent-color: var(--interactive-accent);", + }, + }); + cb.checked = String(f.fid) === String(this.selectedFid); + cb.addEventListener("change", () => { + if (cb.checked) this.selectedFid = parseInt(f.fid); + }); + const label = row.createEl("label", { + text: f.name, + attr: { + for: `forum-${f.fid}`, + style: "cursor: pointer; font-size: 13px; color: var(--text-normal);", + }, + }); + label.addEventListener("click", () => cb.click()); + if (hasSub) render(f.subforums, container, depth + 1); + } + } + }; + + render(this.forums, group); + } + + async readFileAndSetContent(path: string) { + const file = this.app.vault.getFileByPath(path); + if (!file) return; + this.content = await this.app.vault.cachedRead(file); + } + + setTitleFromFile(path: string) { + this.activeFilePath = path; + const file = this.app.vault.getFileByPath(path); + if (!file) return; + this.title = extractTitle(this.content, file.basename); + this.selectedFid = extractFid(this.content, this.currentSite.defaultFid); + } + + async publish() { + if (!this.title || !this.content) { + new Notice("标题或内容不能为空"); + return; + } + this.notice = new Notice("发布中..."); + try { + // ===== 1. 确定发帖身份 ===== + if (this.selectedAlias) { + const aliases = parseAliases(this.currentSite.aliases); + const alias = aliases.find((a) => a.username === this.selectedAlias); + if (!alias) { + new Notice("❌ 未找到马甲:" + this.selectedAlias); + this.notice.hide(); + return; + } + console.log("[Discuz] 切换到马甲:", alias.username); + await HttpUtils.loginAs(alias.username, alias.password); + } else { + console.log("[Discuz] 使用主账号:", this.currentSite.username); + await HttpUtils.loginAs( + this.currentSite.username, + this.currentSite.password + ); + } + + // ===== 2. 发帖 ===== + let body = stripFrontmatter(this.content); + body = markdownToBBCode(body); + + const res = await HttpUtils.post("/post/newthread", { + fid: this.selectedFid, + subject: this.title, + message: body, + }); + + console.log("[Discuz] 发帖返回:", JSON.stringify(res, null, 2)); + + if (res.ret === 0) { + const tid = + res.tid || + res.data?.tid || + res.data?.msg?.values?.tid || + res.msg?.values?.tid; + console.log("[Discuz] 解析到的 tid:", tid); + const url = + tid && this.currentSite.siteUrl + ? `${this.currentSite.siteUrl}/forum.php?mod=viewthread&tid=${tid}` + : ""; + + if (tid && this.activeFilePath) { + await this.writeBackFrontmatter(this.activeFilePath, tid, url); + } + + new Notice( + "✅ 发布成功" + + (this.selectedAlias ? ` (${this.selectedAlias})` : "") + + (tid ? ` tid: ${tid}` : "") + ); + if (url) window.open(url, "_blank"); + } else { + new Notice("❌ 发布失败: " + (res.msg?.message || res.msg || "未知错误")); + } + + // ===== 3. 恢复主账号身份 ===== + try { + console.log("[Discuz] 发帖结束,恢复主账号:", this.currentSite.username); + await HttpUtils.loginAs( + this.currentSite.username, + this.currentSite.password + ); + } catch (e) { + console.error("[Discuz] 恢复主账号失败:", e); + } + + // ===== 4. 关闭弹窗 ===== + this.close(); + } catch (e) { + console.error(e); + new Notice("❌ " + (e instanceof Error ? e.message : String(e))); + // 出错也要尽量恢复主账号 + try { + await HttpUtils.loginAs( + this.currentSite.username, + this.currentSite.password + ); + } catch {} + } finally { + this.notice.hide(); + } + } + + private async writeBackFrontmatter(path: string, tid: number, url: string) { + const file = this.app.vault.getFileByPath(path); + if (!file) return; + let content = await this.app.vault.read(file); + + const now = new Date().toISOString(); + const discuzYaml = [ + `discuz_tid: ${tid}`, + `discuz_fid: ${this.selectedFid}`, + `discuz_site: ${this.currentSite.name}`, + this.selectedAlias ? `discuz_as: ${this.selectedAlias}` : "", + `discuz_url: ${url}`, + `discuz_published: ${now}`, + ] + .filter(Boolean) + .join("\n"); + + const fmRegex = /^---\n([\s\S]*?)\n---\n?/; + const match = content.match(fmRegex); + + if (match) { + let fm = match[1]; + // 移除旧的 discuz_ 字段 + fm = fm.replace(/\ndiscuz_\w+:.*\n?/g, "\n"); + fm = fm.replace(/^discuz_\w+:.*\n?/gm, ""); + const newFm = fm.trimEnd() + "\n" + discuzYaml; + content = content.replace(fmRegex, `---\n${newFm}\n---\n`); + } else { + content = `---\n${discuzYaml}\n---\n\n${content}`; + } + + await this.app.vault.modify(file, content); + } + + onClose() { + this.contentEl.empty(); + } +} \ No newline at end of file