From f16bb8cebbb6c0881d917e7e18958777bbc1644a Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:05:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 29 ++ CHANGELOG.md | 7 + CONTRIBUTING.md | 19 ++ LICENSE | 21 ++ README.md | 31 +- main.ts | 890 ++++++++++++++++++++++++++++++++++++++++++++++++ manifest.json | 10 + styles.css | 120 +++++++ 8 files changed, 1126 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 main.ts create mode 100644 manifest.json create mode 100644 styles.css 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 7a3e348..958b138 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ -# XiaoHongShu +# Xiaohongshu Sync +> 仓库:`XiaoHongShu` · 类型:Obsidian 插件 · 版本:`1.0.0` · 作者:XIGE + +导入小红书笔记及其媒体与分类信息,带附件的笔记保存为同名文件夹。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `main.ts` +- `manifest.json` +- `styles.css` + +## 安装与使用 + +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/main.ts b/main.ts new file mode 100644 index 0000000..3d375a4 --- /dev/null +++ b/main.ts @@ -0,0 +1,890 @@ +import { Plugin, Notice, Modal, requestUrl, PluginSettingTab, App, Setting } from "obsidian"; + +interface XHSSyncSettings { + defaultFolder: string; + categories: string[]; + lastCategory: string; + downloadMedia: boolean; + aiEnabled: boolean; + aiApiKey: string; + aiApiUrl: string; + aiModel: string; +} + +const DEFAULT_SETTINGS: XHSSyncSettings = { + defaultFolder: "xhs", + categories: ["美食", "旅行", "娱乐", "知识", "工作", "情感", "个人成长", "优惠", "搞笑", "育儿"], + lastCategory: "", + downloadMedia: false, + aiEnabled: false, + aiApiKey: "", + aiApiUrl: "https://api.deepseek.com/chat/completions", + aiModel: "deepseek-chat", +}; + +export default class XHSSyncPlugin extends Plugin { + settings: XHSSyncSettings; + + async onload() { + await this.loadSettings(); + + this.addRibbonIcon("book", "导入小红书笔记", async () => { + const input = await this.promptForShareText(); + if (input && input.text) { + const url = this.extractURL(input.text); + if (url) { + await this.importXHSNote(url, input.category, input.downloadMedia); + } else { + new Notice("未在文本中找到有效的小红书链接。"); + } + } + }); + + this.addCommand({ + id: "import", + name: "导入小红书笔记", + callback: async () => { + const input = await this.promptForShareText(); + if (input && input.text) { + const url = this.extractURL(input.text); + if (url) { + await this.importXHSNote(url, input.category, input.downloadMedia); + } else { + new Notice("未在文本中找到有效的小红书链接。"); + } + } + }, + }); + + this.addSettingTab(new XHSSyncSettingTab(this.app, this)); + } + + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + + async saveSettings() { + await this.saveData(this.settings); + } + + async promptForShareText(): Promise<{ text: string | null; category: string; downloadMedia: boolean } | null> { + return new Promise((resolve) => { + const modal = new XHSInputModal(this.app, this, (result) => resolve(result)); + modal.open(); + }); + } + + extractURL(shareText: string): string | null { + const mobileUrlMatch = shareText.match(/https?:\/\/xhslink\.(?:com|cn)\/[a-zA-Z0-9/?=&._-]+/); + if (mobileUrlMatch) { + return mobileUrlMatch[0]; + } + + const webUrlMatch = shareText.match(/https?:\/\/www\.xiaohongshu\.com\/(?:discovery\/item|explore)\/[a-zA-Z0-9]+(?:\?[^\s,,]*)?/); + if (webUrlMatch) { + return webUrlMatch[0].replace('/explore/', '/discovery/item/'); + } + + return null; + } + + // ===== AI 调用底层方法 ===== + async callAI(systemPrompt: string, userContent: string): Promise { + const response = await requestUrl({ + url: this.settings.aiApiUrl, + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${this.settings.aiApiKey}`, + }, + body: JSON.stringify({ + model: this.settings.aiModel, + messages: [ + { role: "system", content: systemPrompt }, + { role: "user", content: userContent }, + ], + temperature: 0.7, + }), + }); + + const json = response.json; + const content = json?.choices?.[0]?.message?.content; + if (!content) throw new Error("AI 返回内容为空"); + return content.trim(); + } + + // ===== AI 生成标题 ===== + async generateTitleWithAI(content: string): Promise { + try { + const result = await this.callAI( + "你是小红书笔记标题助手。请根据用户提供的笔记正文,生成一个简洁的中文标题。要求:不超过 20 个字,不要标点符号,不要引号,不要表情符号,只返回标题本身。", + content.substring(0, 1500) + ); + let title = result.replace(/["""'']/g, "").replace(/[。!?,、;:]/g, "").trim(); + title = title.substring(0, 20); + return title || ""; + } catch (e) { + console.log(`AI 生成标题失败:${e.message}`); + return ""; + } + } + + // ===== AI 生成标签 ===== + async generateTagsWithAI(content: string): Promise { + try { + const result = await this.callAI( + "你是小红书笔记标签助手。请根据用户提供的笔记正文,生成 3-6 个中文标签。要求:每个标签不超过 8 个字,不要带 # 号,不要标点符号。只返回一个 JSON 数组,例如 [\"自然教育\",\"户外活动\"],不要有其他文字。", + content.substring(0, 2000) + ); + + const jsonMatch = result.match(/\[[\s\S]*\]/); + if (jsonMatch) { + const tags = JSON.parse(jsonMatch[0]); + if (Array.isArray(tags)) { + return tags + .map((t: any) => String(t).replace(/[#\s]/g, "").trim()) + .filter((t: string) => t.length > 0) + .slice(0, 6); + } + } + } catch (e) { + console.log(`AI 生成标签失败:${e.message}`); + } + return []; + } + + // ===== AI 生成摘要(标题扩写 + 按类型适配) ===== + async generateSummaryWithAI(content: string): Promise { + try { + const fullContent = content.length > 8000 ? content.substring(0, 8000) : content; + + const result = await this.callAI( + `你是笔记摘要助手。请先判断这篇笔记的类型,再按对应方式写摘要: + +- 观点论述型:提炼最核心的观点或结论 +- 清单/数据型:概括内容主题 + 列出最重要的 1-2 个关键数据或条目 +- 教程/步骤型:概括目标 + 核心步骤 + +摘要其实内容更丰富的标题,要让读者一眼知道这篇笔记主要讲了什么。严格控制在 60 字以内,只返回摘要本身,不要分点,不要表情符号,不要引号。`, + fullContent + ); + + return result.replace(/\n+/g, " ").trim(); + } catch (e) { + console.log(`AI 生成摘要失败:${e.message}`); + return ""; + } + } + + async downloadMediaFile(url: string, folderPath: string, filename: string): Promise { + try { + const response = await fetch(url); + if (!response.ok) throw new Error(`HTTP 错误 ${response.status}`); + const blob = await response.blob(); + const arrayBuffer = await blob.arrayBuffer(); + const filePath = `${folderPath}/${filename}`; + await this.app.vault.adapter.writeBinary(filePath, arrayBuffer); + return filename; + } catch (error) { + console.log(`下载媒体失败 ${url}: ${error.message}`); + new Notice(`下载媒体失败:${error.message}`); + return url; + } + } + + formatContent(rawContent: string): string { + let text = rawContent; + text = text.replace(/#[^#\s]*(?:\s+#[^#\s]*)*\s*/g, ""); + const lines = text.split("\n").map((line) => line.trim()); + const paragraphs: string[] = []; + let buffer: string[] = []; + + for (const line of lines) { + if (line === "") { + if (buffer.length > 0) { + paragraphs.push(buffer.join(" ")); + buffer = []; + } + } else { + buffer.push(line); + } + } + if (buffer.length > 0) { + paragraphs.push(buffer.join(" ")); + } + + return paragraphs.join("\n\n"); + } + + formatDateTime(date: Date): string { + const y = date.getFullYear(); + const m = String(date.getMonth() + 1).padStart(2, "0"); + const d = String(date.getDate()).padStart(2, "0"); + const hh = String(date.getHours()).padStart(2, "0"); + const mm = String(date.getMinutes()).padStart(2, "0"); + const ss = String(date.getSeconds()).padStart(2, "0"); + return `${y}-${m}-${d} ${hh}:${mm}:${ss}`; + } + + async importXHSNote(url: string, category: string, downloadMedia: boolean) { + try { + const response = await requestUrl({ url }); + const html = response.text; + + let title = this.extractTitle(html); + const videoUrl = this.extractVideoUrl(html); + const images = this.extractImages(html); + const content = this.extractContent(html); + const isVideo = this.isVideoNote(html); + const author = this.extractAuthor(html); + const publishTime = this.extractPublishTime(html); + + const now = new Date(); + const noteDate = this.formatDateTime(now).split(" ")[0]; + const importedAt = this.formatDateTime(now); + + // ===== AI 处理 ===== + let aiSummary = ""; + let tags: string[] = []; + + if (this.settings.aiEnabled && this.settings.aiApiKey) { + if (!title || title.trim().length === 0) { + new Notice("正在用 AI 生成标题..."); + const aiTitle = await this.generateTitleWithAI(content); + if (aiTitle) title = aiTitle; + } + + new Notice("正在用 AI 生成标签..."); + tags = await this.generateTagsWithAI(content); + + new Notice("正在用 AI 生成摘要..."); + aiSummary = await this.generateSummaryWithAI(content); + } + + if (!title || title.trim().length === 0) { + const firstLine = content.split("\n")[0].trim(); + title = firstLine.substring(0, 20) || "无标题"; + } + + if (tags.length === 0) { + tags = this.extractTags(content); + } + + const baseFolder = this.settings.defaultFolder || "xhs"; + const categoryFolder = category || "未分类"; + const folderPath = baseFolder ? `${baseFolder}/${categoryFolder}` : categoryFolder; + + let safeTitle = title + .replace(/[/\\?%*:|"<>]/g, "-") + .replace(/[\x00-\x1f\x7f]/g, "") + .replace(/\s+/g, " ") + .trim(); + + safeTitle = safeTitle.length > 0 ? safeTitle : "无标题"; + safeTitle = safeTitle.substring(0, 20); + + const datePrefix = noteDate; + const fileBaseName = `${datePrefix}_${safeTitle}`; + + const hasMedia = (images.length > 0 || (isVideo && videoUrl)) && downloadMedia; + + let notePath: string; + let mediaFolder: string; + + if (hasMedia) { + const noteFolder = `${folderPath}/${fileBaseName}`; + if (!await this.app.vault.adapter.exists(noteFolder)) { + await this.app.vault.createFolder(noteFolder); + } + notePath = `${noteFolder}/${fileBaseName}.md`; + mediaFolder = noteFolder; + } else { + if (!await this.app.vault.adapter.exists(folderPath)) { + await this.app.vault.createFolder(folderPath); + } + notePath = `${folderPath}/${fileBaseName}.md`; + mediaFolder = folderPath; + } + + const formattedContent = this.formatContent(content); + + let frontmatterTags = "tags: []\n"; + if (tags.length > 0) { + frontmatterTags = "tags:\n" + tags.map((tag) => ` - ${tag}`).join("\n") + "\n"; + } + + let markdown = `--- +title: ${title} +作者: ${author.nickname || "未知作者"} +作者主页: ${author.profileUrl || ""} +发布时间: ${publishTime || "未知"} +source: ${url} +导入时间: ${importedAt} +分类: ${category} +${frontmatterTags}--- +# ${title} + +`; + + if (aiSummary) { + markdown += `> [!abstract] AI 摘要\n> ${aiSummary}\n\n`; + } + + if (isVideo) { + if (videoUrl) { + let finalVideoUrl = videoUrl; + if (downloadMedia) { + const videoFilename = `video.mp4`; + const downloadedFilename = await this.downloadMediaFile(videoUrl, mediaFolder, videoFilename); + finalVideoUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`; + } + markdown += `\n\n`; + } else if (images.length > 0) { + let finalImageUrl = images[0]; + if (downloadMedia) { + const imageFilename = `1.jpg`; + const downloadedFilename = await this.downloadMediaFile(images[0], mediaFolder, imageFilename); + finalImageUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`; + } + markdown += `[![封面图](${finalImageUrl})](${url})\n\n`; + new Notice("未找到视频地址,已使用封面图替代。"); + } + } + + markdown += `${formattedContent}\n\n`; + + if (!isVideo && images.length > 0) { + markdown += `---\n\n## 图片\n\n`; + let downloadedImages: string[] = []; + + if (downloadMedia) { + for (let i = 0; i < images.length; i++) { + const imageFilename = `${i + 1}.jpg`; + const downloadedFilename = await this.downloadMediaFile(images[i], mediaFolder, imageFilename); + const finalImageUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`; + downloadedImages.push(finalImageUrl); + } + } else { + downloadedImages = images; + } + + markdown += downloadedImages.map((url, idx) => `**图 ${idx + 1}**\n\n![图片](${url})`).join("\n\n") + "\n"; + } + + const file = await this.app.vault.create(notePath, markdown); + await this.app.workspace.getLeaf(true).openFile(file); + + this.settings.lastCategory = category; + await this.saveSettings(); + + new Notice(`已导入小红书笔记:${notePath}`); + } catch (error) { + console.log(`导入笔记失败 ${url}: ${error.message}`); + new Notice(`导入笔记失败:${error.message}`); + } + } + + extractTitle(html: string): string { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (stateMatch) { + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const note = state.note.noteDetailMap[noteId].note; + + const titleFromState = note.title || note.displayTitle || ""; + if (titleFromState && titleFromState.trim().length > 0) { + return titleFromState.trim(); + } + } catch (e) { + console.log(`从 JSON 解析标题失败:${e.message}`); + } + } + + return ""; + } + + extractImages(html: string): string[] { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (!stateMatch) return []; + + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const imageList = state.note.noteDetailMap[noteId].note.imageList || []; + return imageList + .map((img: any) => img.urlDefault || "") + .filter((url: string) => url && url.startsWith("http")); + } catch (e) { + console.log(`解析图片失败:${e.message}`); + return []; + } + } + + extractVideoUrl(html: string): string | null { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (!stateMatch) return null; + + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const noteData = state.note.noteDetailMap[noteId].note; + const videoInfo = noteData.video; + + if (!videoInfo || !videoInfo.media || !videoInfo.media.stream) return null; + + if (videoInfo.media.stream.h264 && videoInfo.media.stream.h264.length > 0) { + return videoInfo.media.stream.h264[0].masterUrl || null; + } + if (videoInfo.media.stream.h265 && videoInfo.media.stream.h265.length > 0) { + return videoInfo.media.stream.h265[0].masterUrl || null; + } + return null; + } catch (e) { + console.log(`解析视频失败:${e.message}`); + return null; + } + } + + extractContent(html: string): string { + const divMatch = html.match(/
([\s\S]*?)<\/div>/); + if (divMatch) { + return divMatch[1] + .replace(/<[^>]+>/g, "") + .replace(/\[话题\]/g, "") + .replace(/\[[^\]]+\]/g, "") + .trim() || "未找到正文内容"; + } + + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (stateMatch) { + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const desc = state.note.noteDetailMap[noteId].note.desc || ""; + return desc + .replace(/\[话题\]/g, "") + .replace(/\[[^\]]+\]/g, "") + .trim() || "未找到正文内容"; + } catch (e) { + console.log(`解析正文失败:${e.message}`); + } + } + return "未找到正文内容"; + } + + isVideoNote(html: string): boolean { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (!stateMatch) return false; + + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const noteType = state.note.noteDetailMap[noteId].note.type; + return noteType === "video"; + } catch (e) { + console.log(`判断笔记类型失败:${e.message}`); + return false; + } + } + + extractAuthor(html: string): { nickname: string; profileUrl: string } { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (!stateMatch) return { nickname: "", profileUrl: "" }; + + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const note = state.note.noteDetailMap[noteId].note; + const user = note.user || {}; + + const nickname = user.nickname || user.nickName || ""; + const userId = user.userId || user.user_id || ""; + const profileUrl = userId ? `https://www.xiaohongshu.com/user/profile/${userId}` : ""; + + return { nickname, profileUrl }; + } catch (e) { + console.log(`解析作者信息失败:${e.message}`); + return { nickname: "", profileUrl: "" }; + } + } + + extractPublishTime(html: string): string { + const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s); + if (!stateMatch) return ""; + + try { + const jsonStr = stateMatch[1].trim(); + const cleanedJson = jsonStr.replace(/undefined/g, "null"); + const state = JSON.parse(cleanedJson); + const noteId = Object.keys(state.note.noteDetailMap)[0]; + const note = state.note.noteDetailMap[noteId].note; + const rawTime = note.time || note.publishTime || ""; + + if (!rawTime) return ""; + + const date = new Date(Number(rawTime)); + if (isNaN(date.getTime())) return ""; + + const y = date.getFullYear(); + const m = String(date.getMonth() + 1).padStart(2, "0"); + const d = String(date.getDate()).padStart(2, "0"); + return `${y}-${m}-${d}`; + } catch (e) { + console.log(`解析发布时间失败:${e.message}`); + return ""; + } + } + + extractTags(content: string): string[] { + const tagMatches = content.match(/#[\w\u4e00-\u9fa5-]+/g) || []; + return tagMatches.map((tag) => tag.replace("#", "").trim()); + } + + onunload() {} +} + +class XHSSyncSettingTab extends PluginSettingTab { + plugin: XHSSyncPlugin; + + constructor(app: App, plugin: XHSSyncPlugin) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + + new Setting(containerEl) + .setName("默认存储文件夹") + .setDesc("笔记保存的基础文件夹。留空则保存到库根目录。") + .addText((text) => + text + .setPlaceholder("xhs") + .setValue(this.plugin.settings.defaultFolder) + .onChange(async (value) => { + this.plugin.settings.defaultFolder = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName("默认下载媒体") + .setDesc("开启后,导入时默认将图片和视频下载到本地。每次导入时仍可单独覆盖。") + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.downloadMedia) + .onChange(async (value) => { + this.plugin.settings.downloadMedia = value; + await this.plugin.saveSettings(); + }) + ); + + const aiHeading = new Setting(containerEl) + .setName("AI 功能") + .setHeading(); + aiHeading.settingEl.addClass("xhs-setting-heading"); + + containerEl.createEl("p", { + text: "开启后,导入笔记时会调用 AI 自动生成标题(仅无标题时)、标签和摘要。需要填写 DeepSeek API Key。", + }); + + new Setting(containerEl) + .setName("开启 AI 功能") + .setDesc("关闭时,标题和标签走原有逻辑,不生成摘要。") + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.aiEnabled) + .onChange(async (value) => { + this.plugin.settings.aiEnabled = value; + await this.plugin.saveSettings(); + this.display(); + }) + ); + + if (this.plugin.settings.aiEnabled) { + new Setting(containerEl) + .setName("AI API Key") + .setDesc("DeepSeek 的 API Key,形如 sk-xxxxxx。") + .addText((text) => + text + .setPlaceholder("sk-...") + .setValue(this.plugin.settings.aiApiKey) + .onChange(async (value) => { + this.plugin.settings.aiApiKey = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName("AI API 地址") + .setDesc("默认使用 DeepSeek 官方接口。如果使用其他兼容 OpenAI 格式的服务,可以改这里。") + .addText((text) => + text + .setPlaceholder("https://api.deepseek.com/chat/completions") + .setValue(this.plugin.settings.aiApiUrl) + .onChange(async (value) => { + this.plugin.settings.aiApiUrl = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName("AI 模型名") + .setDesc("默认 deepseek-chat。") + .addText((text) => + text + .setPlaceholder("deepseek-chat") + .setValue(this.plugin.settings.aiModel) + .onChange(async (value) => { + this.plugin.settings.aiModel = value.trim(); + await this.plugin.saveSettings(); + }) + ); + } + + const headingSetting = new Setting(containerEl) + .setName("分类管理") + .setHeading(); + headingSetting.settingEl.addClass("xhs-setting-heading"); + + containerEl.createEl("p", { text: "添加、编辑或删除用于整理笔记的分类。使用上下箭头调整顺序。" }); + + this.plugin.settings.categories.forEach((category, index) => { + const setting = new Setting(containerEl) + .setName(`分类 ${index + 1}`) + .addText((text) => + text + .setValue(category) + .onChange(async (value) => { + this.plugin.settings.categories[index] = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + setting.addButton((button) => + button + .setIcon("arrow-up") + .setTooltip("上移") + .setDisabled(index === 0) + .onClick(async () => { + if (index > 0) { + [this.plugin.settings.categories[index], this.plugin.settings.categories[index - 1]] = + [this.plugin.settings.categories[index - 1], this.plugin.settings.categories[index]]; + await this.plugin.saveSettings(); + this.display(); + } + }) + ); + + setting.addButton((button) => + button + .setIcon("arrow-down") + .setTooltip("下移") + .setDisabled(index === this.plugin.settings.categories.length - 1) + .onClick(async () => { + if (index < this.plugin.settings.categories.length - 1) { + [this.plugin.settings.categories[index], this.plugin.settings.categories[index + 1]] = + [this.plugin.settings.categories[index + 1], this.plugin.settings.categories[index]]; + await this.plugin.saveSettings(); + this.display(); + } + }) + ); + + setting.addButton((button) => + button + .setButtonText("删除") + .onClick(async () => { + this.plugin.settings.categories.splice(index, 1); + await this.plugin.saveSettings(); + this.display(); + }) + ); + }); + + new Setting(containerEl) + .addButton((button) => + button + .setButtonText("添加分类") + .onClick(async () => { + this.plugin.settings.categories.push("新分类"); + await this.plugin.saveSettings(); + this.display(); + }) + ); + } +} + +class XHSInputModal extends Modal { + result: { text: string | null; category: string; downloadMedia: boolean } | null = null; + onSubmit: (result: { text: string | null; category: string; downloadMedia: boolean } | null) => void; + plugin: XHSSyncPlugin; + selectedCategory: string; + downloadMedia: boolean; + + constructor(app: App, plugin: XHSSyncPlugin, onSubmit: (result: { text: string | null; category: string; downloadMedia: boolean } | null) => void) { + super(app); + this.plugin = plugin; + this.onSubmit = onSubmit; + this.selectedCategory = this.plugin.settings.lastCategory && this.plugin.settings.categories.includes(this.plugin.settings.lastCategory) + ? this.plugin.settings.lastCategory + : this.plugin.settings.categories[0] || "其他"; + this.downloadMedia = this.plugin.settings.downloadMedia; + } + + onOpen() { + const { contentEl } = this; + contentEl.addClass("xhs-modal-content"); + + contentEl.createEl("h2", { text: "导入小红书笔记" }); + + const textRow = contentEl.createEl("div", { cls: "xhs-modal-row" }); + textRow.createEl("p", { text: "粘贴分享文本:" }); + const input = textRow.createEl("textarea", { + cls: "xhs-modal-textarea", + attr: { placeholder: "例如:64 不叫小黄了发布了一篇小红书笔记..." }, + }); + + const categoryRow = contentEl.createEl("div", { cls: "xhs-modal-row" }); + categoryRow.createEl("p", { text: "选择分类:" }); + const chipContainer = categoryRow.createEl("div", { cls: "xhs-chip-container" }); + + const addCategoryRow = contentEl.createEl("div", { cls: "xhs-add-category-row" }); + const newCategoryInput = addCategoryRow.createEl("input", { + cls: "xhs-add-category-input", + attr: { type: "text", placeholder: "新增分类名称" }, + }); + const addCategoryButton = addCategoryRow.createEl("button", { + text: "新增分类", + cls: "xhs-add-category-button", + }); + + const updateChipStyles = () => { + chipContainer.querySelectorAll("button").forEach((btn) => { + if (btn.textContent === this.selectedCategory) { + btn.classList.add("xhs-chip--selected"); + } else { + btn.classList.remove("xhs-chip--selected"); + } + }); + }; + + const renderChips = () => { + chipContainer.empty(); + + this.plugin.settings.categories.forEach((category) => { + const chip = chipContainer.createEl("button", { + text: category, + cls: "xhs-chip", + }); + if (category === this.selectedCategory) { + chip.classList.add("xhs-chip--selected"); + } + + chip.addEventListener("click", () => { + this.selectedCategory = category; + updateChipStyles(); + }); + }); + + const otherChip = chipContainer.createEl("button", { + text: "其他", + cls: "xhs-chip", + }); + if ("其他" === this.selectedCategory) { + otherChip.classList.add("xhs-chip--selected"); + } + + otherChip.addEventListener("click", () => { + this.selectedCategory = "其他"; + updateChipStyles(); + }); + }; + + renderChips(); + + const handleAddCategory = async () => { + const name = newCategoryInput.value.trim(); + if (!name) { + new Notice("请输入分类名称。"); + return; + } + if (name === "其他") { + new Notice("“其他”是保留分类,请换一个名称。"); + return; + } + if (this.plugin.settings.categories.includes(name)) { + new Notice("该分类已存在。"); + return; + } + + this.plugin.settings.categories.push(name); + await this.plugin.saveSettings(); + + this.selectedCategory = name; + newCategoryInput.value = ""; + renderChips(); + + new Notice(`已新增分类:${name}`); + }; + + addCategoryButton.addEventListener("click", handleAddCategory); + newCategoryInput.addEventListener("keypress", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + handleAddCategory(); + } + }); + + const downloadRow = contentEl.createEl("div", { cls: ["xhs-modal-row", "xhs-download-row"] }); + const downloadWrapper = downloadRow.createEl("div", { cls: "xhs-download-wrapper" }); + const checkboxId = "download-media-checkbox"; + const checkbox = downloadWrapper.createEl("input", { attr: { type: "checkbox", id: checkboxId } }); + checkbox.checked = this.downloadMedia; + checkbox.addEventListener("change", () => { + this.downloadMedia = checkbox.checked; + }); + downloadWrapper.createEl("label", { + text: "本次导入下载媒体到本地", + cls: "xhs-download-label", + attr: { for: checkboxId }, + }); + + const buttonRow = contentEl.createEl("div", { cls: ["xhs-modal-row", "xhs-button-row"] }); + const submitButton = buttonRow.createEl("button", { + text: "导入", + cls: "xhs-submit-button", + }); + + submitButton.addEventListener("click", () => { + this.result = { text: input.value.trim(), category: this.selectedCategory, downloadMedia: this.downloadMedia }; + this.close(); + }); + + input.addEventListener("keypress", (e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + this.result = { text: input.value.trim(), category: this.selectedCategory, downloadMedia: this.downloadMedia }; + this.close(); + } + }); + } + + onClose() { + this.onSubmit(this.result); + } +} \ No newline at end of file diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..c7d4af1 --- /dev/null +++ b/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "xiaohongshu-sync", + "name": "Xiaohongshu Sync", + "version": "1.0.0", + "minAppVersion": "0.15.0", + "description": "Import Xiaohongshu (小红书) notes with media and categorization. Notes with attachments are saved in same-name folders.", + "author": "Your Name", + "authorUrl": "https://github.com/your-username", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..d489334 --- /dev/null +++ b/styles.css @@ -0,0 +1,120 @@ +/* styles.css */ + +/* Modal content container */ +.xhs-modal-content { + display: flex; + flex-direction: column; + gap: 10px; + padding: 10px; +} + +/* Row containers (used for text, category, download, and button rows) */ +.xhs-modal-row { + display: flex; + flex-direction: column; +} + +/* Text input (textarea) */ +.xhs-modal-textarea { + width: 100%; + height: 100px; + margin: 0; +} + +/* Category chip container */ +.xhs-chip-container { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +/* Category chip (button) */ +.xhs-chip { + padding: 4px 8px; + border-radius: 12px; + border: 1px solid #ccc; + background-color: #f0f0f0; + color: #000; + cursor: pointer; + transition: background-color 0.2s; +} + +/* Selected category chip with increased specificity */ +.xhs-chip.xhs-chip--selected { + background-color: #FF2442; + color: #fff; +} + +/* 新增分类行 */ +.xhs-add-category-row { + display: flex; + gap: 8px; + align-items: center; + margin-top: 4px; +} + +/* 新增分类输入框 */ +.xhs-add-category-input { + flex: 1; + padding: 4px 8px; + border: 1px solid #ccc; + border-radius: 4px; + background-color: var(--background-modifier-form-field); + color: var(--text-normal); +} + +/* 新增分类按钮 */ +.xhs-add-category-button { + padding: 4px 12px; + border: 1px solid #ccc; + border-radius: 4px; + background-color: #f0f0f0; + color: #000; + cursor: pointer; + white-space: nowrap; +} + +.xhs-add-category-button:hover { + background-color: #e0e0e0; +} + +/* Download row specific styles */ +.xhs-download-row { + flex-direction: row !important; + align-items: center; + gap: 8px; + margin-top: 20px; + margin-bottom: 20px; +} + +/* Wrapper for checkbox and label to ensure alignment */ +.xhs-download-wrapper { + display: flex; + align-items: center; + gap: 8px; +} + +/* Download label */ +.xhs-download-label { + cursor: pointer; + margin: 0; + line-height: normal; +} + +/* Button row specific styles */ +.xhs-button-row { + display: flex; + justify-content: flex-end; +} + +/* Submit button */ +.xhs-submit-button { + width: 100%; + margin: 0; +} + +/* 去掉设置页面分类管理标题的左边距 */ +.xhs-setting-heading { + margin-left: 0; + padding-left: 0; +} \ No newline at end of file