From cdbe60b5fe09861c0b903b9cf906956ac6d5b50d Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:05:05 +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 ++ manifest.json | 10 + src/lang/README.md | 13 + src/lang/helpers.ts | 57 +++ src/lang/locale/ar.ts | 3 + src/lang/locale/cz.ts | 3 + src/lang/locale/da.ts | 3 + src/lang/locale/de.ts | 3 + src/lang/locale/en-gb.ts | 3 + src/lang/locale/en.ts | 42 +++ src/lang/locale/es.ts | 3 + src/lang/locale/fr.ts | 3 + src/lang/locale/hi.ts | 3 + src/lang/locale/id.ts | 3 + src/lang/locale/it.ts | 3 + src/lang/locale/ja.ts | 3 + src/lang/locale/ko.ts | 3 + src/lang/locale/nl.ts | 3 + src/lang/locale/no.ts | 3 + src/lang/locale/pl.ts | 3 + src/lang/locale/pt-br.ts | 4 + src/lang/locale/pt.ts | 3 + src/lang/locale/ro.ts | 3 + src/lang/locale/ru.ts | 3 + src/lang/locale/tr.ts | 3 + src/lang/locale/zh-cn.ts | 42 +++ src/lang/locale/zh-tw.ts | 3 + src/main.ts | 180 ++++++++++ src/qiniu_sidebar.ts | 746 +++++++++++++++++++++++++++++++++++++++ src/settings.ts | 171 +++++++++ src/uploader/qiniu.ts | 75 ++++ src/uploader/uploader.ts | 14 + styles.css | 217 ++++++++++++ 37 files changed, 1738 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 manifest.json create mode 100644 src/lang/README.md create mode 100644 src/lang/helpers.ts create mode 100644 src/lang/locale/ar.ts create mode 100644 src/lang/locale/cz.ts create mode 100644 src/lang/locale/da.ts create mode 100644 src/lang/locale/de.ts create mode 100644 src/lang/locale/en-gb.ts create mode 100644 src/lang/locale/en.ts create mode 100644 src/lang/locale/es.ts create mode 100644 src/lang/locale/fr.ts create mode 100644 src/lang/locale/hi.ts create mode 100644 src/lang/locale/id.ts create mode 100644 src/lang/locale/it.ts create mode 100644 src/lang/locale/ja.ts create mode 100644 src/lang/locale/ko.ts create mode 100644 src/lang/locale/nl.ts create mode 100644 src/lang/locale/no.ts create mode 100644 src/lang/locale/pl.ts create mode 100644 src/lang/locale/pt-br.ts create mode 100644 src/lang/locale/pt.ts create mode 100644 src/lang/locale/ro.ts create mode 100644 src/lang/locale/ru.ts create mode 100644 src/lang/locale/tr.ts create mode 100644 src/lang/locale/zh-cn.ts create mode 100644 src/lang/locale/zh-tw.ts create mode 100644 src/main.ts create mode 100644 src/qiniu_sidebar.ts create mode 100644 src/settings.ts create mode 100644 src/uploader/qiniu.ts create mode 100644 src/uploader/uploader.ts 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..1529712 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Shoujian Zheng + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..04995ce --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# Qiniu Image Uploader + +> 仓库:`Qiniu` · 类型:Obsidian 插件 · 版本:`1.1.5` · 作者:Jade Zheng + +将剪贴板图片上传到七牛云并插入 Obsidian 笔记。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `manifest.json` +- `src/` +- `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/manifest.json b/manifest.json new file mode 100644 index 0000000..2a2b73b --- /dev/null +++ b/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "qiniu-image-uploader", + "name": "Qiniu Image Uploader", + "version": "1.1.5", + "minAppVersion": "0.15.0", + "description": "Uploads images from your clipboard to qiniu.com and embeds uploaded image to your note.", + "author": "Jade Zheng", + "authorUrl": "https://github.com/jianzs", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/src/lang/README.md b/src/lang/README.md new file mode 100644 index 0000000..78f7f73 --- /dev/null +++ b/src/lang/README.md @@ -0,0 +1,13 @@ +## Localization + +The plugin has full localization support, and will attempt to load the current Obsidian locale. If one does not exist, it will fall back to English. + +### Adding a new Locale + +New locales can be added by creating a pull request. Two things should be done in this pull request: + +1. Create the locale in the `locales` folder by copying the `en.ts` file. This file should be given a name matching the string returned by `moment.locale()`. +2. Create the translation by editing the value of each property. +3. Add the import in `locales.ts`. +4. Add the language to the `localeMap` variable. + diff --git a/src/lang/helpers.ts b/src/lang/helpers.ts new file mode 100644 index 0000000..ec930e2 --- /dev/null +++ b/src/lang/helpers.ts @@ -0,0 +1,57 @@ +import { moment } from 'obsidian'; + +import ar from './locale/ar'; +import cz from './locale/cz'; +import da from './locale/da'; +import de from './locale/de'; +import en from './locale/en'; +import enGB from './locale/en-gb'; +import es from './locale/es'; +import fr from './locale/fr'; +import hi from './locale/hi'; +import id from './locale/id'; +import it from './locale/it'; +import ja from './locale/ja'; +import ko from './locale/ko'; +import nl from './locale/nl'; +import no from './locale/no'; +import pl from './locale/pl'; +import pt from './locale/pt'; +import ptBR from './locale/pt-br'; +import ro from './locale/ro'; +import ru from './locale/ru'; +import tr from './locale/tr'; +import zhCN from './locale/zh-cn'; +import zhTW from './locale/zh-tw'; + +const localeMap: { [k: string]: Partial } = { + ar, + cs: cz, + da, + de, + en, + 'en-gb': enGB, + es, + fr, + hi, + id, + it, + ja, + ko, + nl, + nn: no, + pl, + pt, + 'pt-br': ptBR, + ro, + ru, + tr, + 'zh-cn': zhCN, + 'zh-tw': zhTW, +}; + +const locale = localeMap[moment.locale()]; + +export function t(str: keyof typeof en): string { + return (locale && locale[str]) || en[str]; +} diff --git a/src/lang/locale/ar.ts b/src/lang/locale/ar.ts new file mode 100644 index 0000000..fdcaab2 --- /dev/null +++ b/src/lang/locale/ar.ts @@ -0,0 +1,3 @@ +// العربية + +export default {}; diff --git a/src/lang/locale/cz.ts b/src/lang/locale/cz.ts new file mode 100644 index 0000000..6ab53ab --- /dev/null +++ b/src/lang/locale/cz.ts @@ -0,0 +1,3 @@ +// čeština + +export default {}; diff --git a/src/lang/locale/da.ts b/src/lang/locale/da.ts new file mode 100644 index 0000000..68f85af --- /dev/null +++ b/src/lang/locale/da.ts @@ -0,0 +1,3 @@ +// Dansk + +export default {}; diff --git a/src/lang/locale/de.ts b/src/lang/locale/de.ts new file mode 100644 index 0000000..9d044c2 --- /dev/null +++ b/src/lang/locale/de.ts @@ -0,0 +1,3 @@ +// Deutsch + +export default {}; \ No newline at end of file diff --git a/src/lang/locale/en-gb.ts b/src/lang/locale/en-gb.ts new file mode 100644 index 0000000..3678622 --- /dev/null +++ b/src/lang/locale/en-gb.ts @@ -0,0 +1,3 @@ +// British English + +export default {}; diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts new file mode 100644 index 0000000..6d0e821 --- /dev/null +++ b/src/lang/locale/en.ts @@ -0,0 +1,42 @@ +// English + +export default { + // settings.ts + "Access Key": "Access key", + "Access Key Desc": "You can get key from key management from Qiniu personal center.", + "Access Key Input": "Enter your access key", + + "Access Secret Key": "Access secret key", + "Access Secret Key Desc": "You can get key from key management from Qiniu personal center.", + "Access Secret Key Input": "Enter your access secret key", + + "Bucket Name": "Bucket name", + "Bucket Name Desc": "Please indicate the bucket where you would like to upload the image.", + "Bucket Name Input": "The specific bucket", + + "Domain": "Domain", + "Domain Desc": "Go to the Qiniu bucket settings to configure the external link domain name, and enter the domain here.", + "Domain Input": "The external link domain name of above bucket", + + "Name Prefix": "Name prefix", + "Name Prefix Desc": "The uploaded filename's prefix in Qiniu, the uploaded filename will be: {{prefix}}{{timestamp}}.", + "Name Prefix Input": "The image's prefix", + + "Time Format": "Time format", + "Time Format Desc": "The time format in the configuration file name, the default is the timestamp format, and you can configure the format according to the [document](https://github.com/date-fns/date-fns/blob/main/docs/unicodeTokens.md), for example: yyMMdd-HHmmss.", + "Time Format Input": "Time format", + + "Region": "Region", + "Region Desc": "The region in which the bucket is located.", + + "North China - Hebei": "North China - Hebei", + "East China - Zhejiang": "East China - Zhejiang", + "East China - Zhejiang 2": "East China - Zhejiang 2", + "South China - Guangdong": "South China - Guangdong", + "North America - Los Angeles": "North America - Los Angeles", + "Asia Pacific - Singapore (formerly Southeast Asia)": "Asia Pacific - Singapore (formerly Southeast Asia)", + "HTTPS": "HTTPS", + "HTTPS Desc": "Whether to use HTTPS protocol", + "YES": "Yes", + "NO": "No", +}; diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts new file mode 100644 index 0000000..cc4ce68 --- /dev/null +++ b/src/lang/locale/es.ts @@ -0,0 +1,3 @@ +// Español + +export default {}; diff --git a/src/lang/locale/fr.ts b/src/lang/locale/fr.ts new file mode 100644 index 0000000..b05317b --- /dev/null +++ b/src/lang/locale/fr.ts @@ -0,0 +1,3 @@ +// français + +export default {}; diff --git a/src/lang/locale/hi.ts b/src/lang/locale/hi.ts new file mode 100644 index 0000000..ed2bf66 --- /dev/null +++ b/src/lang/locale/hi.ts @@ -0,0 +1,3 @@ +// हिन्दी + +export default {}; diff --git a/src/lang/locale/id.ts b/src/lang/locale/id.ts new file mode 100644 index 0000000..b431a6f --- /dev/null +++ b/src/lang/locale/id.ts @@ -0,0 +1,3 @@ +// Bahasa Indonesia + +export default {}; diff --git a/src/lang/locale/it.ts b/src/lang/locale/it.ts new file mode 100644 index 0000000..fb9329e --- /dev/null +++ b/src/lang/locale/it.ts @@ -0,0 +1,3 @@ +// Italiano + +export default {}; diff --git a/src/lang/locale/ja.ts b/src/lang/locale/ja.ts new file mode 100644 index 0000000..0876f5b --- /dev/null +++ b/src/lang/locale/ja.ts @@ -0,0 +1,3 @@ +// 日本語 + +export default {}; \ No newline at end of file diff --git a/src/lang/locale/ko.ts b/src/lang/locale/ko.ts new file mode 100644 index 0000000..74bfc3a --- /dev/null +++ b/src/lang/locale/ko.ts @@ -0,0 +1,3 @@ +// 한국어 + +export default {}; diff --git a/src/lang/locale/nl.ts b/src/lang/locale/nl.ts new file mode 100644 index 0000000..f6acbd3 --- /dev/null +++ b/src/lang/locale/nl.ts @@ -0,0 +1,3 @@ +// Nederlands + +export default {}; diff --git a/src/lang/locale/no.ts b/src/lang/locale/no.ts new file mode 100644 index 0000000..0739bc4 --- /dev/null +++ b/src/lang/locale/no.ts @@ -0,0 +1,3 @@ +// Norsk + +export default {}; diff --git a/src/lang/locale/pl.ts b/src/lang/locale/pl.ts new file mode 100644 index 0000000..caed52b --- /dev/null +++ b/src/lang/locale/pl.ts @@ -0,0 +1,3 @@ +// język polski + +export default {}; diff --git a/src/lang/locale/pt-br.ts b/src/lang/locale/pt-br.ts new file mode 100644 index 0000000..ace53cd --- /dev/null +++ b/src/lang/locale/pt-br.ts @@ -0,0 +1,4 @@ +// Português do Brasil +// Brazilian Portuguese + +export default {}; \ No newline at end of file diff --git a/src/lang/locale/pt.ts b/src/lang/locale/pt.ts new file mode 100644 index 0000000..f4cb0c8 --- /dev/null +++ b/src/lang/locale/pt.ts @@ -0,0 +1,3 @@ +// Português + +export default {}; diff --git a/src/lang/locale/ro.ts b/src/lang/locale/ro.ts new file mode 100644 index 0000000..4ea9cae --- /dev/null +++ b/src/lang/locale/ro.ts @@ -0,0 +1,3 @@ +// Română + +export default {}; diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts new file mode 100644 index 0000000..7b0f002 --- /dev/null +++ b/src/lang/locale/ru.ts @@ -0,0 +1,3 @@ +// русский + +export default {}; diff --git a/src/lang/locale/tr.ts b/src/lang/locale/tr.ts new file mode 100644 index 0000000..d1db79b --- /dev/null +++ b/src/lang/locale/tr.ts @@ -0,0 +1,3 @@ +// Türkçe + +export default {}; diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts new file mode 100644 index 0000000..7b6d95f --- /dev/null +++ b/src/lang/locale/zh-cn.ts @@ -0,0 +1,42 @@ +// 简体中文 + +export default { + // settings.ts + "Access Key": "Access Key", + "Access Key Desc": "从七牛云/个人中心/密钥管理获取 Access Key", + "Access Key Input": "请输入 Access Key", + + "Access Secret Key": "Access Secret Key", + "Access Secret Key Desc": "从七牛云/个人中心/密钥管理获取Access Secret Key", + "Access Secret Key Input": "请输入 Access Secret Key", + + "Bucket Name": "空间名称", + "Bucket Name Desc": "指定你要上传到哪个存储空间", + "Bucket Name Input": "指定的空间名称", + + "Domain": "外链域名", + "Domain Desc": "七牛云需要配置外链域名才能外部访问,在存储空间配置后,将配置域名输入在这里", + "Domain Input": "存储空间对应的外链域名", + + "Name Prefix": "文件名前缀", + "Name Prefix Desc": "配置上传文件的前缀,文件名将为:前缀{{timestamp}}", + "Name Prefix Input": "上传后的文件前缀", + + "Time Format": "时间格式", + "Time Format Desc": "配置文件名中时间的格式,默认为时间戳格式,可按[文档](https://github.com/date-fns/date-fns/blob/main/docs/unicodeTokens.md)配置,例如:yyMMdd-HHmmss", + "Time Format Input": "时间格式", + + "Region": "区域", + "Region Desc": "指明桶所在的区域", + + "North China - Hebei": "华北-河北", + "East China - Zhejiang": "华东-浙江", + "East China - Zhejiang 2": "华东-浙江2", + "South China - Guangdong": "华南-广东", + "North America - Los Angeles": "北美-洛杉矶", + "Asia Pacific - Singapore (formerly Southeast Asia)": "亚太-新加坡(原东南亚)", + "HTTPS": "HTTPS", + "HTTPS Desc": "是否使用HTTPS协议", + "YES": "是", + "NO": "否", +}; diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts new file mode 100644 index 0000000..0b7c4b6 --- /dev/null +++ b/src/lang/locale/zh-tw.ts @@ -0,0 +1,3 @@ +// 繁體中文 + +export default {}; diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..f615295 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,180 @@ +import { format } from 'date-fns'; +import { Editor, Notice, Plugin } from 'obsidian'; +import { DEFAULT_SETTINGS, PluginSettings, SettingTab } from './settings'; +import { Uploader, buildUploaderFrom } from './uploader/uploader'; +import { QiniuSidebar, VIEW_TYPE } from './qiniu_sidebar'; + +// 全局变量,供其他模块获取设置 +let pluginInstance: QiniuImageUploader | null = null; + +export function getSettings(): PluginSettings { + return pluginInstance?.settings || DEFAULT_SETTINGS; +} + +export default class QiniuImageUploader extends Plugin { + settings: PluginSettings; + uploader: Uploader | undefined; + + async onload() { + pluginInstance = this; + + await this.loadSettings(); + this.addSettingTab(new SettingTab(this.app, this)); + + this.registerEvent(this.app.workspace.on('editor-paste', this.customPasteEventCallback)); + this.registerEvent(this.app.workspace.on('editor-drop', this.customDropEventListener)); + + this.uploader = buildUploaderFrom(this.settings); + + this.registerView(VIEW_TYPE, (leaf) => new QiniuSidebar(leaf)); + + this.addRibbonIcon("cloud-upload", "七牛云管理", () => { + this.openSidebar(); + }); + + this.app.workspace.onLayoutReady(() => { + this.openSidebar(); + }); + } + + async openSidebar() { + const { workspace } = this.app; + let leaf = workspace.getLeavesOfType(VIEW_TYPE)[0]; + if (!leaf) { + leaf = workspace.getRightLeaf(false); + if (leaf) { + await leaf.setViewState({ + type: VIEW_TYPE, + active: true, + }); + } + } else { + workspace.revealLeaf(leaf); + } + } + + onunload() { + pluginInstance = null; + } + + private customPasteEventCallback = async (e: ClipboardEvent) => { + if (!this.uploader) { + QiniuImageUploader.showUnconfiguredPluginNotice(); + return; + } + if (e.clipboardData == null || e.clipboardData.files.length === 0) { + return; + } + + const files = Array.from(e.clipboardData.files); + const imageFiles = files.filter(f => f.type.startsWith('image')); + if (imageFiles.length === 0) { + return; + } + + e.preventDefault(); + await this.uploadMultipleFiles(imageFiles); + } + + private customDropEventListener = async (e: DragEvent) => { + if (!this.uploader) { + QiniuImageUploader.showUnconfiguredPluginNotice(); + return; + } + if (e.dataTransfer == null || e.dataTransfer.files.length === 0) { + return; + } + + const files = Array.from(e.dataTransfer.files); + const imageFiles = files.filter(f => f.type.startsWith('image')); + if (imageFiles.length === 0) { + return; + } + + e.preventDefault(); + await this.uploadMultipleFiles(imageFiles); + } + + private async uploadMultipleFiles(files: File[]) { + const editor = this.getEditor(); + if (!editor) { + new Notice('⚠️ Please open a file.'); + return; + } + + const pasteId = (Math.random() + 1).toString(36).substring(2, 7); + const progressText = `![Uploading ${files.length} images... ${pasteId}]()`; + const cursor = editor.getCursor(); + const startPos = cursor; + editor.replaceRange(`${progressText}\n`, cursor); + + try { + const schema = this.settings.https === 'Yes' ? 'https' : 'http'; + const baseTimestamp = Date.now(); + const imageUrls: string[] = []; + let successCount = 0; + + for (let i = 0; i < files.length; i++) { + const file = files[i]; + try { + const fileName = this.genFullFileName(file, i, baseTimestamp); + await this.uploader!.uploadFile(fileName, file); + const imageUrl = `${schema}://${this.settings.domain}/${fileName}`; + imageUrls.push(`![](${imageUrl})`); + successCount++; + } catch (error) { + console.error('Upload failed:', error); + imageUrls.push(`![Upload failed: ${file.name}]()`); + } + } + + const endPos = { + line: startPos.line, + ch: startPos.ch + progressText.length + 1 + }; + editor.replaceRange(imageUrls.join('\n') + '\n', startPos, endPos); + + if (successCount === files.length) { + new Notice(`✅ ${successCount} images uploaded`); + } else { + new Notice(`⚠️ ${successCount}/${files.length} uploaded`); + } + } catch (error) { + const endPos = { + line: startPos.line, + ch: startPos.ch + progressText.length + 1 + }; + editor.replaceRange('', startPos, endPos); + new Notice('❌ Upload failed'); + } + } + + private getEditor(): Editor | undefined { + return this.app.workspace.activeEditor?.editor; + } + + // ====== 修改:ob-时间戳-原始文件名 ====== + private genFullFileName(image: File, index: number, baseTimestamp: number): string { + const timestamp = baseTimestamp + index; + let fileName = `${this.settings.namePrefix}${timestamp}-${image.name}`; + + if (this.settings.folder) { + return `${this.settings.folder}/${fileName}`; + } + return fileName; + } + + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + + async saveSettings() { + await this.saveData(this.settings); + this.uploader = buildUploaderFrom(this.settings); + } + + private static showUnconfiguredPluginNotice() { + const fiveSecondsMillis = 5_000; + new Notice('⚠️ Please configure Qiniu Image Uploader or disable it', fiveSecondsMillis); + } +} \ No newline at end of file diff --git a/src/qiniu_sidebar.ts b/src/qiniu_sidebar.ts new file mode 100644 index 0000000..e3938ed --- /dev/null +++ b/src/qiniu_sidebar.ts @@ -0,0 +1,746 @@ +import { ItemView, setIcon, Notice, MarkdownView, Modal, App } from "obsidian"; +import { QiniuUploader } from "./uploader/qiniu"; + +const qiniu = require('qiniu'); +const VIEW_TYPE = "qiniu-sidebar"; + +// 图片预览模态框 +class ImageModal extends Modal { + file: any; + + constructor(app: App, file: any) { + super(app); + this.file = file; + } + + onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.addClass("image-preview-modal"); + + const imageContainer = contentEl.createDiv({ + cls: "image-preview-container", + }); + + imageContainer.createEl("h2", { + text: this.file.title || this.file.displayName || this.file.key, + cls: "image-preview-title", + }); + + const infoContainer = imageContainer.createDiv({ + cls: "image-preview-info", + }); + infoContainer.createEl("span", { + text: `大小: ${this.formatFileSize(this.file.size)}`, + cls: "image-info-item", + }); + + const img = imageContainer.createEl("img", { + cls: "image-preview-img", + attr: { src: this.file.url }, + }); + } + + formatFileSize(size: number): string { + if (size < 1024) { + return size + " B"; + } else if (size < 1024 * 1024) { + return (size / 1024).toFixed(2) + " KB"; + } else { + return (size / (1024 * 1024)).toFixed(2) + " MB"; + } + } + + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +} + +export class QiniuSidebar extends ItemView { + pageSize = 15; + currentPage = 1; + contentContainer: HTMLElement; + totalFiles = 0; // 总文件数 + + getViewType(): string { + return VIEW_TYPE; + } + + getDisplayText() { + return "七牛云管理"; + } + + getIcon(): string { + return "cloud-upload"; + } + + private getSettings() { + const app = this.app; + const plugins = (app as any).plugins; + const plugin = plugins?.plugins?.['qiniu-image-uploader']; + return plugin?.settings || null; + } + + async onOpen() { + const container = this.containerEl.children[1]; + container.empty(); + + const toolbar = container.createDiv({ cls: "qiniu-toolbar" }); + + const refreshBtn = toolbar.createEl("button", { cls: "qiniu-btn" }); + setIcon(refreshBtn, "rotate-ccw"); + refreshBtn.addEventListener("click", () => { + this.currentPage = 1; + this.loadFileList(this.contentContainer); + }); + + const uploadBtn = toolbar.createEl("button", { cls: "qiniu-btn qiniu-btn-primary" }); + setIcon(uploadBtn, "upload"); + uploadBtn.createSpan({ text: " 上传" }); + uploadBtn.addEventListener("click", () => { + this.uploadFile(this.contentContainer); + }); + + const pageSizeContainer = toolbar.createDiv({ cls: "qiniu-page-size" }); + pageSizeContainer.createEl("span", { text: "每页:", cls: "qiniu-label" }); + const pageSizeSelect = pageSizeContainer.createEl("select", { cls: "qiniu-select" }); + [10, 15, 20, 30, 50].forEach((size) => { + const option = pageSizeSelect.createEl("option", { + text: size.toString(), + value: size.toString(), + }); + if (size === this.pageSize) { + option.selected = true; + } + }); + pageSizeSelect.addEventListener("change", () => { + this.pageSize = parseInt(pageSizeSelect.value); + this.currentPage = 1; + this.loadFileList(this.contentContainer); + }); + + this.contentContainer = container.createDiv({ cls: "qiniu-file-list" }); + this.loadFileList(this.contentContainer); + } + + async loadFileList(container: Element) { + container.empty(); + + const settings = this.getSettings(); + if (!settings) { + container.createEl("p", { + text: "⚠️ 请先配置七牛云", + cls: "qiniu-empty", + }); + return; + } + + if (!settings.accessKey || !settings.accessSecretKey || !settings.bucketName) { + container.createEl("p", { + text: "⚠️ 请先配置七牛云", + cls: "qiniu-empty", + }); + return; + } + + try { + // 获取所有文件(整体排序) + const allFiles = await this.fetchAllFiles(settings); + + // 按 putTime 降序排序(最新的在前) + allFiles.sort((a, b) => { + return (b.putTime || 0) - (a.putTime || 0); + }); + + this.totalFiles = allFiles.length; + + if (this.totalFiles === 0) { + container.createEl("p", { + text: "📭 暂无文件", + cls: "qiniu-empty", + }); + return; + } + + // 显示文件总数 + const info = container.createEl("div", { + cls: "qiniu-file-count", + text: `共 ${this.totalFiles} 个文件`, + }); + + // 手动分页 + const start = (this.currentPage - 1) * this.pageSize; + const end = Math.min(start + this.pageSize, this.totalFiles); + const pageFiles = allFiles.slice(start, end); + + const list = container.createEl("ul", { cls: "qiniu-file-list-ul" }); + + for (const file of pageFiles) { + const item = list.createEl("li", { cls: "qiniu-file-item" }); + + const info = item.createDiv({ cls: "qiniu-file-info" }); + + if (file.mimeType && file.mimeType.startsWith("image/")) { + const preview = info.createDiv({ cls: "qiniu-file-preview" }); + const img = preview.createEl("img", { + cls: "qiniu-preview-img", + attr: { src: file.url }, + }); + img.addEventListener("click", (e) => { + e.stopPropagation(); + this.showImageModal(file); + }); + } + + const textInfo = info.createDiv({ cls: "qiniu-file-text" }); + const { displayName, timestamp } = this.extractFileInfo(file.key, settings); + textInfo.createEl("div", { text: displayName, cls: "qiniu-file-name" }); + const timeStr = this.formatTimeFromTimestamp(timestamp); + textInfo.createEl("div", { + text: `${timeStr} · ${this.formatFileSize(file.size)}`, + cls: "qiniu-file-meta" + }); + + const actions = item.createDiv({ cls: "qiniu-file-actions" }); + + const copyBtn = actions.createEl("button", { cls: "qiniu-action-btn" }); + setIcon(copyBtn, "link"); + copyBtn.setAttr("title", "复制 Markdown 图片代码"); + copyBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.copyToClipboard(file.url, displayName); + }); + + const insertBtn = actions.createEl("button", { cls: "qiniu-action-btn qiniu-insert-btn" }); + setIcon(insertBtn, "document"); + insertBtn.setAttr("title", "插入到编辑器"); + insertBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.insertToEditor(file.url, displayName); + }); + + const deleteBtn = actions.createEl("button", { cls: "qiniu-action-btn qiniu-delete-btn" }); + setIcon(deleteBtn, "trash"); + deleteBtn.setAttr("title", "删除"); + deleteBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.deleteFile(file.key, container); + }); + } + + // 分页控件 + const totalPages = Math.ceil(this.totalFiles / this.pageSize); + if (totalPages > 1) { + const pagination = container.createDiv({ cls: "qiniu-pagination" }); + + if (this.currentPage > 1) { + const prev = pagination.createEl("button", { text: "上一页", cls: "qiniu-page-btn" }); + prev.addEventListener("click", () => { + this.currentPage--; + this.loadFileList(container); + }); + } + + pagination.createEl("span", { + text: `第 ${this.currentPage} 页 / 共 ${totalPages} 页`, + cls: "qiniu-page-info", + }); + + if (this.currentPage < totalPages) { + const next = pagination.createEl("button", { text: "下一页", cls: "qiniu-page-btn" }); + next.addEventListener("click", () => { + this.currentPage++; + this.loadFileList(container); + }); + } + } + + } catch (error) { + console.error("❌ 加载文件列表失败:", error); + container.createEl("p", { + text: "❌ 加载失败: " + (error.message || "未知错误"), + cls: "qiniu-error", + }); + } + } + + // 获取所有文件 + async fetchAllFiles(settings: any): Promise { + const mac = new qiniu.auth.digest.Mac(settings.accessKey, settings.accessSecretKey); + const config = new qiniu.conf.Config({ + zone: this.getZone(settings.region), + }); + const bucketManager = new qiniu.rs.BucketManager(mac, config); + + return new Promise((resolve, reject) => { + let prefix = ''; + if (settings.folder) { + prefix = settings.folder + '/'; + } + prefix += settings.namePrefix; + + const allItems: any[] = []; + + const listAll = (marker?: string) => { + const options: any = { + limit: 1000, + prefix: prefix, + delimiter: '', + }; + if (marker) { + options.marker = marker; + } + + bucketManager.listPrefix(settings.bucketName, options, (err: any, respBody: any, respInfo: any) => { + if (err) { + reject(err); + return; + } + if (respInfo.statusCode !== 200) { + reject(new Error(`API错误: ${respInfo.statusCode}`)); + return; + } + + const items = respBody.items || []; + allItems.push(...items); + + const nextMarker = respBody.marker || ''; + if (nextMarker) { + listAll(nextMarker); + } else { + // 转换为文件对象 + const files = allItems.map((item: any) => { + const url = `${settings.https === 'Yes' ? 'https' : 'http'}://${settings.domain}/${item.key}`; + return { + key: item.key, + size: item.fsize || 0, + mimeType: item.mimeType || 'application/octet-stream', + url: url, + putTime: item.putTime, + hash: item.hash, + }; + }); + resolve(files); + } + }); + }; + + listAll(); + }); + } + + private extractFileInfo(key: string, settings: any): { displayName: string, timestamp: number } { + let name = key; + if (settings.folder) { + name = name.replace(settings.folder + '/', ''); + } + name = name.replace(settings.namePrefix, ''); + + const timestampMatch = name.match(/^(\d+)-/); + let timestamp = 0; + let displayName = name; + + if (timestampMatch) { + timestamp = parseInt(timestampMatch[1]); + displayName = name.replace(/^\d+-/, ''); + } + + return { displayName, timestamp }; + } + + private formatTimeFromTimestamp(timestamp: number): string { + if (!timestamp) return "未知时间"; + + const date = new Date(timestamp); + const now = new Date(); + const diff = (now.getTime() - date.getTime()) / 1000; + + if (date.getFullYear() < 2000 || isNaN(date.getTime())) { + return "未知时间"; + } + + if (diff < 60) { + return "刚刚"; + } else if (diff < 3600) { + return Math.floor(diff / 60) + "分钟前"; + } else if (diff < 86400) { + return Math.floor(diff / 3600) + "小时前"; + } else { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; + } + } + + private getZone(region: string): any { + const zoneMap: { [key: string]: any } = { + "as0": qiniu.zone.Zone_as0, + "cn_east_2": qiniu.zone.Zone_cn_east_2, + "na0": qiniu.zone.Zone_na0, + "z0": qiniu.zone.Zone_z0, + "z1": qiniu.zone.Zone_z1, + "z2": qiniu.zone.Zone_z2, + }; + return zoneMap[region] || qiniu.zone.Zone_z1; + } + + showImageModal(file: any) { + const modal = new ImageModal(this.app, file); + modal.open(); + } + + formatFileSize(size: number): string { + if (size < 1024) { + return size + " B"; + } else if (size < 1024 * 1024) { + return (size / 1024).toFixed(2) + " KB"; + } else { + return (size / (1024 * 1024)).toFixed(2) + " MB"; + } + } + + copyToClipboard(url: string, fileName: string) { + if (!url) { + new Notice("复制失败"); + return; + } + + const title = fileName.replace(/\.[^/.]+$/, ""); + const copyText = `![${title}](${url})`; + + const textarea = document.createElement("textarea"); + textarea.value = copyText; + textarea.style.position = "absolute"; + textarea.style.left = "-9999px"; + document.body.appendChild(textarea); + + textarea.select(); + document.execCommand("copy"); + document.body.removeChild(textarea); + + new Notice(`✅ 已复制 Markdown: ${title}`); + } + + private getActiveEditor(): any { + try { + const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView); + if (markdownView && markdownView.editor) { + return markdownView.editor; + } + + const activeLeaf = this.app.workspace.activeLeaf; + if (activeLeaf && activeLeaf.view instanceof MarkdownView) { + return activeLeaf.view.editor; + } + + const leaves = this.app.workspace.getLeavesOfType("markdown"); + + // 焦点在侧边栏时,前面两步必然拿不到(activeLeaf 已经不是编辑器了), + // 所以这里先按「当前活动文件」精确定位到对应的叶子。 + // 不这么做就会退化成「工作区第一个 markdown 叶子」, + // 把内容写进后台标签页里的另一篇笔记,而界面还提示插入成功。 + const activeFile = this.app.workspace.getActiveFile(); + if (activeFile) { + const matched = leaves.find( + (leaf) => + leaf.view instanceof MarkdownView && + leaf.view.file?.path === activeFile.path + ); + if (matched && (matched.view as MarkdownView).editor) { + return (matched.view as MarkdownView).editor; + } + } + + // 没有活动文件时才退回到原有的兜底逻辑 + for (const leaf of leaves) { + if (leaf.view instanceof MarkdownView) { + return leaf.view.editor; + } + } + + return null; + } catch (error) { + return null; + } + } + + async insertToEditor(url: string, fileName: string) { + try { + const activeFile = this.app.workspace.getActiveFile(); + if (!activeFile) { + new Notice("❌ 请先打开一个 Markdown 文件"); + return false; + } + + const editor = this.getActiveEditor(); + if (!editor) { + new Notice("❌ 无法获取编辑器"); + return false; + } + + const title = fileName.replace(/\.[^/.]+$/, ""); + const insertText = `![${title}](${url})`; + + const cursor = editor.getCursor(); + editor.replaceRange(insertText, cursor); + + new Notice(`✅ 已插入: ${title}`); + return true; + } catch (error) { + new Notice("❌ 插入失败"); + return false; + } + } + + async deleteFile(key: string, container: Element) { + if (!confirm(`确定要删除 "${key}" 吗?`)) { + return; + } + + try { + const settings = this.getSettings(); + if (!settings) { + new Notice("❌ 未配置七牛云"); + return; + } + const mac = new qiniu.auth.digest.Mac(settings.accessKey, settings.accessSecretKey); + const config = new qiniu.conf.Config({ + zone: this.getZone(settings.region), + }); + const bucketManager = new qiniu.rs.BucketManager(mac, config); + + bucketManager.delete(settings.bucketName, key, (err: any, respBody: any, respInfo: any) => { + if (err) { + new Notice("❌ 删除失败"); + return; + } + if (respInfo.statusCode !== 200) { + new Notice(`❌ 删除失败: ${respInfo.statusCode}`); + return; + } + new Notice(`✅ 已删除: ${key}`); + this.currentPage = 1; + this.loadFileList(container); + }); + } catch (error) { + new Notice("❌ 删除失败"); + } + } + + uploadFile(container: Element) { + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.multiple = true; + fileInput.style.display = "none"; + document.body.appendChild(fileInput); + + fileInput.addEventListener("change", async () => { + const files = Array.from(fileInput.files || []); + if (files.length === 0) { + document.body.removeChild(fileInput); + return; + } + + const progressPanel = this.createUploadProgressPanel(files.length); + document.body.appendChild(progressPanel.element); + + let isCancelled = false; + if (progressPanel.cancelButton) { + progressPanel.cancelButton.onclick = () => { + isCancelled = true; + progressPanel.updateStatus("已取消"); + setTimeout(() => progressPanel.hide(), 1000); + }; + } + + try { + const settings = this.getSettings(); + if (!settings) { + new Notice("❌ 未配置七牛云"); + return; + } + const uploader = new QiniuUploader(settings); + const baseTimestamp = Date.now(); + + for (let i = 0; i < files.length; i++) { + if (isCancelled) break; + + const file = files[i]; + const current = i + 1; + const total = files.length; + + progressPanel.updateFile(file.name); + progressPanel.updateStatus(`上传中 (${current}/${total})`); + progressPanel.setProgress(((current - 1) / total) * 100); + + try { + const timestamp = baseTimestamp + i; + let fileName = `${settings.namePrefix}${timestamp}-${file.name}`; + + if (settings.folder) { + fileName = `${settings.folder}/${fileName}`; + } + + await uploader.uploadFile(fileName, file); + progressPanel.setProgress((current / total) * 100); + + if (i < files.length - 1) { + await new Promise((resolve) => setTimeout(resolve, 300)); + } + } catch (err) { + console.error(`上传 ${file.name} 失败:`, err); + progressPanel.updateStatus(`⚠️ ${file.name} 失败`); + } + } + + if (isCancelled) { + progressPanel.updateStatus("已取消"); + } else { + progressPanel.updateStatus("✅ 全部完成!"); + progressPanel.setProgress(100); + await new Promise((resolve) => setTimeout(resolve, 1000)); + this.currentPage = 1; + this.loadFileList(container); + } + } catch (error) { + progressPanel.updateStatus("❌ 上传失败"); + } finally { + setTimeout(() => progressPanel.hide(), 2000); + document.body.removeChild(fileInput); + } + }); + + fileInput.click(); + } + + private createUploadProgressPanel(totalFiles: number) { + const panel = document.createElement("div"); + panel.className = "qiniu-upload-progress-panel"; + + if (!document.getElementById("qiniu-upload-progress-style")) { + const style = document.createElement("style"); + style.id = "qiniu-upload-progress-style"; + style.textContent = ` + .qiniu-upload-progress-panel { + position: fixed; + bottom: 20px; + right: 20px; + z-index: 9999; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 8px; + padding: 12px 16px; + min-width: 300px; + box-shadow: 0 4px 12px rgba(0,0,0,0.15); + font-size: var(--font-ui-smaller); + transition: opacity 0.3s, transform 0.3s; + } + .qiniu-upload-progress-panel.fade-out { + opacity: 0; + transform: translateY(20px); + } + .qiniu-upload-progress-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 8px; + } + .qiniu-upload-progress-title { + font-weight: 600; + color: var(--text-normal); + } + .qiniu-upload-progress-cancel { + background: none; + border: none; + color: var(--text-muted); + cursor: pointer; + font-size: 16px; + padding: 2px; + border-radius: 4px; + } + .qiniu-upload-progress-cancel:hover { + color: var(--text-accent); + } + .qiniu-upload-progress-filename { + color: var(--text-faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-bottom: 4px; + } + .qiniu-upload-progress-bar-container { + width: 100%; + height: 6px; + background: var(--background-modifier-border); + border-radius: 3px; + overflow: hidden; + margin: 6px 0; + } + .qiniu-upload-progress-bar { + height: 100%; + background: var(--interactive-accent); + border-radius: 3px; + width: 0%; + transition: width 0.3s ease; + } + .qiniu-upload-progress-status { + display: flex; + justify-content: space-between; + color: var(--text-muted); + } + `; + document.head.appendChild(style); + } + + panel.innerHTML = ` +
+ 📎 上传中 + +
+
-
+
+
+
+
+ 准备中... + 0% +
+ `; + + const filenameEl = panel.querySelector(".qiniu-upload-progress-filename") as HTMLElement; + const barEl = panel.querySelector(".qiniu-upload-progress-bar") as HTMLElement; + const statusEl = panel.querySelector(".status-text") as HTMLElement; + const percentEl = panel.querySelector(".progress-percent") as HTMLElement; + const cancelButton = panel.querySelector(".qiniu-upload-progress-cancel") as HTMLElement; + + return { + element: panel, + cancelButton, + updateFile(filename: string) { + filenameEl.textContent = filename; + }, + updateStatus(text: string) { + statusEl.textContent = text; + }, + setProgress(percent: number) { + const p = Math.max(0, Math.min(100, Math.round(percent))); + barEl.style.width = `${p}%`; + percentEl.textContent = `${p}%`; + }, + hide() { + panel.classList.add("fade-out"); + setTimeout(() => { + if (panel.parentNode) panel.parentNode.removeChild(panel); + }, 300); + }, + }; + } + + async onClose() { + // 清理 + } +} + +export { VIEW_TYPE }; \ No newline at end of file diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..8cca711 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,171 @@ +import { App, PluginSettingTab, Setting, Notice } from "obsidian"; +import QiniuImageUploader from "./main"; +import { t } from "./lang/helpers"; + +export interface PluginSettings { + accessKey: string; + accessSecretKey: string; + bucketName: string; + https: string; + domain: string; + namePrefix: string; + timeFormat: string; + region: string; + deleteSource: boolean; + folder: string; // 新增 +} + +export const DEFAULT_SETTINGS: PluginSettings = { + accessKey: "", + accessSecretKey: "", + bucketName: "", + https: "No", + domain: "", + namePrefix: "ob-", + timeFormat: "", + region: "z1", + deleteSource: false, + folder: "", // 新增,默认为空(根目录) +}; + +export class SettingTab extends PluginSettingTab { + plugin: QiniuImageUploader; + + constructor(app: App, plugin: QiniuImageUploader) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + + containerEl.empty(); + + new Setting(containerEl) + .setName(t("Access Key")) + .setDesc(t("Access Key Desc")) + .addText(text => text + .setPlaceholder(t("Access Key Input")) + .setValue(this.plugin.settings.accessKey) + .onChange(async (value) => { + this.plugin.settings.accessKey = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName(t("Access Secret Key")) + .setDesc(t("Access Secret Key Desc")) + .addText(text => text + .setPlaceholder(t("Access Secret Key Input")) + .setValue(this.plugin.settings.accessSecretKey) + .onChange(async (value) => { + this.plugin.settings.accessSecretKey = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName(t("Bucket Name")) + .setDesc(t("Bucket Name Desc")) + .addText(text => text + .setPlaceholder(t("Bucket Name Input")) + .setValue(this.plugin.settings.bucketName) + .onChange(async (value) => { + this.plugin.settings.bucketName = value; + await this.plugin.saveSettings(); + })); + + const regionMapping: { [key: string]: string } = { + "z1": t("North China - Hebei"), + "z0": t("East China - Zhejiang"), + "cn-east-2": t("East China - Zhejiang 2"), + "z2": t("South China - Guangdong"), + "na0": t("North America - Los Angeles"), + "as0": t("Asia Pacific - Singapore (formerly Southeast Asia)"), + }; + + new Setting(containerEl) + .setName(t("Region")) + .setDesc(t("Region Desc")) + .addDropdown(dropDown => dropDown + .addOption("z1", t("North China - Hebei")) + .addOption("z0", t("East China - Zhejiang")) + .addOption("cn-east-2", t("East China - Zhejiang 2")) + .addOption("z2", t("South China - Guangdong")) + .addOption("na0", t("North America - Los Angeles")) + .addOption("as0", t("Asia Pacific - Singapore (formerly Southeast Asia)")) + .setValue(this.plugin.settings.region) + .onChange(async (value) => { + this.plugin.settings.region = value; + await this.plugin.saveSettings(); + const fiveSecondsMillis = 5_000 + new Notice("修改地区为 " + regionMapping[value], fiveSecondsMillis) + }) + ); + + new Setting(containerEl) + .setName(t("HTTPS")) + .setDesc(t("HTTPS Desc")) + .addDropdown(dropDown => dropDown + .addOption("Yes", t("YES")) + .addOption("No", t("NO")) + .setValue(this.plugin.settings.https) + .onChange(async (value) => { + this.plugin.settings.https = value; + await this.plugin.saveSettings(); + const fiveSecondsMillis = 5_000; + if (value === "Yes") { + new Notice("修改为 HTTPS", fiveSecondsMillis) + } else { + new Notice("修改为 HTTP", fiveSecondsMillis) + } + }) + ); + + new Setting(containerEl) + .setName(t("Domain")) + .setDesc(t("Domain Desc")) + .addText(text => text + .setPlaceholder(t("Domain Input")) + .setValue(this.plugin.settings.domain) + .onChange(async (value) => { + this.plugin.settings.domain = value; + await this.plugin.saveSettings(); + })); + + // 新增:文件夹设置 + new Setting(containerEl) + .setName("文件夹") + .setDesc("上传到存储桶的指定文件夹,不填则传到根目录") + .addText(text => text + .setPlaceholder("例如: images/2024") + .setValue(this.plugin.settings.folder) + .onChange(async (value) => { + // 去除首尾空格和斜杠,统一格式 + const cleanFolder = value.trim().replace(/^\/+|\/+$/g, ''); + this.plugin.settings.folder = cleanFolder; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName(t("Name Prefix")) + .setDesc(t("Name Prefix Desc")) + .addText(text => text + .setPlaceholder(t("Name Prefix Input")) + .setValue(this.plugin.settings.namePrefix) + .onChange(async (value) => { + this.plugin.settings.namePrefix = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName(t("Time Format")) + .setDesc(t("Time Format Desc")) + .addText(text => text + .setPlaceholder(t("Time Format Input")) + .setValue(this.plugin.settings.timeFormat) + .onChange(async (value) => { + this.plugin.settings.timeFormat = value; + await this.plugin.saveSettings(); + })); + } +} \ No newline at end of file diff --git a/src/uploader/qiniu.ts b/src/uploader/qiniu.ts new file mode 100644 index 0000000..c9a7727 --- /dev/null +++ b/src/uploader/qiniu.ts @@ -0,0 +1,75 @@ +import { PluginSettings } from "../settings"; +import * as qiniu from 'qiniu'; +import { Uploader } from "./uploader"; + +const zoneMapping: { [key: string]: qiniu.conf.Zone } = { + "as0": qiniu.zone.Zone_as0, + "cn_east_2": qiniu.zone.Zone_cn_east_2, + "na0": qiniu.zone.Zone_na0, + "z0": qiniu.zone.Zone_z0, + "z1": qiniu.zone.Zone_z1, + "z2": qiniu.zone.Zone_z2, +} + +export class QiniuUploader implements Uploader { + settings: PluginSettings; + + lastToken: string; + tokenCreated: number; + tokenExpires: number; + + constructor(settings: PluginSettings) { + this.settings = settings; + + this.lastToken = ""; + this.tokenCreated = Date.now(); + this.tokenExpires = 7200; + } + + public async uploadFile(name: string, file: File): Promise { + var config = new qiniu.conf.Config({ + zone: zoneMapping[this.settings.region] + }); + + var formUploader = new qiniu.form_up.FormUploader(config); + var putExtra = new qiniu.form_up.PutExtra(); + + const uploadToken = await this.getToken(); + const content = await file.arrayBuffer(); + return new Promise((resolve, reject) => { + formUploader.put(uploadToken, name, Buffer.from(content), putExtra, function (respErr, + respBody, respInfo) { + if (respErr) { + reject(respErr); + return; + } + if (respInfo.statusCode != 200) { + reject({ Status: respInfo.statusCode, Body: respBody }); + return; + } + resolve(respBody); + }); + }); + } + + private async getToken(): Promise { + if (this.lastToken != '' && Date.now() - this.tokenCreated < this.tokenExpires * 0.9) { + return this.lastToken; + } + + var accessKey = this.settings.accessKey; + var secretKey = this.settings.accessSecretKey; + var mac = new qiniu.auth.digest.Mac(accessKey, secretKey); + + var options = { + scope: this.settings.bucketName, + expires: this.tokenExpires, + }; + var putPolicy = new qiniu.rs.PutPolicy(options); + var uploadToken = putPolicy.uploadToken(mac); + + this.tokenCreated = Date.now(); + this.lastToken = uploadToken; + return uploadToken; + } +} \ No newline at end of file diff --git a/src/uploader/uploader.ts b/src/uploader/uploader.ts new file mode 100644 index 0000000..c0641b3 --- /dev/null +++ b/src/uploader/uploader.ts @@ -0,0 +1,14 @@ +import { PluginSettings } from "../settings"; +import { QiniuUploader } from "./qiniu"; + +export interface Uploader { + uploadFile(name: string, file: File): Promise; +} + +export function buildUploaderFrom(settings: PluginSettings): Uploader | undefined { + if (settings.accessKey == "" || settings.accessSecretKey == "" || settings.bucketName == "" || settings.domain == "" || settings.region == "") { + console.log('Settings: ', settings); + return undefined + } + return new QiniuUploader(settings); +} \ No newline at end of file diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..f76c9d2 --- /dev/null +++ b/styles.css @@ -0,0 +1,217 @@ +/* + +This CSS file will be included with your plugin, and +available in the app when your plugin is enabled. + +If your plugin does not need CSS, delete this file. + +*/ + +/* ===== 七牛云边栏样式 ===== */ +.qiniu-sidebar-header { + padding: 12px 16px 8px 16px; + border-bottom: 1px solid var(--background-modifier-border); +} + +.qiniu-sidebar-header h3 { + margin: 0; + font-size: 16px; +} + +.qiniu-toolbar { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + flex-wrap: wrap; + border-bottom: 1px solid var(--background-modifier-border); +} + +.qiniu-btn { + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; + padding: 4px 10px; + font-size: 13px; + transition: all 0.2s; +} + +.qiniu-btn:hover { + background: var(--background-modifier-hover); +} + +.qiniu-btn-primary { + background: var(--interactive-accent); + color: var(--text-on-accent); + border-color: var(--interactive-accent); +} + +.qiniu-btn-primary:hover { + background: var(--interactive-accent-hover); +} + +.qiniu-page-size { + display: flex; + align-items: center; + gap: 4px; + margin-left: auto; +} + +.qiniu-label { + font-size: 12px; + color: var(--text-muted); +} + +.qiniu-select { + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + padding: 2px 6px; + font-size: 12px; +} + +.qiniu-file-list { + padding: 8px 12px; + overflow-y: auto; + flex: 1; +} + +.qiniu-empty, .qiniu-error { + color: var(--text-muted); + text-align: center; + padding: 30px 0; +} + +.qiniu-file-list-ul { + list-style: none; + margin: 0; + padding: 0; +} + +.qiniu-file-item { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 10px; + margin-bottom: 4px; + border-radius: 4px; + background: var(--background-secondary); + transition: background 0.2s; +} + +.qiniu-file-item:hover { + background: var(--background-modifier-hover); +} + +.qiniu-file-info { + display: flex; + align-items: center; + flex: 1; + min-width: 0; +} + +.qiniu-file-preview { + width: 32px; + height: 32px; + border-radius: 4px; + overflow: hidden; + flex-shrink: 0; + margin-right: 10px; + background: var(--background-modifier-border); +} + +.qiniu-preview-img { + width: 100%; + height: 100%; + object-fit: cover; + cursor: pointer; +} + +.qiniu-file-text { + min-width: 0; + flex: 1; +} + +.qiniu-file-name { + font-size: 13px; + color: var(--text-normal); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.qiniu-file-size { + font-size: 11px; + color: var(--text-muted); +} + +.qiniu-file-actions { + display: flex; + gap: 4px; + flex-shrink: 0; + margin-left: 8px; +} + +.qiniu-action-btn { + background: none; + border: none; + color: var(--text-muted); + cursor: pointer; + padding: 2px 6px; + border-radius: 4px; + transition: all 0.2s; +} + +.qiniu-action-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.qiniu-insert-btn:hover { + color: var(--interactive-accent); +} + +.qiniu-delete-btn:hover { + color: var(--text-error); +} + +.qiniu-pagination { + display: flex; + justify-content: center; + align-items: center; + gap: 12px; + padding: 12px 0 8px 0; + border-top: 1px solid var(--background-modifier-border); +} + +.qiniu-page-btn { + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + padding: 4px 12px; + font-size: 12px; + transition: all 0.2s; +} + +.qiniu-page-btn:hover { + background: var(--background-modifier-hover); +} + +.qiniu-page-info { + font-size: 12px; + color: var(--text-muted); +} +/* 文件元信息(时间 + 大小) */ +.qiniu-file-meta { + font-size: 11px; + color: var(--text-muted); + margin-top: 2px; +} \ No newline at end of file