同步插件源代码并补齐标准项目文件

This commit is contained in:
XIGE
2026-11-26 15:04:25 +08:00
parent 0738175c91
commit ebaded9af8
12 changed files with 1217 additions and 1 deletions

29
.gitignore vendored Normal file
View File

@@ -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

7
CHANGELOG.md Normal file
View File

@@ -0,0 +1,7 @@
# 变更记录
## 2026-11-26 · 初始同步
- 同步插件源代码到新 Gitea 仓库。
- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。
- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。

19
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,19 @@
# 贡献指南
欢迎对本插件提出改进建议或提交代码。
## 提交前检查
- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。
- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。
- 涉及对外服务或凭据的配置不要写入代码或文档。
## 提交流程
1. Fork 仓库并创建功能分支。
2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
3. 重要功能变更请同步更新 `CHANGELOG.md`。
## 问题反馈
请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。

21
LICENSE Normal file
View File

@@ -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.

View File

@@ -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` 及源码目录放入 `<Vault>/.obsidian/plugins/<插件 id>/`。
3. 在 Obsidian「设置 → 第三方插件」中启用该插件。
## 开发与贡献
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
## 授权
授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
## 变更记录
详见 [CHANGELOG.md](CHANGELOG.md)。

9
manifest.json Normal file
View File

@@ -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
}

64
src/main.ts Normal file
View File

@@ -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);
}
}

View File

@@ -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(),
};
});
}

269
src/setting/setting_tab.ts Normal file
View File

@@ -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();
})
);
}
}

58
src/utils/converter.ts Normal file
View File

@@ -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;
}

234
src/utils/request.ts Normal file
View File

@@ -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<string> {
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<Record<string, string>> {
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<string, string> = {
"Content-Type": "application/json",
appid,
nonce,
t: String(t),
sign: s,
};
if (token) raw.token = token;
const headers: Record<string, string> = {};
for (const [k, v] of Object.entries(raw)) {
headers[this.capitalize(k)] = v;
}
return headers;
}
private static async ensureToken(): Promise<void> {
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<string, any>): Promise<any> {
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<any> {
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<any> {
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<any> {
await this.ensureToken();
return { token: this.token };
}
}

410
src/view/push.ts Normal file

File diff suppressed because it is too large Load Diff