Compare commits

...

68 Commits

Author SHA1 Message Date
Jiaxin Peng
90dcc1aef0 chore: release v2.8.0-beta.3 2025-12-10 23:15:18 +00:00
Jiaxin Peng
7053a74e24 feat: Add 'sync-preffix' translation key to multiple locales. 2025-12-10 23:05:07 +00:00
Jiaxin Peng
5144f10e77 feat: Add auto-copy Notion link setting 2025-12-10 23:04:58 +00:00
Jiaxin Peng
5806a2831b fix: remove unnecessary resetAutoSyncNoticeCache call when autoSyncFrontmatterKey changes 2025-12-10 22:51:08 +00:00
Jiaxin Peng
eeaf7c036d feat: Enable first-time auto-upload for new documents with autosync-database key and refine auto-sync notice logic. 2025-12-10 21:51:04 +00:00
Jiaxin Peng
3de92d3f54 feat: Enable first-time auto-upload for new documents and update documentation. 2025-12-10 21:32:25 +00:00
Jiaxin Peng
e6b13e5eee feat: auto copy after upload 2025-12-10 21:32:06 +00:00
Jiaxin Peng
f4def623bb styles: improve the translation 2025-12-10 21:30:49 +00:00
Jiaxin Peng
3620505b56 update beta version 2.8.0-beta.2 2025-11-06 16:51:42 +00:00
Jiaxin Peng
e9355aaf92 docs: enhance auto sync documentation with frontmatter key configuration and examples 2025-11-06 16:50:50 +00:00
Jiaxin Peng
943ec6af6d Merge pull request #68 from jxpeng98/autosync-filter
Autosync filter
2025-11-06 16:44:58 +00:00
Jiaxin Peng
bb4b75c82e feat: add auto sync frontmatter key configuration and update related messages 2025-11-06 16:43:24 +00:00
Jiaxin Peng
ae4488546c feat: add auto sync database list handling and notifications for missing entries 2025-11-06 16:27:24 +00:00
Jiaxin Peng
7661bc94c7 fix: update changelog to reflect version v2.8.0-beta.1 release 2025-11-01 00:44:35 +00:00
Jiaxin Peng
e8a9594ea1 fix: refine tag patterns for release triggers in workflow 2025-11-01 00:42:01 +00:00
Jiaxin Peng
bb211543f5 fix: remove branch trigger for prerelease workflow 2025-11-01 00:38:25 +00:00
Jiaxin Peng
c52f84232d Merge pull request #67 from jxpeng98/automate-sync
Automate sync
2025-11-01 00:35:52 +00:00
Jiaxin Peng
3730b7645a chore: update changelog with detailed auto sync feature description and improvements 2025-11-01 00:34:23 +00:00
Jiaxin Peng
e2a965e3d6 fix: update autoSyncTimeout type and ensure window context for setTimeout calls 2025-11-01 00:32:35 +00:00
Jiaxin Peng
2738498dc2 fix: clean up formatting in auto sync logic for better readability 2025-11-01 00:30:39 +00:00
Jiaxin Peng
6df5e21f3d feat: implement enhanced frontmatter change detection and caching for auto sync 2025-11-01 00:30:09 +00:00
Jiaxin Peng
d660a088e3 feat: add GitHub Actions workflow for prerelease builds and asset uploads 2025-10-31 23:44:53 +00:00
Jiaxin Peng
83d4f1e48c feat: enhance auto sync functionality to support multiple databases and improved user notifications 2025-10-31 23:36:57 +00:00
Jiaxin Peng
7c841f3db3 feat: update UI text to use internationalization configuration for modals and notices 2025-10-31 23:36:49 +00:00
Jiaxin Peng
fab3acdc21 feat: add auto sync messages and database management labels in English, Japanese, and Chinese locales 2025-10-31 23:35:28 +00:00
Jiaxin Peng
59fa32b5e5 docs: enhance auto sync documentation with detailed setup, scenarios, and troubleshooting guidance 2025-10-31 23:35:16 +00:00
Jiaxin Peng
e5f906bba2 feat: migrate settings for auto sync feature and add user notification 2025-10-31 21:57:21 +00:00
Jiaxin Peng
c369c291a7 feat: add auto sync functionality with configurable delay in settings 2025-10-31 21:42:48 +00:00
Jiaxin Peng
33f0848b32 docs: add changelog and roadmap links to English and Chinese index files 2025-10-31 21:21:50 +00:00
Jiaxin Peng
a33e63a219 docs: add changelog and roadmap files in English and Chinese 2025-10-31 17:00:26 +00:00
Jiaxin Peng
99a40375f5 docs: update documentation website link in README files 2025-10-31 14:27:39 +00:00
Jiaxin Peng
7282fc6955 chore: Switch to pnpm and create individual package for docs 2025-10-31 13:46:31 +00:00
Jiaxin Peng
770061e826 chore: remove unused image files from documentation 2025-10-31 11:14:43 +00:00
Jiaxin Peng
de7b7dd28d Merge pull request #65 from jxpeng98/docs
add doc website
2025-10-31 11:03:19 +00:00
Jiaxin Peng
1c6c3fb0d9 chore: add vitepress package 2025-10-31 10:57:37 +00:00
Jiaxin Peng
ca0935bfe8 docs: update README to reflect new features and improved database support 2025-10-31 10:56:47 +00:00
Jiaxin Peng
e944721415 docs: add documentation for Obsidian to NotionNext plugin setup and usage 2025-10-31 10:47:34 +00:00
Jiaxin Peng
db66ef137c Update version to 2.7.0 2025-10-27 23:21:30 +00:00
Jiaxin Peng
a152201510 Merge pull request #64 from jxpeng98/callout-support
feat: callout support
2025-10-27 23:20:27 +00:00
Jiaxin Peng
abb699fe4d docs: add support for converting Obsidian callouts to Notion callout blocks 2025-10-27 23:17:55 +00:00
Jiaxin Peng
cf6c80df0f update yarn.lock 2025-10-27 23:14:43 +00:00
Jiaxin Peng
cf884de554 refactor: remove redundant debug logs from upload commands and base class 2025-10-27 23:12:25 +00:00
Jiaxin Peng
8eb4694342 refactor: removing redundant debug logs 2025-10-27 22:57:28 +00:00
Jiaxin Peng
6c0f6cea30 feat: enhance logging and error handling in upload commands and base class 2025-10-27 22:34:46 +00:00
Jiaxin Peng
8af4816f87 chore: update martian dependency version to 1.3.1 2025-10-27 20:44:23 +00:00
Jiaxin Peng
f6d24daa52 chore: bump martian dependency version to 1.3.0 2025-10-27 13:40:42 +00:00
Jiaxin Peng
da72846903 Update version to 2.6.0 2025-10-06 23:25:29 +01:00
Jiaxin Peng
8e08c4325d Update version to 2.6.0 2025-10-06 23:22:00 +01:00
Jiaxin Peng
ebb7a290e8 Merge pull request #61 from jxpeng98/unify-upload-functions
unify three databases with single upload file
2025-10-06 23:19:55 +01:00
Jiaxin Peng
24e68fc798 unify three databases with single upload file 2025-10-06 23:18:01 +01:00
Jiaxin Peng
78d2a29c8a Update README.md img links 2025-07-20 12:19:10 +01:00
Jiaxin Peng
1156bd3809 Merge pull request #58 from jxpeng98/notion-relation
update img links
2025-07-20 12:17:56 +01:00
Jiaxin Peng
b46e24f1ed update img links 2025-07-20 12:16:10 +01:00
Jiaxin Peng
a950e2e301 Update version to 2.5.0 2024-11-20 22:19:38 +00:00
Jiaxin Peng
aac7bc154a feat: consistent sync function (requestUrl) for desktop and mobile 2024-11-20 22:19:03 +00:00
Jiaxin Peng
a573ef728d chore: remove node-fetch and change the platform back to browser. 2024-11-20 22:17:49 +00:00
Jiaxin Peng
1344c14933 Update version to 2.4.3 2024-10-22 10:29:09 +01:00
Jiaxin Peng
c1f4ecd14b Update version to 2.4.3 2024-10-22 10:27:49 +01:00
Jiaxin Peng
5942876c92 fix: cannot parse title from front matter 2024-10-22 10:27:33 +01:00
Jiaxin Peng
3218eb9fba Update version to 2.4.2 2024-09-19 13:50:51 +01:00
Jiaxin Peng
48566eca20 Merge pull request #37 from jxpeng98/pluggin-does-not-appear-on-mac
fix: obsidian language not set in English, Chinese and Japanese
2024-09-19 13:49:08 +01:00
Jiaxin Peng
8bd8346423 fix: obsidian language not set in English, Chinese and Japanese 2024-09-19 13:47:57 +01:00
Jiaxin Peng
00411e9599 Merge pull request #35 from jxpeng98/mobile-fail-to-start
feat: separate mobile sync from desktop version
2024-09-03 12:19:23 +01:00
Jiaxin Peng
296125f6b4 chore: remove process from dependencies 2024-09-03 12:15:36 +01:00
Jiaxin Peng
1b385ccd0a solve: the fail to load of mobile caused by the node version 2024-09-01 23:26:22 +01:00
Jiaxin Peng
a90e4871bb Backup mobile requesturl after version 2.4.1 2024-09-01 22:57:03 +01:00
Jiaxin Peng
885ccba027 fix: test the desktop function for next and general 2024-08-31 23:43:19 +01:00
Jiaxin Peng
f282dde1b7 fix: test the desktop function of custom database
with platform function
2024-08-31 00:00:09 +01:00
64 changed files with 7184 additions and 3736 deletions

111
.github/workflows/prerelease.yml vendored Normal file
View File

@@ -0,0 +1,111 @@
name: Prerelease
on:
push:
tags:
- "*-beta*"
- "*-rc*"
- "*-alpha*"
- "*-test*"
env:
PLUGIN_NAME: share-to-notionnext
CHANGELOG_FILENAME: CHANGELOG.md
jobs:
build:
name: prerelease
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- name: Build
id: build
run: |
npm install
npm run build
mkdir ${{ env.PLUGIN_NAME }}
cp main.js manifest.json ${{ env.PLUGIN_NAME }}
zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }}
ls
echo "tag_name=$(git tag --sort version:refname | tail -n 1)" >> $GITHUB_OUTPUT
- name: Create Prerelease
id: create_prerelease
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
VERSION: ${{ github.ref }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }} (Prerelease)
body: |
## ⚠️ Prerelease Version - For Testing Only
This is a prerelease version intended for testing purposes.
**Important Notes:**
- This version may contain bugs or experimental features
- Not recommended for production use
- Please report any issues you encounter
### Installation
**Method 1: Using BRAT (Recommended)**
1. Install [BRAT](https://github.com/TfTHacker/obsidian42-brat) plugin if you haven't already
2. Open BRAT settings
3. Click "Add Beta plugin"
4. Enter: `jxpeng98/obsidian-to-NotionNext`
5. Enable "Share to NotionNext" in Community Plugins
**Method 2: Manual Installation**
1. Download the `${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip` file
2. Extract it to your `.obsidian/plugins/` folder
3. Reload Obsidian
### Changelog
See [CHANGELOG.md](${{ env.CHANGELOG_FILENAME }}) for details.
---
**Feedback:** Please report issues in the [GitHub Issues](https://github.com/${{ github.repository }}/issues) section.
draft: false
prerelease: true
- name: Upload zip file
id: upload-zip
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./${{ env.PLUGIN_NAME }}.zip
asset_name: ${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip
asset_content_type: application/zip
- name: Upload main.js
id: upload-main
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./main.js
asset_name: main.js
asset_content_type: text/javascript
- name: Upload manifest.json
id: upload-manifest
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./manifest.json
asset_name: manifest.json
asset_content_type: application/json

View File

@@ -2,8 +2,11 @@ name: Release
on:
push:
branches:
- main
tags:
- "*"
- "v*.*.*"
- "[0-9]+.[0-9]+.[0-9]+"
env:
PLUGIN_NAME: share-to-notionnext # Change this to match the id of your plugin.

7
.gitignore vendored
View File

@@ -21,3 +21,10 @@ data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
.history
# local data
local-data
# vitepress
docs/.vitepress/dist
docs/.vitepress/cache

View File

@@ -1,4 +1,53 @@
## Fix
# Changelog
- Fix code block not being highlighted in Notion after syncing.
- 修复代码块同步之后,在 Notion 中未高亮的问题。
## v2.8.0-beta.3 (2025-12-10)
### Added
- **Auto-copy Notion Link setting**: New toggle to automatically copy the Notion page link to clipboard after syncing (defaults to on)
- **Smart auto-sync notice**: Show notice only for files that were previously synced but missing `autosync-database` field; new files are silently skipped
### Fixed
- Fixed `undefined` appearing in sync success notification by adding missing `sync-preffix` i18n key
- Fixed build error caused by removed `resetAutoSyncNoticeCache()` method reference
- Added `autoCopyNotionLink` to settings migration logic for seamless upgrades
### Changed
- Improved auto-sync behavior: files without `autosync-database` are now silently ignored unless they have an existing NotionID
- Updated documentation with new auto-sync scenarios (A-1 and A-2)
---
## v2.8.0-beta.2 (2025-11-05)
### Featured
- Added setting to customise the frontmatter key used for auto sync database lists (defaults to `autosync-database`)
## v2.8.0-beta.1 (2025-10-31)
### Added
- **Auto Sync Feature**: Automatically sync notes to Notion when content or frontmatter changes
- Configurable delay (default: 5 seconds, minimum: 2 seconds)
- Support for multiple database syncing
- Smart detection to avoid sync loops when only NotionID is updated
- Content hash comparison to detect body text changes
- Works on both desktop and mobile platforms
- Added comprehensive i18n support for all UI elements and notifications
- Added prerelease workflow for beta testing via GitHub Actions and BRAT
- Added setting to customise the frontmatter key used for auto sync database lists (defaults to `autosync-database`)
### Changed
- Enhanced settings tab with auto-sync configuration options
- Improved debug logging for better troubleshooting
- Updated documentation with auto-sync usage guide and troubleshooting section
### Fixed
- Fixed mobile compatibility issues by using `window.setTimeout` instead of `NodeJS.Timeout`
- Fixed sync loop prevention logic to properly handle frontmatter and content changes
- Fixed cache update timing to ensure accurate change detection

View File

@@ -1,307 +1,20 @@
# Obsidian share to NotionNext
# Obsidian to NotionNext
感谢[原作者](https://github.com/EasyChris/obsidian-to-notion)开发出了这么好用的插件能够将obsidian同步到notion。 但是原仓库只能同步Name和Tags信息如果像我一样通过[NotionNext](https://github.com/tangly1024/NotionNext)来搭建自己的网页,就有一些局限性。每次导入之后都需要进行大量的修改。
[![Test](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml)
[![Release](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml)
[![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22share-to-notionnext%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json)](https://GitHub.com/jxpeng98/obsidian-to-NotionNext/releases/)
[![GitHub release (with filter)](https://img.shields.io/github/package-json/v/jxpeng98/obsidian-to-NotionNext)](https://github.com/jxpeng98/obsidian-to-NotionNext/releases/)
所以我在[原作者](https://github.com/EasyChris/obsidian-to-notion)的基础之上,增加了匹配[NotionNext](https://github.com/tangly1024/NotionNext)模板的功能。这样可以直接在Obsidian编辑整理好之后一键发布
使用 Notion API 将文件从 Obsidian 分享到任何 Notion 数据库。此插件支持通用 Notion 数据库、NotionNext 博客模板和完全自定义的数据库模式
## 更新说明
### 1.1.2
- 修复了一个拼写错误,导致无法同步`status`到NotionNext。现在你可以使用`stats`或者`status`来同步文章的状态到NotionNext。这个更新不会影响到同步到General数据库的功能。
- **`stats``status`都可以使用,但是你只能使用其中一个。**
**详细说明请访问[文档网站](https://obsidian-to-notionnext.pages.dev/)。**
```yaml
stats: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
# or
status: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
# both of them will work, but you can only use one of them.
```
## 功能特性
### 1.1.1
- 修复了在日语系统下,无法显示设置按钮的错误
- 增加日语翻译
### 1.1.0
- 修复设置中自定义标题的显示问题。
- 增加了标签同步的控制按钮。以减少空标签集造成的上传失败。
- **多种数据库类型**支持通用、NotionNext 和自定义数据库。
- **自定义属性**:在自定义数据库中,可将任何 frontmatter 键映射到任何 Notion 属性
- **灵活同步**:即时选择要同步到哪个数据库
如果你不想使用同步标签功能你可以在设置中关闭。不论你在md文件表头添加了tags与否都不会将标签同步到Notion数据库中。
## 致谢
如果你需要同步标签到Notion数据库中**你需要通过如下格式添加表填到md表头中。**
```yaml
tags: #空标签选项1
tags: [test,test1,test2] # 用中括号将所有的标签括起来选项2
tags:
- test
- test1
- test2 # 每个标签单独一行选项3
```
### 1.0.1
- 修复了自定义标题在设置菜单中显示错误的问题。
### 1.0.0 (大更新)
- 这个版本开始,你可以**任意修改第一列表头的名字 (标题列,默认:'title')**。 **注意你必须保证你的Notion数据库中有'tags这一列的存在并且在markdown文件中把`tags:`添加到你的YAML表头中。否则会返回`400 错误`。但是你可以`tags:`设置为空。**
![](https://minioapi.pjx.ac.cn/img1/2023/11/4a298b9be3990e9d2201bf2f50ca5a0a.png)
例如这样:
![](https://minioapi.pjx.ac.cn/img1/2023/11/4cd8d79cd9dd9dde299e39c666cb3473.gif)
- 增加了一个控制按钮来控制是否开启当前数据库同步命令的功能。如果你关闭了这个按钮,你在上传命令列表中就不会出现当前数据库的选项。
![](https://minioapi.pjx.ac.cn/img1/2023/11/becb60fc44783842da4b3cf4c322f363.gif)
### 0.2.6
- 增加一个按钮用来控制是否在名列列表中显示如下数据库。
![](https://minioapi.pjx.ac.cn/img1/2023/11/147c6a4eaa34da41a6f102558ed77106.png)
如果你关闭普通数据库的按钮你在上传命令列表中就不会出现普通数据库的选项。如果你关闭NotionNext数据库的按钮你在上传命令列表中就不会出现NotionNext数据库的选项。
![](https://minioapi.pjx.ac.cn/img1/2023/11/70b8e4fc2148688ccbd6cfc53ce339a2.png)
### 0.2.3
- 修复了一个bug现在可以正常更新了。
### 0.2.2
- 支持NotionNext 和 普通Notion 数据库的同步。
- 你可以有一个NotionNext和一个普通Notion数据库。
- 普通Notion数据库的同步方式和原作者的一样只同步`title``tags`。**如果使用普通数据库功能,你需要保证你的数据库中有`title``tags`这两个表头。必须使用小写。**
![](https://minioapi.pjx.ac.cn/img1/2023/11/712a12081d855aa60f82a7b46913ab7e.gif)
![](https://minioapi.pjx.ac.cn/img1/2023/11/9de76cecceef74c78884ddfc1c221659.gif)
### 0.2.1
- 重构代码。
### 0.2.0
- 从这个版本开始,重构了交互逻辑。现在当你点击左侧的按钮,会弹出可同步的数据库选项。你可以选择你想要同步的数据库,然后点击同步按钮。**但是现在仅支持同步单个数据库如果你的数据库不是NotionNext你可以不用更新。**
### 0.1.10
- 修正了设置中的中文显示。
### 0.1.8
- 重新整理了代码,增加了一个仓库转换按钮为之后的多数据库支持作准备。**但是现在还不支持多数据库如果你的数据库不是NotionNext你可以不用更新。**
### 0.1.7
- [x] 删除了设置中`convert tags`的选项。 你现在可以直接添加tags而不需要考虑是否开启tags选项。如果你不需要tags可以直接删除tags选项或者留白。
## 使用方式
### 注意事项
本插件现在暂时只能用于匹配[NotionNext](https://github.com/tangly1024/NotionNext)。如果你不是使用这个模板,你只会无限返回`error 400`.
所以没有NotionNext需求的请使用原作者的[Obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion)
### 准备安装
在安装插件之前,你必须配置好了以下内容:
1. 你的NotionNext数据库。
2. 根据原作者的readme.md配置好了Notion API并且已经和你的NotionNext仓库关联。
3. NotionNext Database ID
4. 你的NotionNext数据库有如下内容
- type
- title
- slug
- category
- tags
- date
- status
- summary
- password
- icon
在最新的0.0.6版本,我还增加了以下内容:
- titleicon 标题的emoji图标,暂时只能支持emoji
- coverurl 封面图片的url url可以是任何一种图片的url 例如jpgpngsvg等等。
**如果你是直接复制的NotionNext的模板这些内容应该已经有了。我在原作者的基础之上对本插件的内容进行了更改所以你只需要保证你的数据库有如上内容并且所有的字母都是小写**
**⚠️⚠️⚠️:表头全部小写!!!顺序无所谓!**
### 安装插件
#### 社区插件市场下载
打开`Obsidian -> 设置 -> 社区插件 -> 浏览 -> 搜索Share to NotionNext`, 然后点击安装。
#### 手动安装
1. 关闭Obsidian
2. 从Release下载插件文件解压到你的obsidian插件目录下。
3. 重新打开Obsidian进入设置启用插件。
4. 在设置中找到Obsidian to NotionNext填入你的NotionNext Database ID 和 API token。
### 使用插件
在仓库中我上传了一个模板你可以直接复制到你的模板文件夹中。然后使用Obsidian的模板功能一键生成新笔记。
如果你不想使用模板你也可以直接在Obsidian中创建一个新的文件然后复制下边的内容。然后保存。
```markdown
---
# default value has been set.
# for any unwanted value, you can delete it or set it to empty.
# for example, if you donot want to set password, you can delete password: "1234" or set it to password: ""
# 我已经在插件中设置了默认值,如果有不需要的选项,可以直接删除。
# 例如你不需要密码选项你可以将password: "1234"删除,或者将它设置为空。
# !!!!!!!!!!!!
# 现在阶段一定不要修改表头的名字, please do not change the name of the header in YAML front matter
# !!!!!!!!!!!!
titleicon: 📎 # emoji icon, default is 📜, 默认是📜
date: 2023-07-23 # default is today 默认是今天。 Format is YYYY-MM-DD 格式是YYYY-MM-DD
coverurl: https://img.jxpeng.dev/2023/08/843e27a210847f05a0f7cfb121fec100.jpg # default is empty 默认是空
type: Post # Post or Page, default is Post 默认是Post
slug: test # slug for url, default is empty 默认是空
stats: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
category: test # default is 'Obsidian' 默认是'Obsidian'
summary: this is a summary for test post # default is empty 默认是空
icon: fa-solid fa-camera # you can ignore this, default is empty 默认是空,可直接删除
password: "1234" # if you donot want to set password, you can delete this line, default is empty 默认是空,可直接删除
# 现在必须开启tags选项否则会报错
tags:
- test # tags for post
- web # add more tags if you want
---
Contents Below
```
模板使用如下:
![](https://minioapi.pjx.ac.cn/img1/2023/09/354b950e5777b48832c2475e4a31f2cc.gif)
**插件预览如下**
![](https://minioapi.pjx.ac.cn/img1/2023/09/d6199619b68fab218fca8ae0cebece78.gif)
---
**以下为原README.md**
非常感谢原作者的开发,我只是在原作者的基础之上进行了修改,增加了一些功能。如果你觉得这个插件对你有帮助,可以给[原作者](https://github.com/EasyChris/obsidian-to-notion)一个star。
# Obsidian to Notion
[![](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml)
[![Release Obsidian plugin](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml)
[![GitHub license](https://camo.githubusercontent.com/400c4e52df43f6a0ab8a89b74b1a78d1a64da56a7848b9110c9d2991bb7c3105/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d47504c76332d626c75652e737667)](https://raw.githubusercontent.com/EasyChris/obsidian-to-notion/master/LICENSE)
[![Github all releases](https://img.shields.io/github/downloads/Easychris/obsidian-to-notion/total.svg)](https://GitHub.com/Easychris/obsidian-to-notion/releases/)
[![GitLab latest release](https://badgen.net/github/release/Easychris/obsidian-to-notion/)](https://github.com/Easychris/obsidian-to-notion/releases)
Obsidian share to Notion [English](README.md)
将obsidian文件一键分享到Notion,并在obsidian中添加Notion分享链接
如果能对你有所帮助欢迎给一个star支持。
![](./doc/1.gif)
# 使用方式
## 安装插件
### 市场下载
插件市场搜索 noiton 即可下载
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220628214145.png)
### BRAT
插件中中心搜索 BRAT
添加 `EasyChris/obsidian-to-notion` 到 BRAT 插件安装列表中
返回插件中心启用即可
### 手动安装
```
cd YOUR_OBSIDIAN_FOLDER/.obsidian/plugins/
git clone https://github.com/EasyChris/obsidian-to-notion.git
```
## 申请 Notion API
官方参考文档:[https://developers.notion.com/docs](https://developers.notion.com/docs)
### 第 1 步创建integration
转到 [https://www.notion.com/my-integrations](https://www.notion.com/my-integrations)
创建完成之后,复制`secrets toekn`
![](https://files.readme.io/2ec137d-093ad49-create-integration.gif)
### 第2步与你的集成共享一个数据库
新建一个的page权限为公开
在page中新建一个数据库 -> 需要`full page database`
![](./doc/3.gif)
`integration`添加到你的新建的数据库中
![](./doc/6.gif)
#### 注意
数据库的第一个自定义名称必须是 "Name",否则同步会失败。
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220618102029.png)
### 第三步复制database ID
```
https://www.notion.so/myworkspace/a8aec43384f447ed84390e8e42c2e089?v=...
|--------- Database ID --------|
```
## 打开插件配置
将得到的 `NOTION_API_KEY``DATABASE_ID`填入配置当中
![](./doc/2.png)
## 上传文件内容到notion
点击上传notion的按钮
![](./doc/4.png)
上传成功之后会自动生成一个分享链接
![](./doc/5.png)
## 页面 Banner 链接[可选]
默认可以不填写
横幅URL必须是图像URL例如https//i.imgur.com/xxx.jpg
## Notion ID [可选]
Notion ID是你想分享文件的页面ID。
如果你不写它notion将分享到默认的链接<https://www.notion.so/myworkspace/a8aec43384f447ed84390访问这个页面将重定向到你的网站页面>
如果你写了Notion ID它将分享到页面链接如<https://your_user_name.notion.site/myworkspace/a8aec43384f447ed84390不需要重定向网址>
## 同步图片
使用 [Obsidian Image Auto Upload Plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin) 插件,配置你自己的 cos 或者 oss将图片存储到你自己的云存储然后在 obsidian 中使用图片链接即可。该插件会自动帮你上传图片,并替换成链接。
# 请我喝杯咖啡
[顿顿饭](https://dun.mianbaoduo.com/@easy)
# 感谢
[开发流程 | Obsidian 插件开发文档](https://luhaifeng666.github.io/obsidian-plugin-docs-zh/zh/getting-started/development-workflow.html)
[GitHub - devbean/obsidian-wordpress: An obsidian plugin for publishing docs to WordPress.](https://github.com/devbean/obsidian-wordpress)
[GitHub - obsidianmd/obsidian-api](https://github.com/obsidianmd/obsidian-api)
[GitHub - zhaohongxuan/obsidian-weread-plugin: Obsidian Weread Plugin is an plugin to sync Weread(微信读书) hightlights and annotations into your Obsidian Vault.](https://github.com/zhaohongxuan/obsidian-weread-plugin)
此插件是 EasyChris 的原创作品 [obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion) 的一个分支,增加了新功能并支持更灵活的数据库配置。

448
README.md
View File

@@ -5,449 +5,17 @@
[![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22share-to-notionnext%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json)](https://GitHub.com/jxpeng98/obsidian-to-NotionNext/releases/)
[![GitHub release (with filter)](https://img.shields.io/github/package-json/v/jxpeng98/obsidian-to-NotionNext)](https://github.com/jxpeng98/obsidian-to-NotionNext/releases/)
[//]: # ([![Github all releases]&#40;https://img.shields.io/github/downloads/jxpeng98/obsidian-to-NotionNext/total.svg&#41;]&#40;https://GitHub.com/jxpeng98/obsidian-to-NotionNext/releases/&#41;)
[中文版](README-zh.md)
Share files from Obsidian to any Notion database using the Notion API. This plugin supports general Notion databases, NotionNext blog templates, and fully custom database schemas.
[//]: # ([中文文档]&#40;README-zh.md&#41;)
**For detailed instructions, please visit the [documentation website](https://obsidian-to-notionnext.pages.dev/).**
**Now, support All Notion databases, including NotionNext and General Notion databases, and customise the database list.**
## Features
**现在支持所有Notion数据库包括NotionNext和一般Notion数据库以及自定义数据库列表。**
## Precautions
### For customised database users before version 2.3.0
**⚠️⚠️⚠️: The existing customised database should be recreated if you want to update to version 2.3.0. The new version has a new database structure, and the old database structure is not compatible with the new version to build the index properly.**
### 在2.3.0版本之前的自定义数据库用户
**⚠️⚠️⚠️: 如果你想要更新到2.3.0版本,你需要重新创建自定义数据库。新版本有一个新的数据库结构,旧的数据库结构无法构建索引。**
## TODO List
- [x] Modify the Edit function for the custom properties. 改进自定义属性的编辑功能
- [x] Support sync with long notes (From `v2.4.0`). 从`v2.4.0`开始支持长笔记同步
- [x] Support custom properties for Notion General database. 支持自定义属性
- [x] Support preview for database details in plugin settings. 支持预览数据库详情
- [x] Support edit for database details in plugin settings. 支持编辑数据库详情
- [ ] Support group upload with one click 支持一键多数据库上传
## How to use
If you want to use this plugin, you need to follow the following steps to set up the plugin. The steps can be divided into two parts: setting up the Notion API and setting up the plugin in Obsidian.
### 1. Setting up the Notion API
1). Go to [Notion API](https://www.notion.com/my-integrations) to create a new integration, and **copy the token**.
![create-api](https://minioapi.pjx.ac.cn/img1/2024/07/28526e416571f8b1fe70d90bd9975b81.gif)
2). Create a database in your Notion workspace.
Open Notion, click top-left `Create` a new page` -> You can give a title for the page and press "/" Select 'Database - Full page'.
![create-database](https://minioapi.pjx.ac.cn/img1/2024/07/f1bd993ed667bcc980a45194eb647c34.gif)
Rename the database properties to `title` and `tags`.
**⚠️⚠️`title` is the title column! `tags` is lower case⚠**
![rename-title-tags](https://minioapi.pjx.ac.cn/img1/2024/07/20c7b81761195706dde6e7dae69edbc4.gif)
3). Add the Notion API integration.
Click the right-top '...' -> connections -> connect to -> find the integration you created and connect it.
![add-integration](https://minioapi.pjx.ac.cn/img1/2024/07/bf59397146d96727c96dac06515c6c22.gif)
4). Publish the database to the public.
Click the 'Share' -> 'Publish' -> 'Publish' -> **copy the database id from the URL**.
![share-publish](https://minioapi.pjx.ac.cn/img1/2024/07/5e5b9585cfa4a9086ef6704c3b48eacf.gif)
### 2. Setting up the plugin in Obsidian
1). Go to Obsidian settings -> community plugins -> search 'NotionNext' -> install it.
![plugin](https://minioapi.pjx.ac.cn/img1/2024/07/1bf82618e943ec5eb68d89d4556bc3fc.png)
2). Open the plugin settings and create a new database.
![add-database](https://minioapi.pjx.ac.cn/img1/2024/07/115f47b4180d04fb362b931f8092b5fb.png)
### 3. Create a database
**You can create three types of databases:**
#### 1⃣ General database
General database is the default database, which only has the `title` and `tags` columns. **⚠️⚠️`title` and `tags` are lowercase⚠**
![general](https://minioapi.pjx.ac.cn/img1/2024/07/b2d0d0259afae7a542bd9f62256cd2c2.png)
The general is as follows:
- Full Name: the full name that you would like to give to the database.
- Abbreviate Name: the abbreviation that you would like to give to the database.
- Notion tags sync: whether you want to sync the tags column to Notion.
- Customise title property: whether you want to change the `title` to another name (e.g., `name`).
- Notion API token: the token you copied from the Notion API page.
- Notion Database ID: the database ID you copied from the Notion database URL. (e.g., only copy `7158cd3f70ce4f60afd9da5bdf74fd0c` between `site/` and `?`. `https://jxpeng.notion.site/7158cd3f70ce4f60afd9da5bdf74fd0c?v=380317ac5373sadasdas3c13e618f&pvs=4**`)
After setting, it should look like this:
![general-setting](https://minioapi.pjx.ac.cn/img1/2024/07/3fc630171f6e8ae1011271b2b37d5d48.png)
Once you click `save`, the new database will be created in the plugin settings and display in the detabase list.
![database-list](https://minioapi.pjx.ac.cn/img1/2024/07/3dff23b1c13a31f7696dc794fb78eba5.png)
#### 2⃣ NotionNext database
If you use [NotionNext](https://github.com/tangly1024/NotionNext) to set up your website, you can use the NotionNext database. (**All the properties are in lowercase, and you do not need to change the properties**)
![notionnext](https://minioapi.pjx.ac.cn/img1/2024/07/b164160ccfaf4fb23aa7ac1ce467e235.png)
Like the general database, you need to fill in the following information:
- Full Name: the full name that you would like to give to the database.
- Abbreviate Name: the abbreviation that you would like to give to the database.
- Notion API token: the token you copied from the Notion API page.
- Notion Database ID: the database ID you copied from the Notion database URL.
#### 3⃣ Custom database
The custom database is purely customised, and you can customise the properties you want to sync. (**All the properties are in lowercase, and you do not need to change the properties**)
![customise](https://minioapi.pjx.ac.cn/img1/2024/07/612b1377ec94d452abec7dc3fbe6cefb.png)
The basic information is identical to the general database and NotionNext database. You need to fill in the following information:
- Full Name: the full name that you would like to give to the database.
- Abbreviate Name: the abbreviation that you would like to give to the database.
- Notion API token: the token you copied from the Notion API page.
- Notion Database ID: the database ID you copied from the Notion database URL.
After adding the information, You can click `Add New Property` to add the properties you want to sync. There is no limit to the number of properties you can add.
![customise-add-property](https://minioapi.pjx.ac.cn/img1/2024/07/17cfbfa93d92404ff70d920302f15981.png)
**⚠️⚠️⚠️**: **`Title column` is the main property in the Notion database, which has the open button to open the underlying page.** You can select the type of all other properties. **⚠️⚠️⚠️**
![title-column](https://minioapi.pjx.ac.cn/img1/2024/07/0521b0aa6cedbe67bca4966bf79041ea.png)
According to the previously shown database, you can use `title` as the `Title column`, and `Tags` as the property 1.
![title-and-tags](https://minioapi.pjx.ac.cn/img1/2024/07/87529214008147d3aa1bbe5868849f31.png)
**Until now, you have set up the plugin in Obsidian. You can start syncing your notes to Notion.**
### 4. Start syncing
Create a new note in Obsidian, and fill in the front matter with the properties you want to sync.
#### 1⃣ note for general database
For example, we can create a test note with the following front matter:
``` markdown
---
title: test
tags: [test, web]
---
This is a test file.
```
After creating the note, you can click the `Share to NotionNext` button on the left sidebar to sync the note to Notion.
![general-sync](https://minioapi.pjx.ac.cn/img1/2024/07/6a690dc4b04d6b74134e9d3d76636c1b.gif)
#### 2⃣ note for NotionNext database
We use the following front matter for the NotionNext database:
```markdown
---
title: test-notionnext
titleicon: 📎
date: 2023-07-23
coverurl: https://img.jxpeng.dev/2023/08/843e27a210847f05a0f7cfb121fec100.jpg
type: Post
slug: test
status: Draft
category: test
summary: this is a summary for test post
icon: fa-solid fa-camera
password: "1234"
tags:
- test
- web
NotionID-pengjiaxin: 8ba573de-8fdf-4681-b063-c39d26e7860e
---
this is a test file
```
![notionnext-sync](https://minioapi.pjx.ac.cn/img1/2024/07/5539ec534e7a855ad87aa7949e5e836f.gif)
#### 3⃣ note for custom database
##### sync title and tags
Use the previously created general database and rename `title` to `Name` and `tags` to `Tags` in Notion.
![rename-notion](https://minioapi.pjx.ac.cn/img1/2024/07/e4d1c988be22353537998db897c7a471.gif)
The front matter for the custom database is as follows:
```markdown
---
Name: test-custom
Tags:
- test
- web
---
This is a test file.
```
![sync-custom](https://minioapi.pjx.ac.cn/img1/2024/07/973f17955cd921cca6b5007f0990eea4.gif)
##### sync more properties
Add more property to the custom database. For example, we can add a `summary` and `date` property to the custom database.
1). Click `Edit` in the plugin settings.
![edit](https://minioapi.pjx.ac.cn/img1/2024/07/f50639d8118b1f106d7bb29be5d3527b.png)
2). Click `Add` and add the `summary` and `date` property.
![add-property](https://minioapi.pjx.ac.cn/img1/2024/07/49716657adf0255a37fa214abf4716dc.gif)
3). After adding the properties, you can see the properties in the plugin settings.
![four properties](https://minioapi.pjx.ac.cn/img1/2024/07/63a0a0e09d537b1cf55cfdc49de4db1a.png)
4). Add the `summary` and `date` in Notion
![add-in-notion](https://minioapi.pjx.ac.cn/img1/2024/07/d193fe72ce3676bf643b0d1eb92dd4b7.gif)
5). Create a new note with the `summary` and `date` property.
```markdown
---
Name: test-custom-more
Tags:
- test
- web
summary: this is a summary for test custom
date: 2022-05-03
---
This is a test file.
```
6). Sync the note to Notion.
![sync-custom](https://minioapi.pjx.ac.cn/img1/2024/07/0e4cfbd61acdaf813fd81ee6d046e067.gif)
---
- **Multiple Database Types**: Supports General, NotionNext, and Custom databases.
- **Custom Properties**: Map any frontmatter key to any Notion property in custom databases.
- **Flexible Syncing**: Choose which database to sync to on-the-fly.
## Acknowledgment
Thanks to the [original author](https://github.com/EasyChris/obsidian-to-notion) for developing such a useful plugin that can synchronize Obsidian to Notion. However, the original repository can only sync Name and Tag information. For those like me who use [NotionNext](https://github.com/tangly1024/NotionNext) to set up their website, this presents some limitations. Every time I import, I need to make a lot of modifications.
Thus, based on the [original author's work](https://github.com/EasyChris/obsidian-to-notion), I've added a feature to match the [NotionNext](https://github.com/tangly1024/NotionNext) template. This way, you can edit directly in Obsidian and publish with a single click after organizing.
---
<details> <summary> Original README.md </summary>
Many Thanks for the original author's work. I've only made some changes to the original author's work. If you find this plugin useful, please give the [original author](https://github.com/EasyChris/obsidian-to-notion) a star.
# Obsidian to Notion
[![](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml)
[![Release Obsidian plugin](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml)
[![GitHub license](https://img.shields.io/github/license/EasyChris/obsidian-to-notion)](https://raw.githubusercontent.com/EasyChris/obsidian-to-notion/master/LICENSE)
[![Github all releases](https://img.shields.io/github/downloads/Easychris/obsidian-to-notion/total.svg)](https://GitHub.com/Easychris/obsidian-to-notion/releases/)
[![GitLab latest release](https://badgen.net/github/release/Easychris/obsidian-to-notion/)](https://github.com/Easychris/obsidian-to-notion/releases)
Share of obsidian to Notion [中文文档](README-zh.md)
Sharing files from Obsidian to Notion with a single click, and Obsidian will automatically add the Notion share link
You are welcome to offer it a star if it can benefit you.
![](./doc/1.gif)
# TODO
### [TODO Board](https://github.com/users/EasyChris/projects/3/views/1)
- [x] support for custom page banner
- [x] update the exsit page
- [x] support for mult language
- [x] support for auto copy the share link to clipboard
- [x] support for mobile
- [x] support tags thank for [@jannikbuscha](https://github.com/jannikbuscha)
- [ ] transfer the bi-link format like [[]] into the format that Notion supports.
# How to use
## Install the plugin
### Marketplace download
Open obsidian setting -> Add plugin -> Search -> notion
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220628214145.png)
### BRAT
Enter `BRAT` into the plugin market center to find it.
Add `EasyChris/obsidian-to-notion` to the list of BRAT plugins that have been installed.
Return to the plugin center and turn it on.
### Manual installation
```
cd YOUR_OBSIDIAN_FOLDER/.obsidian/plugins/
git clone https://github.com/EasyChris/obsidian-to-notion.git
```
## Apply Notion API
Official reference documentation: [https://developers.notion.com/docs](https://developers.notion.com/docs)
### Step 1: Create integration
Go to [https://www.notion.com/my-integrations](https://www.notion.com/my-integrations)
Once created, copy `secrets toekn`
![](https://files.readme.io/2ec137d-093ad49-create-integration.gif)
#### Note
database first custom name must be "Name", otherwise sync to notion will be failed
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220618102029.png)
### Step 2: Share a database with your integration
Create a new page (with public permissions)
Create a new database in the page -> you need `full page database`
![](./doc/3.gif)
Add `integration` to your new database
![](./doc/6.gif)
### Step 3: Copy the database ID
```
https://www.notion.so/myworkspace/a8aec43384f447ed84390e8e42c2e089?v=...
| --------- Database ID --------|
```
## Open the plugin configuration
Fill the configuration with the `NOTION_API_KEY` and `DATABASE_ID` you got
![](./doc/2.png)
## Upload file content to notion
Click the uploadCommand notion button
![](./doc/4.png)
A share link will be automatically generated after successful uploadCommand
![](./doc/5.png)
## Banner URL [option]
Banner url must be a image url like: <https://i.imgur.com/xxx.jpg>
If you don't want to use banner, leave it blank
## Convert Tags [option]
Transfer the Obsidian tags to the Notion table.
It requires the column with the name 'Tags'.
![](./doc/7.png)
Add tags to your notion page
![](./doc/10.png)
- open plugin convert tags
![](./doc/8.png)
- add tags in the head
```markdown
---
tags: [tag1,tag2]
---
this is test tags
```
```markdown
---
tags:
- tag4
---
this is test tags
```
![](./doc/9.png)
Thanks for [@jannikbuscha](https://github.com/jannikbuscha) contribution
## Notion ID [option]
Notion ID is the your notion site ID that you want to share the file to.
if you don't write it, notion will share to the default link like:
<https://www.notion.so/myworkspace/a8aec43384f447ed84390>
that visit this page need to redirect to your site url
if you write the Notion ID, it will share to the page link like:
<https://your_user_name.notion.site/myworkspace/a8aec43384f447ed84390>.
The visiter don't need to redirect url.
## Sync image to Notion
To sync images to your oss or cos bucket, use the [Obsidian Image Auto Upload Plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin).
# Development
```
git clone https://github.com/EasyChris/obsidian-to-notion.git
yarn install
yarn dev
```
## Release
```
node update-version.js
./release.sh
```
# Thanks
[Development Process | Obsidian Plugin Development Documentation](https://luhaifeng666.github.io/obsidian-plugin-docs-zh/zh/getting-started/development-workflow.html)
[GitHub - devbean/obsidian-wordpress: An obsidian plugin for publishing docs to WordPress.](https://github.com/devbean/obsidian-wordpress)
[GitHub - obsidianmd/obsidian-api](https://github.com/obsidianmd/obsidian-api)
[GitHub - Easychris/obsidian-to-notion: Obsidian Weread Plugin is an plugin to sync Weread(微信读书) hightlights and annotations into your Obsidian Vault.](https://github.dev/zhaohongxuan/obsidian-weread-plugin)
[GitHub - Quorafind/Obsidian-Memos: A quick capture plugin for Obsidian, all data from your notes.](https://github.com/Quorafind/Obsidian-Memos)
[https://github.com/jannikbuscha/obsidian-to-notion](https://github.com/jannikbuscha)
# License
GNU GPLv3
</details>
This plugin is a fork of the original [obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion) by EasyChris, with added features and support for more flexible database configurations.

BIN
doc/1.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 552 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

BIN
doc/2.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

BIN
doc/3.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

BIN
doc/4.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

BIN
doc/5.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

BIN
doc/6.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

BIN
doc/7.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

BIN
doc/8.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

BIN
doc/9.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

69
docs/.vitepress/config.ts Normal file
View File

@@ -0,0 +1,69 @@
import { defineConfig } from 'vitepress'
import { withSidebar } from 'vitepress-sidebar';
// https://vitepress.dev/reference/site-config
const vitePressOptions = {
title: "Obsidian to NotionNext",
description: "A plugin to share files to any Notion database using the Notion API.",
themeConfig: {
socialLinks: [
{ icon: 'github', link: 'https://github.com/jxpeng98/obsidian-to-NotionNext' }
]
},
locales: {
root: {
label: 'English',
lang: 'en',
link: '/en/',
themeConfig: {
nav: [
{ text: 'Home', link: '/en/' },
{ text: 'Guide', link: '/en/01-getting-started' }
],
}
},
zh: {
label: '简体中文',
lang: 'zh-CN',
link: '/zh/',
themeConfig: {
nav: [
{ text: '首页', link: '/zh/' },
{ text: '指南', link: '/zh/01-getting-started' }
],
}
}
}
};
const commonSidebarOptions = {
documentRootPath: '/',
useTitleFromFrontmatter: true,
frontmatterTitleFieldName: 'title',
collapsed: true,
removePrefixAfterOrdering: true,
prefixSeparator: '-',
hyphenToSpace: true,
useFolderTitleFromIndexFile: true,
useFolderLinkFromIndexFile: true,
sortMenusByName: false,
};
const vitePressSidebarOptions = [
{
...commonSidebarOptions,
scanStartPath: '/en',
basePath: '/',
resolvePath: '/en/'
},
{
...commonSidebarOptions,
scanStartPath: '/zh',
basePath: '/',
resolvePath: '/zh/',
}
];
export default defineConfig(withSidebar(vitePressOptions, vitePressSidebarOptions));

View File

@@ -0,0 +1,45 @@
---
title: Getting Started
description: Guide to setting up the Obsidian to NotionNext plugin
---
# Getting Started
## Get Notion API Token
Before using the plugin, you need to obtain an API Token from Notion to allow the plugin to access your Notion account.
1. Go to the [Notion API](https://www.notion.so/profile/integrations) page to create a new integration. You need to be logged into your Notion account.
2. Click on `+ New integration`.
![new-integration](https://r2imga.jxpeng.dev/2025/10/3d12358494c000ab7035820e1e836934.png)
3. Fill in the required information:
![integration-info](https://r2imga.jxpeng.dev/2025/10/645b8182105e5e64e61bd263394534d6.png)
4. Integration successfully created.
![success](https://r2imga.jxpeng.dev/2025/10/57ea92c48efc15b95a69f3663424f5ae.png)
5. Enter the "Configure integration settings" page and **prepare to copy the API Token,** which you will need in the plugin settings.
![configure-integration](https://r2imga.jxpeng.dev/2025/10/4a50e55c35e47f905fb7fe63af5c8402.png)
::: warning
**⚠️ Note:** Keep your API Token secure and do not share it with others, as it grants access to your Notion data.
:::
## Create a Notion Database and Connect Integration
Next, you need to create a Notion database to store the notes synced from Obsidian.
1. In your Notion workspace, click on `Create a new page` to create a new page.
![create-new-page](https://r2imga.jxpeng.dev/2025/10/1f092ef1d8c5a25aeb75694d654810a1.png)
2. create a new page and select the `Database - Full page` option.
![new-database](https://r2imga.jxpeng.dev/2025/10/73b700fc65a53f2ff518b58832bf9757.png)
3. Click the `...` menu in the top-right corner of the database page, go to `Connections`, and connect your newly created integration.
![connect-integration](https://r2imga.jxpeng.dev/2025/10/e8d9be4718f6f5c76fdc3bee7d694d23.png)
4. Click `Share` -> `Publish` to publish the database to the web.
![publish](https://r2imga.jxpeng.dev/2025/10/4b1d3f597d67508ee67d20a62151200f.png)
5. Click and copy the **Database ID**.
![database-id](https://r2imga.jxpeng.dev/2025/10/d8f22c1daf5063305256e5e50210adf9.png)
Next, you can proceed to install and configure the plugin in Obsidian by following the [Installation Guide](./02-installation.md).

View File

@@ -0,0 +1,28 @@
---
title: Installation
description: Guide to installing the Obsidian to NotionNext plugin
---
# Installation
Once you have completed the previous section setup on the Notion side, you can install and configure the plugin in Obsidian.
1. Open Obsidian's `Settings`.
![obsidian](https://r2imga.jxpeng.dev/2025/10/6f80d5126391162dd7cc98de87d3c1b2.png)
2. Navigate to `Community plugins`.
![community-plugins](https://r2imga.jxpeng.dev/2025/10/adf7dd7d292dcc331d7625b8f409f222.png)
::: tip
If you haven't enabled community plugins before, you may need to turn off `Safe mode` first (`Turn on Community plugins`).
:::
3. Go to `Community plugins` -> `Browse`.
![browse](https://r2imga.jxpeng.dev/2025/10/e4f170f966902999fe2137196d8b6f9c.png)
4. Search for "NotionNext" and click `Install`.
![install](https://r2imga.jxpeng.dev/2025/10/1b0fcf15bc80aeb3714d9c97cbc6d5b0.png)
5. After installation, enable the plugin.
![enable](https://r2imga.jxpeng.dev/2025/10/6c7a7ee7d6e5861a3f0867c826e3f2c0.png)
Now, once enabled, you can find the "Share to NotionNext" settings in the plugin settings tab to begin [configuring your databases](./03-configuration.md) in the next step.

127
docs/en/03-configuration.md Normal file
View File

@@ -0,0 +1,127 @@
---
title: Configuration
description: Guide to configuring Notion databases in the Obsidian to NotionNext plugin
---
# Database Configuration
After installing the plugin and obtaining the Notion API token and Database ID, you can proceed to configure the databases you want to sync with.
First, open the plugin settings in Obsidian.
![open-plugin-settings](https://r2imga.jxpeng.dev/2025/10/d2cfc05a86a8f014354fbd4e8456ccdc.png)
Click "Add new database" to start creating a new database configuration.
![add-database](https://r2img.jxpeng.dev/2024/07/115f47b4180d04fb362b931f8092b5fb.png)
In the plugin settings, you can add and configure the Notion databases you want to sync with. The plugin supports three types of database configurations.
- [Database Configuration](#database-configuration)
- [1⃣ General Database](#1⃣-general-database)
- [2⃣ NotionNext Database](#2⃣-notionnext-database)
- [3⃣ Custom Database](#3⃣-custom-database)
- [Finalizing Configuration](#finalizing-configuration)
## Auto Sync Frontmatter Entry
If you enable auto sync, the plugin needs a frontmatter entry that lists which configured databases should receive updates. You can customise the name of this entry in **Settings → Auto Sync Frontmatter Key** (default: `autosync-database`). Use any text you like—letters, numbers, emojis, or other scripts are all supported.
In your note's frontmatter, add the configured key and list the database abbreviations you created in the settings:
```yaml
---
title: My Article
autosync-database: [blog, ideas]
---
```
The entry can be a YAML list or comma-separated string, and manual uploads will automatically add the current database abbreviation if it is missing. If you change the key name in settings, update your frontmatter to match the new value.
## 1⃣ General Database
This is the most basic database type and is suitable for most users.
**Configuration:**
- **Full Name**: A name for this database configuration.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
**Notion Database Requirements:**
- Must contain a `Title` property named `title`.
- Must contain a `Multi-select` property named `tags`.
![notion-general](https://r2imga.jxpeng.dev/2025/10/3abc05f71a1bd81bdc00fd988dd71108.png)
Then, fill in the configuration fields as shown below:
- **Database Full Name**: the name you want to give this database to recognise it in the database list (e.g. "Learning Database").
- **Database Abbreviate Name**: a short abbreviation for this database (e.g. "learning").
- **Notion Tags Sync**: enable this option if you want to sync tags columns from Obsidian to Notion (**if you enable this option, make sure you add tags in your notes**).
- **Customise title property**: the property in your Notion database that you want to use as the primary column (default is `title`).
- **Notion API Token**: the API token you obtained in the first step.
- **Database ID**: the database ID you obtained in the second step.
![general](https://r2imga.jxpeng.dev/2025/10/9697de930e530c55081e07835e224782.png)
## 2⃣ NotionNext Database
This type is specifically designed for users of the [NotionNext](https://github.com/tangly1024/NotionNext) blog system, with properties preset to match the NotionNext template.
Config the database similarly to the General Database type:
- **Database Full Name**: A name for this database configuration.
- **Database Abbreviate Name**: A short abbreviation for this database.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
![notionnext](https://r2imga.jxpeng.dev/2025/10/5b1b3b3fb4ef9a76f4fed26fcc6c426b.png)
## 3⃣ Custom Database
This type offers maximum flexibility for advanced users. It allows you to map any frontmatter metadata from your Obsidian notes to any property in your Notion database.
You should first config the database similarly to the General Database type:
- **Database Full Name**: A name for this database configuration.
- **Database Abbreviate Name**: A short abbreviation for this database.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
![custom](https://r2imga.jxpeng.dev/2025/10/667335d7fd2cfa96e307be3df79e157e.png)
Once you have filled in the basic configuration, you can start to add new properties.
You can click the `Add New Property` button to create a new property mapping.
First, you need to add the title property mapping, which is required for the Notion database to function correctly.
![title-property](https://r2imga.jxpeng.dev/2025/10/2ad52037476d3f86f3c4cfbed507f74b.png)
::: tip
Remember to set the "Notion Property" to the property name in your Notion database (case-sensitive) and the "Frontmatter Key" to the key in your Obsidian note's frontmatter.
:::
After adding the title property, you can continue to add more properties as needed.
![property-1](https://r2imga.jxpeng.dev/2025/10/d4c0bcc3abbc741dd34ce22e589d6223.png)
For now, the plugin supports the following Notion property types:
- Text
- Number
- Select
- Multi-select
- Date
- Files & Media
- Checkbox
- URL
- Email
- Phone Number
![types](https://r2imga.jxpeng.dev/2025/10/81d321693dfd046ad3386e4507d60792.png)
::: info
Relation and Rollup types are not supported yet.
:::
## Finalizing Configuration
After configuring your database, make sure to save your settings. You can now start syncing your Obsidian notes to the configured Notion database by using the "Share to NotionNext" command from the command palette or the note context menu.

162
docs/en/04-sync.md Normal file
View File

@@ -0,0 +1,162 @@
---
title: Syncing Notes
description: How to sync your Obsidian notes to Notion using the NotionNext plugin
---
# Syncing Notes
After configuring your Notion database in the plugin settings, you can start syncing your Obsidian notes to Notion.
## Manual Sync
To sync a note, open the note you want to sync and use the "Share to NotionNext" command from the command palette or the note context menu. This will create a new page in your Notion database with the content of your Obsidian note.
## Auto Sync
The plugin supports automatic syncing that monitors your notes for changes and automatically syncs them to Notion.
### Enabling Auto Sync
1. Open the plugin settings
2. Find the "Auto Sync" toggle under General Settings
3. Enable the toggle
4. Configure the "Auto Sync Delay" (default: 5 seconds, minimum: 2 seconds)
### Prepare the Frontmatter
Auto sync reads the database list from the frontmatter key you configured in **Settings → Auto Sync Frontmatter Key** (default: `autosync-database`). To make sure your notes can sync automatically:
- Add the configured key to your note's frontmatter
- List one or more database abbreviations that you defined in the plugin settings
- Keep the list updated if you change the databases a note should sync to
Example with the default key:
```yaml
---
title: My Article
autosync-database: [blog, portfolio]
---
```
If you change the key name in the settings, update your frontmatter to match.
### How Auto Sync Works
When auto sync is enabled:
- The plugin monitors markdown files for changes
- After you stop editing for the configured delay period, auto sync is triggered
- Files with the `autosync-database` key in frontmatter will be automatically synced
- **First-time upload is supported**: No need to manually sync first - just add the frontmatter key and the plugin will handle the initial upload
- If a file is linked to multiple databases, it will sync to all of them automatically
- After the first sync, a `NotionID-{database}` will be added to the frontmatter for future updates
### Auto Sync Scenarios
#### Scenario A-1: New File Missing Auto Sync Entry
```yaml
---
title: My New Article
tags: [blog, tech]
---
```
**Behavior:**
- ✅ Detects that the auto sync key is missing
- ✅ Detects no NotionID present (new file)
- ✅ Silently skips - no notice shown
- 📝 **To enable auto sync:** Add `autosync-database: [your-db-abbreviation]` to the frontmatter
#### Scenario A-2: Synced File Missing Auto Sync Entry
```yaml
---
title: My Article
NotionID-blog: abc123
---
```
**Behavior:**
- ✅ Detects that the auto sync key is missing
- ✅ Detects existing NotionID (file was synced before)
- ✅ Shows notice: "⚠️ Auto-sync skipped: Add autosync-database to your frontmatter to specify target databases"
- ✅ No sync operation performed
- 📝 **Action Required:** Add `autosync-database: [blog]` to the frontmatter
#### Scenario B: New Document (First-Time Auto Upload)
```yaml
---
title: My New Article
autosync-database: [blog]
---
```
**Behavior:**
- ✅ Detects no NotionID present but `autosync-database` is configured
- ✅ Automatically performs first-time upload to the Blog database
- ✅ Adds `NotionID-blog: xxx` to the frontmatter after successful upload
- ✅ Shows success/failure notification
- 📝 **No Action Required:** The plugin handles the initial upload automatically
#### Scenario C: Synced to One Database
```yaml
---
title: My Article
NotionID-blog: abc123
autosync-database: [blog]
---
```
**Behavior:**
- ✅ Detects 1 NotionID
- ✅ Automatically syncs to the Blog database
- ✅ Shows success/failure notification from the upload command
- 📝 **No Action Required:** Changes are automatically synced
#### Scenario D: Synced to Multiple Databases
```yaml
---
title: My Article
NotionID-blog: abc123
NotionID-portfolio: def456
NotionID-notes: ghi789
autosync-database: [blog, portfolio, notes]
---
```
**Behavior:**
- ✅ Detects 3 database targets
- ✅ Shows notice: "🔄 Auto sync: Syncing to 3 database(s)..."
- ✅ Syncs to all 3 databases sequentially
- ✅ Shows individual result notifications for each database
- 📝 **No Action Required:** Changes are automatically synced to all linked databases
#### Scenario E: Custom Frontmatter Key
```yaml
---
title: My Article
NotionID-blog: abc123
NotionID-portfolio: def456
🚀-sync-targets: [blog, portfolio]
---
```
**Behavior:**
- ✅ Uses your custom key (for example `🚀-sync-targets`) configured in settings
- ✅ Syncs to the listed databases when NotionIDs are present
- 📝 **Remember:** Update both the setting and your frontmatter if you rename the key
### Auto Sync Best Practices
1. **Add Frontmatter Key**: Just add `autosync-database: [your-db]` to enable auto sync - no manual upload needed
2. **Configure Delay Appropriately**: Set a longer delay (5-10 seconds) if you make frequent edits
3. **Monitor Sync Status**: Check the notifications to ensure syncs complete successfully
4. **Check Logs**: Open the developer console (Ctrl+Shift+I / Cmd+Option+I) to view detailed sync logs
### Troubleshooting
Having issues with auto sync? Check the [Troubleshooting Guide](05-troubleshooting.md) for detailed solutions to common problems.

View File

@@ -0,0 +1,74 @@
---
title: Troubleshooting
description: Common issues and solutions for the Obsidian to NotionNext plugin
---
# Troubleshooting
## Auto Sync Issues
### Auto sync not working?
**Possible causes and solutions:**
- **Auto sync not enabled**: Ensure auto sync is enabled in plugin settings under General Settings
- **No NotionID in frontmatter**: Verify the document has a NotionID field (e.g., `NotionID-blog: abc123`) in its frontmatter. Auto sync only works for documents that have been manually synced at least once
- **Invalid database configuration**: Check that your database configuration is valid and the API credentials are correct
- **Console errors**: Look for errors in the developer console (`Ctrl+Shift+I` / `Cmd+Option+I`)
### Sync too frequent?
If auto sync is triggering too often while you're editing:
- **Increase the delay**: Go to plugin settings and increase the "Auto Sync Delay" value (default is 5 seconds)
- **Understanding the delay**: The delay timer resets each time you make an edit, so sync only triggers after you stop editing for the configured duration
### Missing notifications?
If you're not seeing sync notifications:
- **Notification duration**: Notifications appear for 3-6 seconds and then automatically disappear
- **Check console logs**: Open the developer console (`Ctrl+Shift+I` / `Cmd+Option+I`) to view detailed sync information
- **Multiple syncs**: When syncing to multiple databases, you'll see a notification for the multi-database sync plus individual result notifications
### Auto sync skipped for new documents
If you see the message "⚠️ Auto sync skipped: This document has not been synced to Notion, please upload manually first":
- **First sync required**: This is expected behavior. Auto sync only works for documents that already have a NotionID
- **Solution**: Use the command palette (`Ctrl/Cmd + P`) and select "Share to NotionNext" to perform the first manual sync
- **After manual sync**: Once the document has a NotionID in its frontmatter, auto sync will work automatically
## General Sync Issues
### Sync failed with error message
If you see error messages during sync:
1. **Check API credentials**: Verify your Notion API token and Database ID are correct
2. **Check permissions**: Ensure the integration has access to the target database
3. **Network issues**: Check your internet connection
4. **Rate limiting**: Notion has API rate limits; wait a moment and try again
5. **Check console**: Open developer tools to see detailed error information
### Multiple database sync issues
When syncing to multiple databases:
- **Partial failures**: If one database fails, others will still continue syncing
- **Individual notifications**: Each database sync shows its own result notification
- **Check frontmatter**: Verify all NotionID fields are present and correct (e.g., `NotionID-blog`, `NotionID-portfolio`)
## Getting Help
If the problem persists, you can [open an issue on GitHub](https://github.com/jxpeng98/obsidian-to-NotionNext/issues) with detailed error information and the steps you took.
You can find the error logs in Obsidian by going to developer tools (`Ctrl+Shift+I` or `Cmd+Option+I`) and checking the console for any error messages related to the NotionNext plugin.
### What to include in bug reports:
1. **Error messages**: Copy the exact error message from notifications or console
2. **Console logs**: Include relevant logs from the developer console (look for `[AutoSync]`, `[Settings]`, or `[Plugin]` prefixes)
3. **Steps to reproduce**: Describe what you were doing when the issue occurred
4. **Configuration**: Mention which database format you're using (NotionNext, General, or Custom)
5. **Settings**: Note if auto sync is enabled and what delay is configured

40
docs/en/06-changelog.md Normal file
View File

@@ -0,0 +1,40 @@
---
title: Changelog
description: Release notes and updates for Obsidian to NotionNext
---
# Changelog
Welcome to the Changelog for Obsidian to NotionNext! Here you'll find a detailed list of all the updates, improvements, and bug fixes made to the plugin over time from the version `2.7.0` onwards.
## v2.8.0-beta.2 (2025-11-05)
### Featured
- Added setting to customise the frontmatter key used for auto sync database lists (defaults to `autosync-database`)
## v2.8.0-beta.1 (2025-10-31)
### Added
- **Auto Sync Feature**: Automatically sync notes to Notion when content or frontmatter changes
- Configurable delay (default: 5 seconds, minimum: 2 seconds)
- Support for multiple database syncing
- Smart detection to avoid sync loops when only NotionID is updated
- Content hash comparison to detect body text changes
- Works on both desktop and mobile platforms
- Added comprehensive i18n support for all UI elements and notifications
- Added prerelease workflow for beta testing via GitHub Actions and BRAT
### Changed
- Enhanced settings tab with auto-sync configuration options
- Improved debug logging for better troubleshooting
- Updated documentation with auto-sync usage guide and troubleshooting section
### Fixed
- Fixed mobile compatibility issues by using `window.setTimeout` instead of `NodeJS.Timeout`
- Fixed sync loop prevention logic to properly handle frontmatter and content changes
- Fixed cache update timing to ensure accurate change detection

10
docs/en/07-roadmap.md Normal file
View File

@@ -0,0 +1,10 @@
---
title: Roadmap
description: Planned features and improvements for Obsidian to NotionNext
---
# Roadmap
- [ ] Automatic Syncing: Implement automatic syncing of notes at regular intervals or upon changes.
- [ ] File Attachments: Support for syncing file attachments from Obsidian to Notion.
- [ ] Relation Property: Enable mapping of Obsidian links to Notion relation properties.

27
docs/en/index.md Normal file
View File

@@ -0,0 +1,27 @@
---
title: Introduction
description: Share files to any Notion database using the Notion API
order: 0
---
# Obsidian to NotionNext
In this documentation, you will find guides and instructions on how to set up and use the Obsidian to NotionNext plugin. This plugin allows you to share your Obsidian notes directly to Notion databases using the Notion API.
This guide will walk you through the process of setting up the Obsidian to NotionNext plugin.
[Getting Started](./01-getting-started.md)
[Installation](./02-installation.md)
[Configuration](./03-configuration.md)
[Syncing Notes](./04-sync.md)
[Troubleshooting](./05-troubleshooting.md)
---
[Changelog](./06-changelog.md)
[Roadmap](./07-roadmap.md)

29
docs/index.md Normal file
View File

@@ -0,0 +1,29 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: "Obsidian to NotionNext"
text: "Share files to any Notion database using the Notion API"
tagline: Support All Notion databases, including NotionNext and General Notion databases, and customise the database list.
actions:
- theme: brand
text: Get Started
link: /en/
- theme: brand
text: 现在开始
link: /zh/
- theme: alt
text: View on GitHub
link: https://github.com/jxpeng98/obsidian-to-NotionNext
features:
- title: All Notion Databases
details: Support for both general and NotionNext-specific databases.
- title: Custom Properties
details: Customize database properties to fit your workflow.
- title: Long Note Sync
details: Sync long notes seamlessly.
- title: Callout Support
details: Obsidian callouts are converted to Notion callout blocks.
---

17
docs/package.json Normal file
View File

@@ -0,0 +1,17 @@
{
"name": "obsidian-to-notionnext-docs",
"private": true,
"engines": {
"node": ">=20"
},
"scripts": {
"dev": "vitepress dev",
"build": "vitepress build",
"preview": "vitepress preview"
},
"devDependencies": {
"vitepress": "^2.0.0-alpha.12",
"vitepress-sidebar": "^1.33.0",
"vue": "^3.5.22"
}
}

1756
docs/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
---
title: 开始使用
description: Obsidian to NotionNext 插件设置指南
---
# 开始使用
## 获取 Notion API 令牌
在使用本插件前,你需要从 Notion 获取一个 API 令牌Token以授权插件访问你的 Notion 账户。
1. 前往 [Notion API](https://www.notion.so/profile/integrations) 页面来创建一个新的集成integration。你需要先登录你的 Notion 账户。
2. 点击 `+ New integration`
![new-integration](https://r2imga.jxpeng.dev/2025/10/3d12358494c000ab7035820e1e836934.png)
3. 填写一些基本信息:
![integration-info](https://r2imga.jxpeng.dev/2025/10/645b8182105e5e64e61bd263394534d6.png)
4. 成功创建集成。
![success](https://r2imga.jxpeng.dev/2025/10/57ea92c48efc15b95a69f3663424f5ae.png)
5. 进入“配置集成设置”页面,**准备好复制 API 令牌**,你很快就会在插件设置中用到它。
![configure-integration](https://r2imga.jxpeng.dev/2025/10/4a50e55c35e47f905fb7fe63af5c8402.png)
::: warning
**⚠️ 注意:** 请妥善保管你的 API 令牌,不要与他人分享,因为它授予了访问你 Notion 数据的权限。
:::
## 创建 Notion 数据库并连接集成
接下来,你需要创建一个 Notion 数据库,用于存放从 Obsidian 同步过来的笔记。
1. 在你的 Notion 工作区中,点击 `Create a new page` 来创建一个新页面。
![create-new-page](https://r2imga.jxpeng.dev/2025/10/1f092ef1d8c5a25aeb75694d654810a1.png)
2. 创建一个新页面后,选择 `Database - Full page` 选项。
![new-database](https://r2imga.jxpeng.dev/2025/10/73b700fc65a53f2ff518b58832bf9757.png)
3. 点击数据库页面右上角的 `...` 菜单,进入 `Connections`,然后连接你刚刚创建的集成。
![connect-integration](https://r2imga.jxpeng.dev/2025/10/e8d9be4718f6f5c76fdc3bee7d694d23.png)
4. 点击 `Share` -> `Publish`,将数据库发布到网络。
![publish](https://r2imga.jxpeng.dev/2025/10/4b1d3f597d67508ee67d20a62151200f.png)
5. 点击并复制 **数据库 ID**
![database-id](https://r2imga.jxpeng.dev/2025/10/d8f22c1daf5063305256e5e50210adf9.png)
接下来,你可以根据[安装指南](./02-installation.md)在 Obsidian 中安装和配置插件了。

View File

@@ -0,0 +1,28 @@
---
title: 安装插件
description: 如何安装 Obsidian to NotionNext 插件
---
# 安装插件
当你在 Notion 端完成上一章节的设置后,就可以在 Obsidian 里安装和配置插件了。
1. 打开 Obsidian 的 `设置`
![obsidian](https://r2imga.jxpeng.dev/2025/10/6f80d5126391162dd7cc98de87d3c1b2.png)
2. 找到 `第三方插件` 菜单。
![community-plugins](https://r2imga.jxpeng.dev/2025/10/adf7dd7d292dcc331d7625b8f409f222.png)
::: tip
如果你之前没有启用过第三方插件,可能需要先关闭 `安全模式`(点击 `打开社区插件`)。
:::
3. 进入 `社区插件` -> `浏览`
![browse](https://r2imga.jxpeng.dev/2025/10/e4f170f966902999fe2137196d8b6f9c.png)
4. 搜索 "NotionNext" 并点击 `安装`
![install](https://r2imga.jxpeng.dev/2025/10/1b0fcf15bc80aeb3714d9c97cbc6d5b0.png)
5. 安装完成后,记得 `启用` 插件。
![enable](https://r2imga.jxpeng.dev/2025/10/6c7a7ee7d6e5861a3f0867c826e3f2c0.png)
启用后,你就可以在插件设置列表中找到 "Share to NotionNext",并在下一步开始[配置你的数据库](./03-configuration.md)了。

112
docs/zh/03-configuration.md Normal file
View File

@@ -0,0 +1,112 @@
---
title: 配置数据库
description: 在 Obsidian to NotionNext 插件中配置 Notion 数据库的指南
---
# 配置数据库
在安装好插件并获取了 Notion API 令牌和数据库 ID 之后,你就可以开始配置要同步的数据库了。
首先,在 Obsidian 中打开插件设置。
![open-plugin-settings](https://r2imga.jxpeng.dev/2025/10/d2cfc05a86a8f014354fbd4e8456ccdc.png)
点击 “添加新数据库” 来创建一个新的数据库配置。
![add-database](https://r2img.jxpeng.dev/2024/07/115f47b4180d04fb362b931f8092b5fb.png)
插件支持三种类型的数据库配置,你可以根据自己的需求选择。
- [数据库配置](#数据库配置)
- [1⃣ 通用数据库](#1⃣-通用数据库)
- [2⃣ NotionNext 数据库](#2⃣-notionnext-数据库)
- [3⃣ 自定义数据库](#3⃣-自定义数据库)
- [完成配置](#完成配置)
## 1⃣ 通用数据库
这是最基础的数据库类型,适合大多数用户。
**配置项:**
- **数据库全名**: 给这个数据库配置起一个容易识别的名字。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
**Notion 数据库要求:**
- 必须包含一个名为 `title``Title` 属性。
- 必须包含一个名为 `tags``Multi-select` 属性。
![notion-general](https://r2imga.jxpeng.dev/2025/10/3abc05f71a1bd81bdc00fd988dd71108.png)
然后,像下面这样填写配置字段:
- **数据库全名 (Database Full Name)**: 你希望这个数据库在列表中显示的名字(例如:“学习资料库”)。
- **数据库简称 (Database Abbreviate Name)**: 一个简短的别名例如“learning”
- **同步 Notion 标签 (Notion Tags Sync)**: 如果希望将 Obsidian 的标签同步到 Notion请启用此选项**启用后,请确保你的笔记中包含 `tags`**)。
- **自定义标题属性 (Customise title property)**: 你想用作主列的 Notion 数据库属性(默认为 `title`)。
- **Notion API 令牌 (Notion API Token)**: 你在第一步中获取的 API 令牌。
- **数据库 ID (Database ID)**: 你在第二步中获取的数据库 ID。
![general](https://r2imga.jxpeng.dev/2025/10/9697de930e530c55081e07835e224782.png)
## 2⃣ NotionNext 数据库
这个类型是为 [NotionNext](https://github.com/tangly1024/NotionNext) 博客系统的用户量身定制的,其属性已预设好以匹配 NotionNext 模板。
配置方式与通用数据库类似:
- **数据库全名**: 为这个数据库配置起一个名字。
- **数据库简称**: 一个简短的别名。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
![notionnext](https://r2imga.jxpeng.dev/2025/10/5b1b3b3fb4ef9a76f4fed26fcc6c426b.png)
## 3⃣ 自定义数据库
这个类型为高级用户提供了极大的灵活性,允许你将 Obsidian 笔记中的任何 frontmatter 元数据映射到 Notion 数据库的任意属性。
首先,你需要像配置通用数据库一样填写基本信息:
- **数据库全名**: 为这个数据库配置起一个名字。
- **数据库简称**: 一个简短的别名。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
![custom](https://r2imga.jxpeng.dev/2025/10/667335d7fd2cfa96e307be3df79e157e.png)
填写完基本配置后,你就可以开始添加新的属性映射了。
你可以点击 `Add New Property` 按钮来创建一个新的属性映射。
首先,你需要添加标题属性的映射,这是 Notion 数据库正常工作所必需的。
![title-property](https://r2imga.jxpeng.dev/2025/10/2ad52037476d3f86f3c4cfbed507f74b.png)
::: tip
请记住,"Notion 属性 (Notion Property)" 需要填写你在 Notion 数据库中的属性名称(区分大小写),而 "Frontmatter 键 (Frontmatter Key)" 则是你 Obsidian 笔记 frontmatter 中的键。
:::
添加完标题属性后,你可以根据需要继续添加更多属性。
![property-1](https://r2imga.jxpeng.dev/2025/10/d4c0bcc3abbc741dd34ce22e589d6223.png)
目前,插件支持以下 Notion 属性类型:
- Text
- Number
- Select
- Multi-select
- Date
- Files & Media
- Checkbox
- URL
- Email
- Phone Number
![types](https://r2imga.jxpeng.dev/2025/10/81d321693dfd046ad3386e4507d60792.png)
::: info
关联Relation和汇总Rollup类型暂时还不支持。
:::
## 完成配置
配置完数据库后,请确保保存你的设置。现在,你可以通过命令面板或笔记右键菜单中的 “Share to NotionNext” 命令,开始将你的 Obsidian 笔记同步到配置好的 Notion 数据库了。

152
docs/zh/04-sync.md Normal file
View File

@@ -0,0 +1,152 @@
---
title: 同步笔记
description: 如何使用 NotionNext 插件将你的 Obsidian 笔记同步到 Notion
---
# 同步笔记
在插件设置中配置好你的 Notion 数据库后,你就可以开始将 Obsidian 笔记同步到 Notion 了。
## 手动同步
要同步一篇笔记,只需打开你想要同步的笔记,然后从命令面板(`Ctrl/Cmd + P`)或笔记的右键菜单中选择 "Share to NotionNext" 命令。这会在你的 Notion 数据库中创建一个新页面,内容与你的 Obsidian 笔记完全一致。
## 自动同步
插件支持自动同步功能,可以监控你的笔记变化并自动同步到 Notion。
### 启用自动同步
1. 打开插件设置
2. 在通用设置下找到"自动同步"开关
3. 开启该开关
4. 配置"自动同步延迟时间"默认5秒最小2秒
### 准备 Frontmatter
自动同步会读取你在 **设置 → 自动同步 Frontmatter 键名** 中配置的键名(默认为 `autosync-database`)来确定要同步的数据库。要让你的笔记能够自动同步:
- 在笔记的 frontmatter 中添加配置的键名
- 列出一个或多个你在插件设置中定义的数据库简称
- 如果修改了笔记要同步的数据库,记得更新列表
示例(使用默认键名):
```yaml
---
title: 我的文章
autosync-database: [blog, portfolio]
---
```
如果你在设置中修改了键名,记得同时更新你的 frontmatter。
### 自动同步工作原理
当自动同步启用后:
- 插件会监控 Markdown 文件的变化
- 在你停止编辑达到配置的延迟时间后,自动触发同步
- **支持首次自动上传**:无需先手动同步,只要添加 frontmatter 键名,插件会自动处理首次上传
- 如果文件关联了多个数据库,会自动同步到所有数据库
- 首次同步后,会自动在 frontmatter 中添加 `NotionID-{数据库}` 用于后续更新
### 自动同步场景示例
#### 场景 A-1新文件缺少自动同步配置
```yaml
---
title: 我的新文章
tags: [博客, 技术]
---
```
**行为:**
- ✅ 检测到缺少自动同步配置键
- ✅ 检测到没有 NotionID新文件
- ✅ 静默跳过,不显示任何提示
- 📝 **如需启用自动同步:** 在 frontmatter 中添加 `autosync-database: [你的数据库简称]`
#### 场景 A-2已同步文件缺少自动同步配置
```yaml
---
title: 我的文章
NotionID-blog: abc123
---
```
**行为:**
- ✅ 检测到缺少自动同步配置键
- ✅ 检测到已存在 NotionID说明之前同步过
- ✅ 显示提示:"⚠️ 自动同步已跳过:请在 frontmatter 中添加 autosync-database 以指定目标数据库"
- ✅ 不执行同步操作
- 📝 **需要操作:** 在 frontmatter 中添加 `autosync-database: [blog]`
#### 场景 B新文档首次自动上传
```yaml
---
title: 我的新文章
autosync-database: [blog]
---
```
**行为:**
- ✅ 检测到没有 NotionID但配置了 `autosync-database`
- ✅ 自动执行首次上传到 Blog 数据库
- ✅ 上传成功后自动添加 `NotionID-blog: xxx` 到 frontmatter
- ✅ 显示成功/失败通知
- 📝 **无需操作:** 插件会自动处理首次上传
#### 场景 C已同步到一个数据库更新
```yaml
---
title: 我的文章
NotionID-blog: abc123
autosync-database: [blog]
---
```
**行为:**
- ✅ 检测到 1 个 NotionID
- ✅ 自动同步更新到 Blog 数据库
- ✅ 显示上传命令返回的成功/失败通知
- 📝 **无需操作:** 变更会自动同步
#### 场景 D同步到多个数据库
```yaml
---
title: 我的文章
NotionID-blog: abc123
NotionID-portfolio: def456
NotionID-notes: ghi789
autosync-database: [blog, portfolio, notes]
---
```
**行为:**
- ✅ 检测到 3 个数据库目标
- ✅ 显示提示:"🔄 自动同步:正在同步到 3 个数据库..."
- ✅ 依次同步到所有 3 个数据库
- ✅ 为每个数据库显示独立的结果通知
- 📝 **无需操作:** 变更会自动同步到所有关联的数据库
### 自动同步最佳实践
1. **添加 Frontmatter 配置**:只需添加 `autosync-database: [你的数据库]` 即可启用自动同步,无需手动上传
2. **合理配置延迟**如果你经常编辑设置较长的延迟时间5-10 秒)
3. **监控同步状态**:注意查看通知以确保同步成功完成
4. **查看日志**打开开发者控制台Ctrl+Shift+I / Cmd+Option+I查看详细的同步日志
### 故障排除
遇到自动同步问题?请查看[问题排查指南](05-troubleshooting.md)获取常见问题的详细解决方案。

View File

@@ -0,0 +1,74 @@
---
title: 问题排查
description: Obsidian to NotionNext 插件的常见问题与解决方案
---
# 问题排查
## 自动同步问题
### 自动同步不工作?
**可能的原因及解决方案:**
- **未启用自动同步**:确保在插件设置的通用设置中启用了自动同步功能
- **frontmatter 中没有 NotionID**:验证文档的 frontmatter 中有 NotionID 字段(如 `NotionID-blog: abc123`)。自动同步仅适用于至少手动同步过一次的文档
- **数据库配置无效**检查数据库配置是否有效API 凭证是否正确
- **控制台错误**:查看开发者控制台(`Ctrl+Shift+I` / `Cmd+Option+I`)中的错误信息
### 同步太频繁?
如果在编辑时自动同步触发太频繁:
- **增加延迟时间**:前往插件设置,增加"自动同步延迟时间"的值(默认为 5 秒)
- **理解延迟机制**:每次编辑都会重置延迟计时器,只有在停止编辑达到配置的时长后才会触发同步
### 看不到通知?
如果没有看到同步通知:
- **通知显示时长**:通知会显示 3-6 秒然后自动消失
- **查看控制台日志**:打开开发者控制台(`Ctrl+Shift+I` / `Cmd+Option+I`)查看详细的同步信息
- **多数据库同步**:同步到多个数据库时,你会看到一个多数据库同步通知以及各个数据库的结果通知
### 新文档跳过自动同步
如果看到消息"⚠️ 自动同步跳过:此文档未同步到 Notion请先手动上传"
- **需要首次同步**:这是预期行为。自动同步仅适用于已有 NotionID 的文档
- **解决方案**:使用命令面板(`Ctrl/Cmd + P`)选择"Share to NotionNext"执行首次手动同步
- **手动同步后**:一旦文档的 frontmatter 中有了 NotionID自动同步就会自动工作
## 常规同步问题
### 同步失败并显示错误消息
如果在同步时看到错误消息:
1. **检查 API 凭证**:验证 Notion API 令牌和数据库 ID 是否正确
2. **检查权限**:确保集成有权限访问目标数据库
3. **网络问题**:检查网络连接
4. **速率限制**Notion 有 API 速率限制,等待片刻后重试
5. **查看控制台**:打开开发者工具查看详细的错误信息
### 多数据库同步问题
同步到多个数据库时:
- **部分失败**:如果一个数据库失败,其他数据库仍会继续同步
- **独立通知**:每个数据库同步都会显示自己的结果通知
- **检查 frontmatter**:验证所有 NotionID 字段都存在且正确(如 `NotionID-blog``NotionID-portfolio`
## 获取帮助
如果问题依然存在,你可以在 GitHub 上[提交一个 Issue](https://github.com/jxpeng98/obsidian-to-NotionNext/issues),并附上详细的错误信息和你的操作步骤,我会尽快帮助你。
你也可以通过 `Ctrl+Shift+I` (Windows/Linux) 或 `Cmd+Option+I` (Mac) 打开 Obsidian 的开发者工具在控制台Console中查看是否有与 NotionNext 插件相关的错误日志,这对于定位问题非常有帮助。
### 提交 Bug 报告时应包含的信息
1. **错误消息**:复制通知或控制台中的确切错误消息
2. **控制台日志**:包含开发者控制台中的相关日志(查找 `[AutoSync]``[Settings]``[Plugin]` 前缀)
3. **重现步骤**:描述问题发生时你正在做什么
4. **配置信息**说明你使用的数据库格式NotionNext、普通或自定义
5. **设置信息**:注明是否启用了自动同步以及配置的延迟时间

6
docs/zh/06-changelog.md Normal file
View File

@@ -0,0 +1,6 @@
---
title: 更新日志
description: Obsidian to NotionNext 的版本更新与变更记录
---
欢迎来到 Obsidian to NotionNext 的更新日志!这里会记录自 `2.7.0` 版本起的所有更新、改进以及问题修复,方便你快速了解插件的演进情况。

8
docs/zh/07-roadmap.md Normal file
View File

@@ -0,0 +1,8 @@
---
title: 路线图
description: Obsidian to NotionNext 的规划功能与未来改进
---
- [ ] 自动同步:支持按时间间隔或内容变更自动同步笔记。
- [ ] 附件支持:允许将 Obsidian 笔记中的附件一同上传到 Notion。
- [ ] 关联属性:实现将 Obsidian 链接映射到 Notion 的 relation 属性。

27
docs/zh/index.md Normal file
View File

@@ -0,0 +1,27 @@
---
title: 介绍
description: 使用 Notion API 将文件分享到任何 Notion 数据库
order: 0
---
# Obsidian to NotionNext
在这份文档中,你将找到关于如何设置和使用 Obsidian to NotionNext 插件的指南和说明。这款插件可以让你使用 Notion API 将你的 Obsidian 笔记直接分享到 Notion 数据库。
本指南将引导你完成设置 Obsidian to NotionNext 插件的全过程。
[开始使用](./01-getting-started.md)
[安装插件](./02-installation.md)
[配置数据库](./03-configuration.md)
[同步笔记](./04-sync.md)
[问题排查](./05-troubleshooting.md)
---
[更新日志](./06-changelog.md)
[路线图](./07-roadmap.md)

View File

@@ -41,7 +41,6 @@ const ctx = await esbuild.context({
"@codemirror/view",
...builtins,
],
platform: "node",
format: "cjs",
target: "es2016",
logLevel: "info",

View File

@@ -1,7 +1,7 @@
{
"id": "share-to-notionnext",
"name": "Share to NotionNext",
"version": "2.4.1",
"version": "2.7.0",
"minAppVersion": "0.0.1",
"description": "Shares obsidian md file to notion with notion api for NotionNext web deploy, originally created by EasyChris/obsidian-to-notion.",
"author": "EasyChris, jxpeng98",

View File

@@ -1,6 +1,6 @@
{
"name": "share-to-notionnext",
"version": "2.4.1",
"version": "2.7.0",
"type": "module",
"description": "Share files to any Notion database using the Notion API, originally created by EasyChris/obsidian-to-notion.",
"main": "main.js",
@@ -10,7 +10,7 @@
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "",
"author": "Jiaxin PENG",
"license": "GNU GPLv3",
"devDependencies": {
"@types/node": "^20.5.7",
@@ -24,10 +24,8 @@
"typescript": "5.2.2"
},
"dependencies": {
"@jxpeng98/martian": "^1.2.7",
"@jxpeng98/martian": "^1.3.1",
"https-proxy-agent": "^7.0.2",
"node-fetch": "^3.3.2",
"process": "^0.11.10",
"remark-math": "^6.0.0",
"yaml": "^2.3.4",
"yaml-front-matter": "^4.1.1"

2213
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -8,10 +8,42 @@ export const I18n: {[key: string]:any} = {
ja,
};
export const I18nConfig = (lang: string): any => {
return I18n[lang];
};
class I18nManager {
private currentLanguage: string;
const storedLanguage = window.localStorage.getItem("language");
constructor() {
this.currentLanguage = this.detectLanguage();
}
export const i18nConfig = I18n[storedLanguage || window.navigator.language.split('-')[0] || "en"];
// return the language to use
private detectLanguage(): string {
const storedLanguage = window.localStorage.getItem("language");
if (storedLanguage && this.isLanguageSupported(storedLanguage)) {
console.log(`Using stored language: ${storedLanguage}`);
return storedLanguage;
}
const browserLanguage = window.navigator.language.split("-")[0];
if (this.isLanguageSupported(browserLanguage)) {
console.log(`Using browser language: ${browserLanguage}`);
return browserLanguage;
}
// Default to English if no match is found
console.log("Using default language: en");
return "en";
}
private isLanguageSupported(lang: string): boolean {
return Object.prototype.hasOwnProperty.call(I18n, lang);
}
// Get the i18n configuration for the current language
public getConfig(): any {
return I18n[this.currentLanguage];
}
}
export const i18nManager = new I18nManager();
export const i18nConfig = i18nManager.getConfig();

View File

@@ -1,82 +1,116 @@
export const en = {
databaseFormat: "Database Format",
databaseFormatDesc: "Select the database format you want to sync to NotionNext or General",
databaseFormatDesc: "Select the database format to sync to: NotionNext or General.",
databaseNext: "NotionNext",
databaseGeneral: "General",
databaseCustom: "Custom",
databaseFullName: "Database Full Name",
databaseFullNameDesc: "Please give a full name for your database",
databaseFullNameText: "Enter your database full name",
databaseAbbreviateName: "Database Abbreviate Name",
databaseAbbreviateNameDesc: "Please give a nick name for your database",
databaseAbbreviateNameText: "Enter your database nick name",
ribbonIcon: "Share to NotionNext",
GeneralSetting: "General information Settings",
databaseFullNameDesc: "Set a full name for your database.",
databaseFullNameText: "Enter your database's full name",
databaseAbbreviateName: "Abbreviated Name",
databaseAbbreviateNameDesc: "Set a shorter, abbreviated name for your database.",
databaseAbbreviateNameText: "Enter your database's abbreviated name",
ribbonIcon: "Sync to NotionNext",
GeneralSetting: "General Settings",
CommandID: "share-to-notionnext",
CommandName: "Share to NotionNext Database",
CommandName: "Sync to NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "Share to Notion General Database",
CommandNameGeneral: "Sync to General Database",
NotionNextButton: "NotionNext Sync",
NotionNextButtonDesc: "Open this option, Sync to NotionNext command will be displayed in the command palette (default: ON)",
NotionNextButtonDesc: "Enables the 'Sync to NotionNext' command in the command palette (default: on).",
NotionNextSettingHeader: "NotionNext Database Settings",
NotionAPI: "Notion API Token",
NotionAPIDesc: "Generate from https://www.notion.so/my-integrations",
NotionAPIDesc: "Get yours from notion.so/my-integrations.",
NotionAPIText: "Enter your Notion API Token",
DatabaseID: "Database ID",
DatabaseIDDesc: "Collect from the top-right Share --> Publish",
DatabaseIDDesc: "Find this in your Notion page's top-right 'Share' menu.",
DatabaseIDText: "Enter your Database ID",
BannerUrl: "Banner url (optional)",
BannerUrl: "Banner URL (optional)",
BannerUrlDesc:
"Default is empty, if you want to show a banner, please enter the url (like: https://abc.com/b.png)",
BannerUrlText: "Enter your banner url",
NotionUser: "Notion ID (username, optional)",
"Leave empty for no banner. If you want a banner, enter an image URL (e.g., https://abc.com/b.png).",
BannerUrlText: "Enter your banner URL",
NotionUser: "Notion Username (optional)",
NotionUserDesc:
"Collect from share link likes:https://username.notion.site. Your notion id is [username]",
NotionUserText: "Enter your notion ID",
NotionLinkDisplay: "Notion Link Display",
NotionLinkDisplayDesc: "Default is ON, if you want to hide the link in the front matter, please turn it off",
"If your site is username.notion.site, your username is [username].",
NotionUserText: "Enter your Notion username",
NotionLinkDisplay: "Display Notion Link",
NotionLinkDisplayDesc: "If disabled, the Notion link won't be added to the front matter after syncing (default: on).",
AutoCopyNotionLink: "Auto-copy Notion Link",
AutoCopyNotionLinkDesc: "Automatically copy the Notion page link to the clipboard after syncing (default: on).",
AutoSync: "Auto Sync",
AutoSyncDesc: "Automatically syncs changes to Notion when the file's frontmatter or content is modified. Supports creating and updating pages.",
AutoSyncFrontmatterKey: "Auto Sync Frontmatter Key",
AutoSyncFrontmatterKeyDesc: "Specify the frontmatter key used to list the databases this file should auto-sync to (defaults to 'autosync-database').",
AutoSyncDelay: "Auto Sync Delay (seconds)",
AutoSyncDelayDesc: "Delay in seconds to wait before syncing after a change. Prevents excessive syncs (default: 5s, min: 2s).",
AutoSyncDelayText: "Enter delay in seconds",
NotionGeneralSettingHeader: "General Notion Database Settings",
NotionGeneralButton: "Notion General Sync",
NotionGeneralButtonDesc: "Open this option, Sync to Notion General Database command will be displayed in the command palette (default: ON)",
NotionTagButton: "Notion Tags Sync",
NotionTagButtonDesc: "Sync Tags to Notion General Database (default: ON)",
NotionCustomTitle: "Customise title property",
NotionCustomTitleDesc: "Modify the column name of the Notion database (default: OFF)",
NotionCustomTitleName: "Preferred title name",
NotionCustomTitleNameDesc: "Enter the preferred title name for the first column of the Notion database (default: title)",
NotionCustomTitleText: "Enter the name",
NotionCustomValues: "Customise values property",
NotionCustomValuesDesc: "Modify the column name of the Notion databaseone per line",
NotionCustomValuesText: "Enter all properties that you want to sync",
NotYetFinish: "Not finished. This function will be available in the next version",
PlaceHolder: "Enter database Name",
"notion-logo": "Share to NotionNext",
"sync-preffix": "Sync to ",
"sync-success": "success",
"sync-fail": "failed",
"open-notion": "Please open the file that needs to be synchronized",
NotionGeneralButton: "General Database Sync",
NotionGeneralButtonDesc: "Enables the 'Sync to General Database' command in the command palette (default: on).",
NotionTagButton: "Sync Tags",
NotionTagButtonDesc: "Sync Obsidian tags to the Notion database (default: on).",
NotionCustomTitle: "Custom Title Property",
NotionCustomTitleDesc: "Customize the title property's name in your Notion database (default: off).",
NotionCustomTitleName: "Custom Title Property Name",
NotionCustomTitleNameDesc: "Enter the custom name for the title property of your Notion database (default: 'title').",
NotionCustomTitleText: "Enter the property name",
NotionCustomValues: "Custom Properties",
NotionCustomValuesDesc: "Define custom properties to sync to your Notion database, one per line.",
NotionCustomValuesText: "Enter all properties you want to sync",
NotYetFinish: "This feature will be available in a future version.",
PlaceHolder: "Enter database name",
"notion-logo": "Sync to NotionNext",
"sync-preffix": "📄",
"sync-success": "Successfully synced to NotionNext:\n",
"sync-fail": "Failed to sync to NotionNext:\n",
"open-notion": "Please open a file to sync first.",
"config-secrets-notion-api":
"Please set up the notion API in the settings tab.",
"Please configure your Notion API key in the plugin settings.",
"config-secrets-database-id":
"Please set up the database id in the settings tab.",
"Please configure your Database ID in the plugin settings.",
"set-tags-fail":
"Set tags fail,please check the frontmatter of the file or close the tag switch in the settings tab.",
"Failed to set tags. Check the frontmatter or disable tag sync in settings.",
NNonMissing:
"The 'NNon' property is missing in the settings. Please set it up.",
"The 'NNon' property is not set. Please select a NotionNext database in settings.",
"set-api-id":
"Please set up the notion API and database ID in the settings tab.",
"Please configure your Notion API key and Database ID in the plugin settings.",
NotionCustomSettingHeader: "Notion Custom Database Settings",
NotionCustomButton: "Notion Customised command switch",
NotionCustomButtonDesc: "Open this option, Sync to Notion Customised Database command will be displayed in the command palette",
NotionCustomButton: "Enable Custom Database Command",
NotionCustomButtonDesc: "If enabled, the 'Sync to Custom Database' command appears in the command palette.",
CustomPropertyName: "Property Name",
CustomPropertyFirstColumn: "Title Column",
CustomPropertyFirstColumnDesc: "The title of the page, must be the first property",
CustomPropertyFirstColumn: "Title Property Name",
CustomPropertyFirstColumnDesc: "The page title. This must be the first property in the list.",
CustomProperty: "Property",
AddCustomProperty: "Add Custom Property",
AddNewProperty: "Add New Property",
AddNewPropertyDesc: "Add new property match with your notion database",
CopyErrorMessage: "Auto copy failed, please copy it manually",
BlockUploaded: "All blocks uploaded",
ExtraBlockUploaded: "Extra blocks uploaded",
CheckConsole: "Check the console for more information \n opt+cmd+i/ctrl+shift+i",
AddNewPropertyDesc: "Add a new property that matches a property in your Notion database.",
CopyErrorMessage: "Auto-copy failed. Please copy the link manually.",
BlockUploaded: "All content blocks uploaded successfully.",
ExtraBlockUploaded: "Additional blocks uploaded successfully.",
CheckConsole: "For more details, open the developer console (opt+cmd+i or ctrl+shift+i).",
SettingsMigrated: "✨ Settings updated! Auto-Sync is now available. Check the settings to learn more.",
AutoSyncNoNotionID: "🆕 Auto-sync: First upload to Notion",
AutoSyncMissingDatabaseList: "⚠️ Auto-sync skipped: Add `{key}: [database_name]` to your frontmatter to specify target databases.",
AutoSyncMultipleSync: "🔄 Auto-sync: Syncing to {count} database(s)...",
AutoSyncFailed: "Auto-sync to {database} failed: {error}",
AutoSyncError: "Auto-sync for {filename} failed: {error}",
"reach-mobile-limit": "Block limit (100) reached. For unlimited blocks, please use the desktop version.",
StartUpload: "Starting upload for {filename}...",
AddNewDatabase: "Add New Database",
AddNewDatabaseDesc: "Add a new database configuration",
AddNewDatabaseTooltip: "Add New Database",
EditDatabase: "Edit Database",
Preview: "Preview",
DatabaseFormatLabel: "Database Format",
DatabaseFullNameLabel: "Database Full Name",
DatabaseAbbreviateNameLabel: "Abbreviated Name",
NotionAPILabel: "Notion API Key",
DatabaseIDLabel: "Database ID",
ToggleAPIKeyVisibility: "Toggle API Key Visibility",
CopyAPIKey: "Copy API Key",
APIKeyCopied: "API key copied to clipboard.",
ToggleDatabaseIDVisibility: "Toggle Database ID Visibility",
CopyDatabaseID: "Copy Database ID",
DatabaseIDCopied: "Database ID copied to clipboard.",
AddNewDatabaseModal: "Add New Database",
}

View File

@@ -1,74 +1,109 @@
export const ja = {
databaseFormat: "データベース形式",
databaseFormatDesc: "同期したいデータベース形式を選択してください",
databaseFormatDesc: "同期先のデータベース形式を選択してくださいNotionNext または 一般)。",
databaseNext: "NotionNext",
databaseGeneral: "一般的なNotion",
databaseGeneral: "一般",
databaseCustom: "カスタム",
databaseFullName: "データベースの全称",
databaseFullNameDesc: "データベースの全称を入力してください",
databaseFullNameDesc: "データベースのフルネームを設定します。",
databaseFullNameText: "データベースの全称を入力",
databaseAbbreviateName: "データベースの略称",
databaseAbbreviateNameDesc: "データベースの略称を入力してください",
databaseAbbreviateNameDesc: "データベースの略称を設定します。",
databaseAbbreviateNameText: "データベースの略称を入力",
ribbonIcon: "NotionNextで共有",
ribbonIcon: "NotionNextへ同期",
GeneralSetting: "一般設定",
CommandID: "share-to-notionnext",
CommandName: "NotionNextデータベースに共有",
CommandName: "NotionNextへ同期",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "一般的なNotionデータベースに共有",
CommandNameGeneral: "一般データベースへ同期",
NotionNextButton: "NotionNext同期",
NotionNextButtonDesc: "このオプションを開くと、NotionNext同期コマンドがコマンドパレットに表示されます(デフォルト:ON",
NotionNextButtonDesc: "有効にすると、コマンドパレットに「NotionNext同期」が表示されます(デフォルト:オン)。",
NotionNextSettingHeader: "NotionNextデータベース設定",
NotionAPI: "Notion API トークン",
NotionAPIDesc: "https://www.notion.so/my-integrations から生成してください",
NotionAPIDesc: "notion.so/my-integrations から取得します。",
NotionAPIText: "Notion API トークンを入力",
DatabaseID: "データベースID",
DatabaseIDDesc: "右上共有 --> 公開から取得してください",
DatabaseIDDesc: "Notionページの右上共有」メニューから取得します。",
DatabaseIDText: "データベースIDを入力",
BannerUrl: "バナーURL任意",
BannerUrlDesc: "デフォルトは空白です。バナーを表示したい場合は、URLを入力してくださいhttps://abc.com/b.png",
BannerUrl: "バナーURL任意",
BannerUrlDesc: "空のままにするとバナーは表示されません。表示するには画像のURLを入力してくださいhttps://abc.com/b.png",
BannerUrlText: "バナーのURLを入力",
NotionUser: "Notion IDユーザー名任意)",
NotionUserDesc: "共有リンクから取得https://username.notion.site。Notion IDは[username]です",
NotionUserText: "Notion IDを入力",
NotionUser: "Notionユーザー名任意)",
NotionUserDesc: "共有リンクが `username.notion.site` の場合、Notionユーザー名は `[username]` です",
NotionUserText: "Notionユーザー名を入力",
NotionLinkDisplay: "Notionリンク表示",
NotionLinkDisplayDesc: "デフォルトはONです。front matterにリンクを非表示にしたい場合は、オフにしてください",
NotionGeneralSettingHeader: "一般的なNotionデータベース設定",
NotionGeneralButton: "一般的なNotion同期",
NotionGeneralButtonDesc: "このオプションを開くと、一般的なNotionデータベース同期コマンドがコマンドパレットに表示されますデフォルトON",
NotionTagButton: "Notionタグ同期",
NotionTagButtonDesc: "タグを一般的なNotionデータベースに同期デフォルトON",
NotionCustomTitle: "タイトルのカスタマイズ",
NotionCustomTitleDesc: "Notionデータベースの列名を変更デフォルトOFF",
NotionCustomTitleName: "希望のタイトル名",
NotionCustomTitleNameDesc: "Notionデータベースの最初の列のための希望のタイトル名を入力デフォルトtitle",
NotionCustomTitleText: "名前を入力",
NotionCustomValues: "値のカスタマイズ",
NotionCustomValuesDesc: "Notionデータベースの列名を変更、1行に1つ",
NotionLinkDisplayDesc: "デフォルトで有効。無効にすると、同期後にfront matterへNotionリンクが追加されません。",
AutoCopyNotionLink: "Notionリンクを自動コピー",
AutoCopyNotionLinkDesc: "同期完了後、Notionページのリンクをクリップボードに自動コピーしますデフォルトオン",
AutoSync: "自動同期",
AutoSyncDesc: "ファイルの内容frontmatterまたは本文が変更されると、自動でNotionに同期します。新規作成と更新の両方に対応。",
AutoSyncFrontmatterKey: "自動同期 frontmatter キー",
AutoSyncFrontmatterKeyDesc: "自動同期の対象となるデータベースをリストアップするための frontmatterキーを設定しますデフォルトautosync-database",
AutoSyncDelay: "自動同期の遅延(秒",
AutoSyncDelayDesc: "変更が検知されてから同期を開始するまでの遅延時間。同期の頻発を防ぎますデフォルト5秒、最小2秒",
AutoSyncDelayText: "遅延秒数を入力",
NotionGeneralSettingHeader: "一般Notionデータベース設定",
NotionGeneralButton: "一般データベース同期",
NotionGeneralButtonDesc: "有効にすると、コマンドパレットに「一般データベースへ同期」が表示されます(デフォルト:オン)。",
NotionTagButton: "タグを同期",
NotionTagButtonDesc: "ObsidianのタグをNotionデータベースに同期しますデフォルトオン。",
NotionCustomTitle: "タイトルプロパティをカスタム",
NotionCustomTitleDesc: "Notionデータベースのタイトル列の名前をカスタマイズしますデフォルトオフ。",
NotionCustomTitleName: "カスタムタイトル名",
NotionCustomTitleNameDesc: "Notionデータベースのタイトル列に使用するカスタム名を入力してくださいデフォルト「title」。",
NotionCustomTitleText: "プロパティ名を入力",
NotionCustomValues: "カスタムプロパティ",
NotionCustomValuesDesc: "Notionデータベースに同期するカスタムプロパティを1行に1つずつ定義します。",
NotionCustomValuesText: "同期したいすべてのプロパティを入力",
NotYetFinish: "未完了。この機能はのバージョンで利用可能になります",
NotYetFinish: "この機能は将来のバージョンで利用可能になります",
PlaceHolder: "データベース名を入力",
"notion-logo": "NotionNextで共有",
"sync-success": "NotionNextへの同期に成功\n",
"sync-fail": "NotionNextへの同期に失敗:\n",
"open-notion": "同期が必要なファイルを開いてください",
"config-secrets-notion-api": "設定タブでNotion APIを設定してください",
"config-secrets-database-id": "設定タブでデータベースIDを設定してください",
"set-tags-fail": "タグの設定に失敗。ファイルのfrontmatterを確認するか、設定タブでタグのスイッチをオフにしてください",
NNonMissing: "設定に 'NNon' プロパティがありません。設定してください",
"set-api-id": "設定タブでNotion APIおよびデータベースIDを設定してください",
"notion-logo": "NotionNextへ同期",
"sync-preffix": "📄",
"sync-success": "NotionNextへの同期が成功しました。\n",
"sync-fail": "NotionNextへの同期に失敗しました。\n",
"open-notion": "同期するファイルを先に開いてください",
"config-secrets-notion-api": "プラグイン設定でNotion APIキーを設定してください",
"config-secrets-database-id": "プラグイン設定でデータベースIDを設定してください",
"set-tags-fail": "タグの設定に失敗しました。frontmatterを確認するか、設定でタグ同期を無効にしてください",
NNonMissing: "'NNon'プロパティが設定されていません。設定でNotionNextデータベースを選択してください",
"set-api-id": "プラグイン設定でNotion APIキーとデータベースIDを設定してください。",
NotionCustomSettingHeader: "Notionカスタムデータベース設定",
NotionCustomButton: "Notionカスタマイズコマンドの切り替え",
NotionCustomButtonDesc: "このオプションを開くと、Notionカスタムデータベース同期コマンドがコマンドパレットに表示されます",
CustomPropertyName: "カスタムプロパティ名",
CustomPropertyFirstColumn: "最初の列のカスタムプロパティ名",
CustomPropertyFirstColumnDesc: "最初の列のカスタムプロパティ名を入力してください",
CustomProperty: "カスタムプロパティ",
NotionCustomButton: "カスタムデータベースコマンドを有効化",
NotionCustomButtonDesc: "有効にすると、「カスタムデータベース同期コマンドがコマンドパレットに表示されます",
CustomPropertyName: "プロパティ名",
CustomPropertyFirstColumn: "タイトルプロパティ名",
CustomPropertyFirstColumnDesc: "ページのタイトル。これはリストの最初のプロパティである必要があります。",
CustomProperty: "プロパティ",
AddCustomProperty: "カスタムプロパティを追加",
AddNewProperty: "新しいプロパティを追加",
AddNewPropertyDesc: "新しいプロパティを追加してください",
CopyErrorMessage: "自動コピーに失敗しました",
BlockUploaded: "ブロックアップロードされました",
ExtraBlockUploaded: "追加ブロックアップロードされました",
CheckConsole: "詳細情報を確認するには、コンソールを開いてください \n opt+cmd+i/ctrl+shift+i",
AddNewPropertyDesc: "Notionデータベースのプロパティと一致する新しいプロパティを追加します。",
CopyErrorMessage: "リンクの自動コピーに失敗しました。手動でコピーしてください。",
BlockUploaded: "すべてのブロックアップロードました",
ExtraBlockUploaded: "追加ブロックアップロードました",
CheckConsole: "詳細は、開発者コンソール(opt+cmd+i または ctrl+shift+i)で確認できます。",
SettingsMigrated: "✨ 設定が更新されました!自動同期が利用可能です。詳細は設定画面をご確認ください。",
AutoSyncNoNotionID: "🆕 自動同期Notionへ初めてアップロードします",
AutoSyncMissingDatabaseList: "⚠️ 自動同期をスキップfrontmatterに `{key}: [データベース名]` を追加して同期先を指定してください。",
AutoSyncMultipleSync: "🔄 自動同期:{count}個のデータベースに同期しています...",
AutoSyncFailed: "{database}への自動同期に失敗しました:{error}",
AutoSyncError: "{filename}の自動同期に失敗しました:{error}",
"reach-mobile-limit": "ブロック上限100に達しました。ブロック数に制限のないデスクトップ版をご利用ください。",
StartUpload: "{filename} のアップロードを開始します...",
AddNewDatabase: "新しいデータベースを追加",
AddNewDatabaseDesc: "新しいデータベース構成を追加",
AddNewDatabaseTooltip: "新しいデータベースを追加",
EditDatabase: "データベースを編集",
Preview: "プレビュー",
DatabaseFormatLabel: "データベース形式",
DatabaseFullNameLabel: "データベースの全称",
DatabaseAbbreviateNameLabel: "データベースの略称",
NotionAPILabel: "Notion API キー",
DatabaseIDLabel: "データベース ID",
ToggleAPIKeyVisibility: "API キーの表示を切り替え",
CopyAPIKey: "API キーをコピー",
APIKeyCopied: "APIキーをクリップボードにコピーしました。",
ToggleDatabaseIDVisibility: "データベース ID の表示を切り替え",
CopyDatabaseID: "データベース ID をコピー",
DatabaseIDCopied: "データベースIDをクリップボードにコピーしました。",
AddNewDatabaseModal: "新しいデータベースを追加",
};

View File

@@ -1,77 +1,111 @@
export const zh = {
databaseFormat: "数据库格式",
databaseFormatDesc: "选择你想要同步的数据库格式Next 或者 普通",
databaseFormatDesc: "选择同步的目标数据库格式NotionNext 或 通用",
databaseNext: "NotionNext",
databaseGeneral: "通",
databaseGeneral: "通",
databaseCustom: "自定义",
databaseFullName: "数据库全",
databaseFullNameDesc: "给你的数据库一个全",
databaseFullNameText: "输入的数据库全",
databaseFullName: "数据库全",
databaseFullNameDesc: "数据库设置一个全",
databaseFullNameText: "输入的数据库全",
databaseAbbreviateName: "数据库简称",
databaseAbbreviateNameDesc: "给你的数据库一个简称",
databaseAbbreviateNameText: "输入的数据库简称",
ribbonIcon: "分享到 NotionNext",
databaseAbbreviateNameDesc: "数据库设置一个简称",
databaseAbbreviateNameText: "输入的数据库简称",
ribbonIcon: "同步到 NotionNext",
GeneralSetting: "通用设置",
CommandID: "share-to-notionnext",
CommandName: "分享到 NotionNext",
CommandName: "同步到 NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "分享到 Notion 普通数据库",
CommandNameGeneral: "同步到通用数据库",
NotionNextButton: "NotionNext 同步",
NotionNextButtonDesc: "打开此选项NotionNext 同步将显示在命令面板中(默认开)",
NotionNextSettingHeader: "NotionNext 数据库参数设置",
NotionNextButtonDesc: "启用后,命令面板中将显示“同步到 NotionNext”命令(默认开",
NotionNextSettingHeader: "NotionNext 数据库设置",
NotionAPI: "Notion API 令牌",
NotionAPIDesc: "从 https://www.notion.so/my-integrations 生成",
NotionAPIText: "输入的 Notion API 令牌",
NotionAPIDesc: "从 notion.so/my-integrations 获取",
NotionAPIText: "输入的 Notion API 令牌",
DatabaseID: "数据库 ID",
DatabaseIDDesc: "右上角的分享 --> 发布中获取",
DatabaseIDText: "输入的数据库 ID",
DatabaseIDDesc: "可从 Notion 页面右上角的分享”菜单中获取",
DatabaseIDText: "输入的数据库 ID",
BannerUrl: "封面图片地址(可选)",
BannerUrlDesc:
"默认为空,如果你想显示封面图片请输入图片地址例如https://abc.com/b.png",
BannerUrlText: "输入的封面图片地址",
NotionUser: "Notion ID用户名可选)",
"留空则不显示。如需封面请输入图片地址例如https://abc.com/b.png",
BannerUrlText: "输入的封面图片地址",
NotionUser: "Notion 用户名可选)",
NotionUserDesc:
"数据库分享链接类似https://username.notion.site/。你的 Notion ID 是 [username]",
NotionUserText: "输入的 Notion ID",
NotionLinkDisplay: "Notion 链接显示",
NotionLinkDisplayDesc: "默认开启,如果你不想在front matter中显示链接,请关闭",
NotionGeneralSettingHeader: "普通 Notion 数据库设置",
NotionGeneralButton: "普通数据库同步",
NotionGeneralButtonDesc: "打开此选项,同步到普通数据库命令将显示在命令面板中(默认:开)",
NotionTagButton: "标签同步开关",
NotionTagButtonDesc: "将标签同步到普通数据库(默认:开)",
NotionCustomTitle: "修改 Notion 数据库表头开关",
NotionCustomTitleDesc: "自定义Notion 数据库第一列表头名(默认:关",
NotionCustomTitleName: "想要修改的表头名",
NotionCustomTitleNameDesc: "输入你想要修改的notion数据库的表头名默认title",
NotionCustomTitleText: "输入表头名",
NotionCustomValues: "自定义Notion 数据库表头",
NotionCustomValuesDesc: "自定义Notion 数据库表头,每行一个",
NotionCustomValuesText: "输入你想要同步的所有属性",
NotYetFinish: "未完成。此功能将在之后版本中提供",
"分享链接username.notion.site你的 Notion 用户名即为 [username]",
NotionUserText: "输入的 Notion 用户名",
NotionLinkDisplay: "显示 Notion 链接",
NotionLinkDisplayDesc: "默认开启。关闭后,同步成功时 frontmatter 中不会出现 Notion 链接",
AutoCopyNotionLink: "自动复制 Notion 链接",
AutoCopyNotionLinkDesc: "同步后自动将 Notion 链接复制到剪贴板(默认开启)",
AutoSync: "自动同步",
AutoSyncDesc: "当文档的 frontmatter 或内容修改时,将自动同步到 Notion支持新建和更新",
AutoSyncFrontmatterKey: "自动同步 Frontmatter 键名",
AutoSyncFrontmatterKeyDesc: "设置用于指定自动同步数据库列表的 frontmatter 键名(默认为 autosync-database",
AutoSyncDelay: "自动同步延迟(秒",
AutoSyncDelayDesc: "文档修改后,等待指定秒数再触发自动同步,以避免频繁操作(默认 5 秒,最少 2 秒)",
AutoSyncDelayText: "输入延迟秒数",
NotionGeneralSettingHeader: "通用 Notion 数据库设置",
NotionGeneralButton: "通用数据库同步",
NotionGeneralButtonDesc: "启用后,命令面板中将显示“同步到通用数据库”命令(默认开启)",
NotionTagButton: "标签同步",
NotionTagButtonDesc: "将 Obsidian 标签同步到 Notion 数据库(默认开启)",
NotionCustomTitle: "自定义标题属性",
NotionCustomTitleDesc: "自定义 Notion 数据库中标题列的名称(默认关闭)",
NotionCustomTitleName: "自定义标题名称",
NotionCustomTitleNameDesc: "为 Notion 数据库的标题列设置一个自定义名称(默认为 title",
NotionCustomTitleText: "输入标题名称",
NotionCustomValues: "自定义属性",
NotionCustomValuesDesc: "自定义同步到 Notion 数据库的属性,每行一个。",
NotionCustomValuesText: "输入所有你希望同步的属性",
NotYetFinish: "此功能将在未来版本中提供",
PlaceHolder: "输入数据库名称",
"notion-logo": "分享到NotionNext",
"sync-success": "同步到NotionNext成功:\n",
"sync-fail": "同步到NotionNext失败: \n",
"open-file": "请打开需要同步的文件",
"config-secrets-notion-api": "请在插件设置中添加notion API",
"config-secrets-database-id": "请在插件设置中添加database id",
"notion-logo": "同步到 NotionNext",
"sync-preffix": "📄",
"sync-success": "成功同步到 NotionNext\n",
"sync-fail": "同步到 NotionNext 失败:\n",
"open-file": "请先打开要同步的文件。",
"config-secrets-notion-api": "请在插件设置中配置 Notion API 密钥。",
"config-secrets-database-id": "请在插件设置中配置数据库 ID。",
"set-tags-fail":
"设置标签失败,请检查文件的frontmatter,或者在插件设置中关闭设置tags开关",
NNonMissing: "未设置'NNon'属性请在插件设置中选择NotionNext数据库。",
"set-api-id": "请在插件设置中设置notion API和database ID",
"标签设置失败请检查 frontmatter 或在设置中关闭标签同步。",
NNonMissing: "未设置 'NNon' 属性,请在插件设置中选择一个 NotionNext 数据库。",
"set-api-id": "请在插件设置中配置 Notion API 和数据库 ID",
NotionCustomSettingHeader: "Notion 自定义数据库设置",
NotionCustomButton: "Notion 自定义数据库同步命令开关",
NotionCustomButtonDesc: "打开此选项,同步到自定义数据库命令将显示在命令面板中",
NotionCustomButton: "启用自定义数据库同步命令",
NotionCustomButtonDesc: "启用后,“同步到自定义数据库”的命令将出现在命令面板中",
CustomPropertyName: "自定义属性名",
CustomPropertyFirstColumn: "第一列属性",
CustomPropertyFirstColumnDesc: "第一列必须为标题属性",
CustomPropertyFirstColumn: "标题属性",
CustomPropertyFirstColumnDesc: "第一列必须为标题属性",
CustomProperty: "自定义属性",
AddCustomProperty: "添加自定义属性",
AddNewProperty: "添加新属性",
AddNewPropertyDesc: "添加一个Notion数据库匹配的新属性",
CopyErrorMessage: "复制链接失败,请手动复制",
BlockUploaded: "所有内容已成功上传",
ExtraBlockUploaded: "额外内容已成功上传",
CheckConsole: "opt+cmd+i/ctrl+shift+i\n打开控制台查看更多信息",
AddNewPropertyDesc: "添加一个与您 Notion 数据库中的属性相匹配的新属性",
CopyErrorMessage: "自动复制链接失败,请手动复制",
BlockUploaded: "所有块已上传成功",
ExtraBlockUploaded: "额外块已上传成功",
CheckConsole: "opt+cmd+i / ctrl+shift+i 打开控制台查看详情。",
SettingsMigrated: "✨ 插件设置已更新!新增自动同步功能,详情请查看设置。",
AutoSyncNoNotionID: "🆕 自动同步:首次上传到 Notion",
AutoSyncMissingDatabaseList: "⚠️ 自动同步已跳过:请在 frontmatter 中添加 \"{key}\" 以指定目标数据库。",
AutoSyncMultipleSync: "🔄 自动同步:正在同步到 {count} 个数据库...",
AutoSyncFailed: "同步到 {database} 失败:{error}",
AutoSyncError: "同步 {filename} 失败:{error}",
StartUpload: "开始上传 {filename}...",
AddNewDatabase: "添加新数据库",
AddNewDatabaseDesc: "添加新的数据库配置",
AddNewDatabaseTooltip: "添加新数据库",
EditDatabase: "编辑数据库",
Preview: "预览",
DatabaseFormatLabel: "数据库格式",
DatabaseFullNameLabel: "数据库全名",
DatabaseAbbreviateNameLabel: "数据库简称",
NotionAPILabel: "Notion API 密钥",
DatabaseIDLabel: "数据库 ID",
ToggleAPIKeyVisibility: "切换 API 密钥可见性",
CopyAPIKey: "复制 API 密钥",
APIKeyCopied: "API 密钥已复制到剪贴板。",
ToggleDatabaseIDVisibility: "切换数据库 ID 可见性",
CopyDatabaseID: "复制数据库 ID",
DatabaseIDCopied: "数据库 ID 已复制到剪贴板。",
AddNewDatabaseModal: "添加新数据库",
}

View File

@@ -1,10 +1,10 @@
import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting } from "obsidian";
import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TFile, EventRef } from "obsidian";
import { addIcons } from 'src/ui/icon';
import { Upload2NotionGeneral } from "src/upload/upload_general/Upload2NotionGeneral";
import { Upload2NotionNext } from "src/upload/upload_next/Upload2NotionNext";
import { i18nConfig } from "src/lang/I18n";
import ribbonCommands from "src/commands/NotionCommands";
import { ObsidianSettingTab, PluginSettings, DEFAULT_SETTINGS, DatabaseDetails } from "src/ui/settingTabs";
import { uploadCommandNext, uploadCommandGeneral, uploadCommandCustom } from "src/upload/uploadCommand";
import { DEFAULT_AUTO_SYNC_DATABASE_KEY, parseAutoSyncDatabaseList, resolveAutoSyncKey } from "src/utils/frontmatter";
// Remember to rename these classes and interfaces!
@@ -13,14 +13,31 @@ export default class ObsidianSyncNotionPlugin extends Plugin {
settings: PluginSettings;
commands: ribbonCommands;
app: App;
modifyEventRef: EventRef | null = null;
autoSyncTimeout: number | null = null;
private syncingFiles: Set<string> = new Set();
private lastFrontmatterCache: Map<string, any> = new Map();
private lastContentHashCache: Map<string, string> = new Map();
async onload() {
await this.loadSettings();
// Log loaded settings for debugging
console.log('[Plugin] Loaded settings:', {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
bannerUrl: this.settings.bannerUrl ? 'set' : 'empty',
notionUser: this.settings.notionUser ? 'set' : 'empty',
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
this.commands = new ribbonCommands(this);
addIcons();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon(
this.addRibbonIcon(
"notion-logo",
i18nConfig.ribbonIcon,
async (evt: MouseEvent) => {
@@ -38,21 +55,134 @@ export default class ObsidianSyncNotionPlugin extends Plugin {
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new ObsidianSettingTab(this.app, this));
// Setup auto sync listener
this.setupAutoSync();
}
onunload() {
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
this.lastFrontmatterCache.clear();
this.lastContentHashCache.clear();
}
async loadSettings() {
const loadedData = await this.loadData();
// Merge loaded data with defaults, ensuring all fields exist
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
loadedData || {}
);
// Ensure critical fields have valid values
if (typeof this.settings.autoSync !== 'boolean') {
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== 'number' || this.settings.autoSyncDelay < 2) {
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.NotionLinkDisplay !== 'boolean') {
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (typeof this.settings.autoCopyNotionLink !== 'boolean') {
this.settings.autoCopyNotionLink = DEFAULT_SETTINGS.autoCopyNotionLink;
}
if (typeof this.settings.autoSyncFrontmatterKey !== 'string') {
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
// Ensure databaseDetails exists
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== 'object') {
this.settings.databaseDetails = {};
}
// Save settings if any migration was needed
const needsSave = !loadedData ||
loadedData.autoSync === undefined ||
loadedData.autoSyncDelay === undefined ||
loadedData.NotionLinkDisplay === undefined ||
loadedData.autoCopyNotionLink === undefined ||
loadedData.autoSyncFrontmatterKey === undefined;
if (needsSave) {
const migratedFields = [];
if (!loadedData) {
console.log('[Settings] First-time setup, creating default settings');
} else {
if (loadedData.autoSync === undefined) migratedFields.push('autoSync');
if (loadedData.autoSyncDelay === undefined) migratedFields.push('autoSyncDelay');
if (loadedData.NotionLinkDisplay === undefined) migratedFields.push('NotionLinkDisplay');
if (loadedData.autoCopyNotionLink === undefined) migratedFields.push('autoCopyNotionLink');
console.log('[Settings] Migrating settings, adding fields:', migratedFields.join(', '));
}
await this.saveSettings();
// Notify user about settings migration (only for existing users, not first-time setup)
if (loadedData && Object.keys(loadedData).length > 0 && migratedFields.length > 0) {
new Notice(i18nConfig.SettingsMigrated, 6000);
console.log('[Settings] Migration notice shown to user');
}
}
}
async saveSettings() {
// Validate settings before saving
this.validateSettings();
await this.saveData(this.settings);
console.log('[Settings] Settings saved successfully', {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
autoSyncFrontmatterKey: this.settings.autoSyncFrontmatterKey,
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
}
validateSettings() {
// Ensure all required fields have valid values
if (typeof this.settings.autoSync !== 'boolean') {
console.warn('[Settings] Invalid autoSync value, resetting to default');
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== 'number' || this.settings.autoSyncDelay < 2) {
console.warn('[Settings] Invalid autoSyncDelay value, resetting to default');
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.NotionLinkDisplay !== 'boolean') {
console.warn('[Settings] Invalid NotionLinkDisplay value, resetting to default');
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (typeof this.settings.autoCopyNotionLink !== 'boolean') {
console.warn('[Settings] Invalid autoCopyNotionLink value, resetting to default');
this.settings.autoCopyNotionLink = DEFAULT_SETTINGS.autoCopyNotionLink;
}
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== 'object') {
console.warn('[Settings] Invalid databaseDetails, resetting to empty object');
this.settings.databaseDetails = {};
}
if (typeof this.settings.autoSyncFrontmatterKey !== 'string' || this.settings.autoSyncFrontmatterKey.trim().length === 0) {
console.warn('[Settings] Invalid autoSyncFrontmatterKey, resetting to default');
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
} else {
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
}
getAutoSyncFrontmatterKey(): string {
return resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
async addDatabaseDetails(dbDetails: DatabaseDetails) {
@@ -82,8 +212,261 @@ export default class ObsidianSyncNotionPlugin extends Plugin {
await this.saveSettings();
}
setupAutoSync() {
// Remove existing listener if any
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
// Only setup if autoSync is enabled
if (!this.settings.autoSync) {
return;
}
// Listen for file modifications
this.modifyEventRef = this.app.vault.on('modify', async (file: TFile) => {
// Only process markdown files
if (!(file instanceof TFile) || file.extension !== 'md') {
return;
}
// Debounce: clear existing timeout
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
// Set a new timeout to trigger sync after user-configured delay (in seconds)
const delayMs = (this.settings.autoSyncDelay || 2) * 1000;
this.autoSyncTimeout = window.setTimeout(async () => {
await this.autoSyncFile(file);
}, delayMs);
});
}
onlyNotionIDChanged(oldFrontmatter: any, newFrontmatter: any): boolean {
// Get all keys from both frontmatters
const oldKeys = Object.keys(oldFrontmatter || {});
const newKeys = Object.keys(newFrontmatter || {});
// Filter out NotionID-related keys and Obsidian internal keys
const isIgnoredKey = (key: string) => {
return key.startsWith('NotionID-') ||
key === 'NotionID' ||
key === 'position'; // Obsidian's internal metadata
};
const oldNonNotionKeys = oldKeys.filter(k => !isIgnoredKey(k)).sort();
const newNonNotionKeys = newKeys.filter(k => !isIgnoredKey(k)).sort();
// If number of non-NotionID keys changed, something else changed
if (oldNonNotionKeys.length !== newNonNotionKeys.length) {
console.log('[AutoSync] Frontmatter: Key count changed:', oldNonNotionKeys.length, '->', newNonNotionKeys.length);
return false;
}
// Check if any non-NotionID key values changed
for (const key of oldNonNotionKeys) {
if (!newNonNotionKeys.includes(key)) {
console.log('[AutoSync] Frontmatter: Key removed or added:', key);
return false; // Key was removed or added
}
// Deep comparison for the value
const oldValue = JSON.stringify(oldFrontmatter[key]);
const newValue = JSON.stringify(newFrontmatter[key]);
if (oldValue !== newValue) {
console.log('[AutoSync] Frontmatter: Value changed for key "' + key + '"');
console.log(' Old:', oldValue.substring(0, 100));
console.log(' New:', newValue.substring(0, 100));
return false; // Value changed
}
}
// Check if any new non-NotionID keys were added
for (const key of newNonNotionKeys) {
if (!oldNonNotionKeys.includes(key)) {
console.log('[AutoSync] Frontmatter: New key added:', key);
return false; // New key was added
}
}
// Only NotionID fields changed (or nothing in frontmatter changed)
return true;
}
simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash.toString();
}
async autoSyncFile(file: TFile) {
// Check if file is already being synced
if (this.syncingFiles.has(file.path)) {
console.log(`[AutoSync] File ${file.path} is already being synced, skipping`);
return;
}
try {
this.syncingFiles.add(file.path);
// Get file's frontmatter
const frontMatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
if (!frontMatter) {
console.log(`[AutoSync] No frontmatter found in ${file.path}`);
return;
}
// Get file content hash for comparison
const content = await this.app.vault.read(file);
const contentHash = this.simpleHash(content);
const lastContentHash = this.lastContentHashCache.get(file.path);
// Check if only NotionID fields changed (to avoid sync loops)
const lastFrontmatter = this.lastFrontmatterCache.get(file.path);
if (lastFrontmatter && lastContentHash) {
const frontmatterOnlyNotionIDChanged = this.onlyNotionIDChanged(lastFrontmatter, frontMatter);
const contentUnchanged = contentHash === lastContentHash;
console.log(`[AutoSync] Change analysis for ${file.basename}:`, {
frontmatterOnlyNotionIDChanged,
contentUnchanged,
frontmatterHasRealChanges: !frontmatterOnlyNotionIDChanged,
contentChanged: !contentUnchanged,
willSync: !(frontmatterOnlyNotionIDChanged && contentUnchanged)
});
// Only skip sync if BOTH conditions are true:
// 1. Frontmatter only has NotionID changes (no real user changes)
// 2. Content is completely unchanged
if (frontmatterOnlyNotionIDChanged && contentUnchanged) {
console.log(`[AutoSync] Only NotionID updated (from sync), content unchanged - skipping auto sync`);
// Update cache even when skipping, so next comparison uses the current state
this.lastFrontmatterCache.set(file.path, { ...frontMatter });
this.lastContentHashCache.set(file.path, contentHash);
return;
}
if (!contentUnchanged) {
console.log(`[AutoSync] Content changed - will sync`);
} else if (!frontmatterOnlyNotionIDChanged) {
console.log(`[AutoSync] Frontmatter changed - will sync`);
}
}
const autoSyncKey = this.getAutoSyncFrontmatterKey();
const autoSyncTargets = parseAutoSyncDatabaseList(frontMatter[autoSyncKey]);
// If no autosync-database field specified
if (autoSyncTargets.length === 0) {
// Check if file has any existing NotionID (meaning it was synced before)
const hasExistingNotionID = Object.keys(frontMatter).some(key =>
key.startsWith('NotionID-') || key === 'NotionID'
);
if (hasExistingNotionID) {
// User likely forgot to add autosync-database - show a notice
const message = i18nConfig.AutoSyncMissingDatabaseList.replace('{key}', autoSyncKey);
new Notice(message, 8000);
console.log(`[AutoSync] File ${file.path} has NotionID but missing autosync-database - showing notice`);
}
// Silently skip files without NotionID (new files that don't need auto-sync)
return;
}
const dbByShortName = new Map<string, DatabaseDetails>();
for (const key in this.settings.databaseDetails) {
const dbDetails = this.settings.databaseDetails[key];
dbByShortName.set(dbDetails.abName.toLowerCase(), dbDetails);
}
const foundDatabases: Array<{ dbDetails: DatabaseDetails, notionId: string | undefined }> = [];
const unresolvedTargets: string[] = [];
for (const target of autoSyncTargets) {
const lookupKey = target.toLowerCase();
const dbDetails = dbByShortName.get(lookupKey);
if (!dbDetails) {
unresolvedTargets.push(target);
continue;
}
const notionIDKey = `NotionID-${dbDetails.abName}`;
// Include database even if no NotionID exists (for first-time upload)
foundDatabases.push({
dbDetails,
notionId: frontMatter[notionIDKey] ? String(frontMatter[notionIDKey]) : undefined
});
}
if (unresolvedTargets.length > 0) {
console.log(`[AutoSync] Frontmatter auto sync targets not found in settings: ${unresolvedTargets.join(", ")}`);
}
// If no valid databases found in settings, skip
if (foundDatabases.length === 0) {
console.log(`[AutoSync] No matching databases found in settings for ${file.path}, skipping auto sync`);
return;
}
// Notify user about multiple syncs if applicable
if (foundDatabases.length > 1) {
const message = i18nConfig.AutoSyncMultipleSync.replace('{count}', String(foundDatabases.length));
new Notice(message, 3000);
console.log(`[AutoSync] Found ${foundDatabases.length} database targets in ${file.path}`);
}
// Sync to all found databases
for (const { dbDetails, notionId } of foundDatabases) {
const isFirstSync = !notionId;
console.log(`[AutoSync] ${new Date().toISOString()} Auto syncing ${file.basename} to ${dbDetails.fullName} (${dbDetails.abName})${isFirstSync ? ' [First Upload]' : ''}`);
try {
// Trigger appropriate upload command based on database format
if (dbDetails.format === 'next') {
await uploadCommandNext(this, this.settings, dbDetails, this.app);
} else if (dbDetails.format === 'general') {
await uploadCommandGeneral(this, this.settings, dbDetails, this.app);
} else if (dbDetails.format === 'custom') {
await uploadCommandCustom(this, this.settings, dbDetails, this.app);
}
} catch (error) {
console.error(`[AutoSync] Error syncing to ${dbDetails.fullName}:`, error);
const message = i18nConfig.AutoSyncFailed
.replace('{database}', dbDetails.fullName)
.replace('{error}', error.message);
new Notice(message, 5000);
}
}
// After sync completes, update cache with the latest frontmatter (including updated NotionIDs)
// Wait a bit for metadata cache to update
window.setTimeout(async () => {
const updatedFrontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
const updatedContent = await this.app.vault.read(file);
const updatedHash = this.simpleHash(updatedContent);
if (updatedFrontmatter) {
this.lastFrontmatterCache.set(file.path, { ...updatedFrontmatter });
this.lastContentHashCache.set(file.path, updatedHash);
console.log(`[AutoSync] Cached updated frontmatter and content hash for ${file.path}`);
}
}, 500);
} catch (error) {
console.error(`[AutoSync] Error syncing file ${file.path}:`, error);
const message = i18nConfig.AutoSyncError
.replace('{filename}', file.basename)
.replace('{error}', error.message);
new Notice(message);
} finally {
this.syncingFiles.delete(file.path);
}
}
}

View File

@@ -93,7 +93,7 @@ export class EditModal extends SettingModal {
display(): void {
this.containerEl.addClass("edit-modal");
this.titleEl.setText('Edit Database');
this.titleEl.setText(i18nConfig.EditDatabase);
let { contentEl } = this;
contentEl.empty();
@@ -245,8 +245,8 @@ export class EditModal extends SettingModal {
}
new Setting(containerEl)
.setName("Add New Property")
.setDesc("Click to add a new property")
.setName(i18nConfig.AddNewProperty)
.setDesc(i18nConfig.AddNewPropertyDesc)
.addButton(button => {
return button
.setButtonText('Add')

View File

@@ -19,7 +19,7 @@ export class PreviewModal extends Modal {
display(): void {
this.containerEl.addClass('preview-modal')
this.titleEl.setText('Preview')
this.titleEl.setText(i18nConfig.Preview)
let { contentEl } = this;
@@ -27,21 +27,21 @@ export class PreviewModal extends Modal {
const dbFormatEl = new Setting(previewEl)
dbFormatEl
.setName('Database Format')
.setName(i18nConfig.DatabaseFormatLabel)
.addText(text => text
.setValue(this.dbDetails.format)
.setDisabled(true));
const dbFullEl = new Setting(previewEl)
dbFullEl
.setName('Database Full Name')
.setName(i18nConfig.DatabaseFullNameLabel)
.addText(text => text
.setValue(this.dbDetails.fullName)
.setDisabled(true));
const dbAbbrEl = new Setting(previewEl)
dbAbbrEl
.setName('Database Abbreviate Name')
.setName(i18nConfig.DatabaseAbbreviateNameLabel)
.addText(text => text
.setValue(this.dbDetails.abName)
.setDisabled(true));
@@ -49,12 +49,12 @@ export class PreviewModal extends Modal {
// Setting for toggle and copy buttons
new Setting(previewEl)
.setName('Notion API Key')
.setName(i18nConfig.NotionAPILabel)
.addExtraButton((button: ExtraButtonComponent) => {
let isApiKeyVisible = false;
return button
.setTooltip('Toggle API Key Visibility')
.setTooltip(i18nConfig.ToggleAPIKeyVisibility)
.setIcon('eye')
.onClick(() => {
isApiKeyVisible = !isApiKeyVisible;
@@ -73,11 +73,11 @@ export class PreviewModal extends Modal {
apiKeySetting
.addExtraButton((button: ExtraButtonComponent) => {
return button
.setTooltip('Copy API Key')
.setTooltip(i18nConfig.CopyAPIKey)
.setIcon('clipboard')
.onClick(() => {
navigator.clipboard.writeText(this.dbDetails.notionAPI)
new Notice('API Key copied to clipboard');
new Notice(i18nConfig.APIKeyCopied);
});
});
@@ -86,12 +86,12 @@ export class PreviewModal extends Modal {
new Setting(previewEl)
.setName('Database ID')
.setName(i18nConfig.DatabaseIDLabel)
.addExtraButton((button: ExtraButtonComponent) => {
let isDbIdVisible = false;
return button
.setTooltip('Toggle Database ID Visibility')
.setTooltip(i18nConfig.ToggleDatabaseIDVisibility)
.setIcon('eye')
.onClick(() => {
@@ -108,11 +108,11 @@ export class PreviewModal extends Modal {
dbIdSetting
.addExtraButton((button: ExtraButtonComponent) => {
return button
.setTooltip('Copy Database ID')
.setTooltip(i18nConfig.CopyDatabaseID)
.setIcon('clipboard')
.onClick(() => {
navigator.clipboard.writeText(this.dbDetails.databaseID)
new Notice('Database ID copied to clipboard');
new Notice(i18nConfig.DatabaseIDCopied);
});
});

View File

@@ -56,7 +56,7 @@ export class SettingModal extends Modal {
display(): void {
this.containerEl.addClass("settings-modal");
this.titleEl.setText('Add new database');
this.titleEl.setText(i18nConfig.AddNewDatabaseModal);
// create the dropdown button to select the database format
let { contentEl } = this;

View File

@@ -5,6 +5,7 @@ import { SettingModal } from "./settingModal";
import { PreviewModal } from "./PreviewModal";
import { EditModal } from "./EditModal";
import { DeleteModal } from "./DeleteModal";
import { DEFAULT_AUTO_SYNC_DATABASE_KEY } from "src/utils/frontmatter";
export interface PluginSettings {
NextButton: boolean;
@@ -13,6 +14,10 @@ export interface PluginSettings {
bannerUrl: string;
notionUser: string;
NotionLinkDisplay: boolean;
autoCopyNotionLink: boolean;
autoSync: boolean;
autoSyncDelay: number;
autoSyncFrontmatterKey: string;
proxy: string;
GeneralButton: boolean;
tagButton: boolean;
@@ -49,6 +54,10 @@ export const DEFAULT_SETTINGS: PluginSettings = {
bannerUrl: "",
notionUser: "",
NotionLinkDisplay: true,
autoCopyNotionLink: true,
autoSync: false,
autoSyncDelay: 5,
autoSyncFrontmatterKey: DEFAULT_AUTO_SYNC_DATABASE_KEY,
proxy: "",
GeneralButton: true,
tagButton: true,
@@ -67,6 +76,7 @@ export const DEFAULT_SETTINGS: PluginSettings = {
export class ObsidianSettingTab extends PluginSettingTab {
plugin: ObsidianSyncNotionPlugin;
databaseEl: HTMLDivElement;
autoSyncDelayContainer: HTMLElement | null = null;
constructor(app: App, plugin: ObsidianSyncNotionPlugin) {
super(app, plugin);
@@ -87,14 +97,57 @@ export class ObsidianSettingTab extends PluginSettingTab {
this.createSettingEl(containerEl, i18nConfig.NotionLinkDisplay, i18nConfig.NotionLinkDisplayDesc, 'toggle', i18nConfig.NotionLinkDisplay, this.plugin.settings.NotionLinkDisplay, 'NotionLinkDisplay')
this.createSettingEl(containerEl, i18nConfig.AutoCopyNotionLink, i18nConfig.AutoCopyNotionLinkDesc, 'toggle', i18nConfig.AutoCopyNotionLink, this.plugin.settings.autoCopyNotionLink, 'autoCopyNotionLink')
this.createSettingEl(containerEl, i18nConfig.AutoSync, i18nConfig.AutoSyncDesc, 'toggle', i18nConfig.AutoSync, this.plugin.settings.autoSync, 'autoSync')
new Setting(containerEl)
.setName(i18nConfig.AutoSyncFrontmatterKey)
.setDesc(i18nConfig.AutoSyncFrontmatterKeyDesc)
.addText((text) =>
text
.setPlaceholder(DEFAULT_AUTO_SYNC_DATABASE_KEY)
.setValue(this.plugin.settings.autoSyncFrontmatterKey ?? "")
.onChange(async (value) => {
this.plugin.settings.autoSyncFrontmatterKey = value;
await this.plugin.saveSettings();
})
);
// Auto Sync Delay setting - only visible when autoSync is enabled
this.autoSyncDelayContainer = containerEl.createDiv();
const delaySetting = new Setting(this.autoSyncDelayContainer)
.setName(i18nConfig.AutoSyncDelay)
.setDesc(i18nConfig.AutoSyncDelayDesc)
.addText((text) =>
text
.setPlaceholder(i18nConfig.AutoSyncDelayText)
.setValue(String(this.plugin.settings.autoSyncDelay))
.onChange(async (value) => {
const delay = parseFloat(value);
if (!isNaN(delay) && delay >= 2) {
this.plugin.settings.autoSyncDelay = delay;
await this.plugin.saveSettings();
} else if (!isNaN(delay) && delay < 2) {
// If user enters less than 2 seconds, set it to 2
this.plugin.settings.autoSyncDelay = 2;
await this.plugin.saveSettings();
text.setValue('2');
}
})
);
// Set initial visibility
this.updateAutoSyncDelayVisibility();
// add new button
new Setting(containerEl)
.setName("Add New Database")
.setDesc("Add New Database")
.setName(i18nConfig.AddNewDatabase)
.setDesc(i18nConfig.AddNewDatabaseDesc)
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip("Add New Database")
.setTooltip(i18nConfig.AddNewDatabaseTooltip)
.setIcon("plus")
.onClick(async () => {
let modal = new SettingModal(this.app, this.plugin, this);
@@ -151,6 +204,13 @@ export class ObsidianSettingTab extends PluginSettingTab {
element.style.alignItems = "center";
}
// Update visibility of autoSyncDelay setting based on autoSync toggle
public updateAutoSyncDelayVisibility() {
if (this.autoSyncDelayContainer) {
this.autoSyncDelayContainer.style.display = this.plugin.settings.autoSync ? "block" : "none";
}
}
// function to add one setting element in the setting tab.
public createSettingEl(containerEl: HTMLElement, name: string, desc: string, type: string, placeholder: string, holderValue: any, settingsKey: string) {
if (type === 'password') {
@@ -178,6 +238,12 @@ export class ObsidianSettingTab extends PluginSettingTab {
this.plugin.settings[settingsKey] = value; // Update the plugin settings directly
await this.plugin.saveSettings();
await this.plugin.commands.updateCommand();
// If autoSync setting changed, update the listener and visibility
if (settingsKey === 'autoSync') {
this.plugin.setupAutoSync();
this.updateAutoSyncDelayVisibility();
}
})
);
} else if (type === 'text') {
@@ -304,4 +370,3 @@ export class ObsidianSettingTab extends PluginSettingTab {
}
}

628
src/upload/Upload2Notion.ts Normal file
View File

@@ -0,0 +1,628 @@
import { App, TFile } from "obsidian";
import { markdownToBlocks } from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
import { LIMITS, paragraph } from "@jxpeng98/martian";
import MyPlugin from "src/main";
import { DatabaseDetails } from "../ui/settingTabs";
import { updateYamlInfo } from "./updateYaml";
import { UploadBase, NotionPageResponse } from "./common/UploadBase";
export type DatasetType = "general" | "next" | "custom";
interface BaseSyncRequest {
dataset: DatasetType;
markdown: string;
nowFile: TFile;
app: App;
}
interface GeneralSyncRequest extends BaseSyncRequest {
dataset: "general";
title: string;
cover: string;
tags: string[];
}
interface NextSyncRequest extends BaseSyncRequest {
dataset: "next";
title: string;
emoji: string;
cover: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
}
interface CustomSyncRequest extends BaseSyncRequest {
dataset: "custom";
cover: string;
customValues: Record<string, string>;
}
export type SyncRequest =
| GeneralSyncRequest
| NextSyncRequest
| CustomSyncRequest;
interface GeneralParams {
title: string;
cover?: string;
tags: string[];
childArr: any[];
notionId?: string;
}
interface NextParams {
title: string;
emoji: string;
cover?: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
childArr: any[];
notionId?: string;
}
interface CustomParams {
cover?: string;
customValues: Record<string, string>;
childArr: any[];
notionId?: string;
}
export class Upload2Notion extends UploadBase {
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
super(plugin, dbDetails);
}
async sync(request: SyncRequest): Promise<NotionPageResponse> {
const startedAt = Date.now();
let response: NotionPageResponse;
switch (request.dataset) {
case "general":
response = await this.handleGeneral(request);
break;
case "next":
response = await this.handleNext(request);
break;
case "custom":
response = await this.handleCustom(request);
break;
default:
throw new Error(`Unsupported dataset type: ${(request as any).dataset}`);
}
if (response.response && response.response.status === 200) {
await updateYamlInfo(
request.markdown,
request.nowFile,
response.data,
request.app,
this.plugin,
this.dbDetails,
);
} else {
console.log(`[Upload2Notion] Sync failed`, response.data);
}
return response;
}
private async handleGeneral(request: GeneralSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling general dataset`, {
cover: request.cover,
tags: request.tags,
});
const blocks = this.buildBlocks(request.markdown, {
notionLimits: {truncate: false},
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "General dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
tagCount: request.tags?.length ?? 0,
});
return this.upsertGeneral({
title: request.title,
cover: request.cover,
tags: request.tags || [],
childArr: blocks,
notionId,
});
}
private async handleNext(request: NextSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling next dataset`, {
type: request.type,
slug: request.slug,
category: request.category,
});
const blocks = this.buildBlocks(request.markdown, {
notionLimits: {truncate: false},
});
this.splitRichTextParagraphs(blocks);
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Next dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
hasEmoji: !!request.emoji,
tags: request.tags || [],
});
return this.upsertNext({
title: request.title,
emoji: request.emoji,
cover: request.cover,
tags: request.tags || [],
type: request.type,
slug: request.slug,
stats: request.stats,
category: request.category,
summary: request.summary,
password: request.password,
favicon: request.favicon,
datetime: request.datetime,
childArr: blocks,
notionId,
});
}
private async handleCustom(request: CustomSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling custom dataset`, {
customKeys: Object.keys(request.customValues || {}),
});
const blocks = this.buildBlocks(request.markdown, {
strictImageUrls: true,
notionLimits: {truncate: false},
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Custom dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
customValueKeys: Object.keys(request.customValues || {}),
});
return this.upsertCustom({
cover: request.cover,
customValues: request.customValues,
childArr: blocks,
notionId,
});
}
private buildBlocks(markdown: string, options: Record<string, unknown>): any[] {
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const content = yamlContent.__content;
const blocks = markdownToBlocks(content, options);
this.debugLog("Upload2Notion", "Converted markdown to blocks", {
blockCount: blocks.length,
firstBlockTypes: blocks.slice(0, 5).map((block: any) => block?.type),
options,
});
return blocks;
}
private getNotionId(app: App, nowFile: TFile): string | undefined {
const frontMatter = app.metadataCache.getFileCache(nowFile)?.frontmatter;
if (!frontMatter) {
this.debugLog("Upload2Notion", "No frontmatter found when resolving Notion ID", {
filePath: nowFile.path,
});
return undefined;
}
const {abName} = this.dbDetails;
const notionIDKey = `NotionID-${abName}`;
const notionId = frontMatter[notionIDKey];
return notionId ? String(notionId) : undefined;
}
private splitRichTextParagraphs(blocks: any[]): void {
blocks.forEach((block, index) => {
if (
block.type === "paragraph" &&
block.paragraph.rich_text.length > LIMITS.RICH_TEXT_ARRAYS
) {
console.log(`[Upload2Notion] Splitting rich text paragraph`, {
index,
length: block.paragraph.rich_text.length,
});
const paragraphChunks = this.chunkArray<any>(block.paragraph.rich_text, 100);
const newParagraphBlocks = paragraphChunks.map((chunk) => paragraph(chunk));
blocks.splice(index, 1, ...newParagraphBlocks);
}
});
}
private chunkArray<T>(items: T[], size: number): T[][] {
const result: T[][] = [];
for (let i = 0; i < items.length; i += size) {
result.push(items.slice(i, i + size));
}
return result;
}
private async upsertGeneral(params: GeneralParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting general page", {
title: params.title,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
notionIdExisting: params.notionId ?? null,
tagList: params.tags,
});
if (params.notionId) {
console.log(`[Upload2Notion] Deleting existing Notion page`, {
notionId: params.notionId,
});
await this.deletePage(params.notionId);
}
const body = this.buildGeneralBody({
title: params.title,
tags: params.tags,
firstChunk,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private async upsertNext(params: NextParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting NotionNext page", {
title: params.title,
type: params.type,
slug: params.slug,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
hasEmoji: !!params.emoji,
notionIdExisting: params.notionId ?? null,
});
if (params.notionId) {
await this.deletePage(params.notionId);
}
const body = this.buildNextBody({
firstChunk,
title: params.title,
emoji: params.emoji,
tags: params.tags,
type: params.type,
slug: params.slug,
stats: params.stats,
category: params.category,
summary: params.summary,
password: params.password,
favicon: params.favicon,
datetime: params.datetime,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private async upsertCustom(params: CustomParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting custom page", {
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
notionIdExisting: params.notionId ?? null,
customValueKeys: Object.keys(params.customValues || {}),
});
if (params.notionId) {
await this.deletePage(params.notionId);
}
const body = this.buildCustomBody({
customValues: params.customValues,
firstChunk,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private buildGeneralBody(params: {title: string; tags: string[]; firstChunk: any[]}): any {
const {
databaseID,
customTitleButton,
customTitleName,
tagButton,
} = this.dbDetails;
return {
parent: {
database_id: databaseID,
},
properties: {
[customTitleButton ? customTitleName : "title"]: {
title: [
{
text: {
content: params.title,
},
},
],
},
...(tagButton
? {
tags: {
multi_select:
params.tags && params.tags.length > 0
? params.tags.map((tag) => ({name: tag}))
: [],
},
}
: {}),
},
children: params.firstChunk,
};
}
private buildNextBody(params: {
firstChunk: any[];
title: string;
emoji: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
}): any {
const {databaseID} = this.dbDetails;
const pageProperties: any = {
parent: {
database_id: databaseID,
},
properties: {
title: {
title: [
{
text: {
content: params.title,
},
},
],
},
type: {
select: {
name: params.type || "Post",
},
},
status: {
select: {
name: params.stats || "Draft",
},
},
category: {
select: {
name: params.category || "Obsidian",
},
},
password: {
rich_text: [
{
text: {
content: params.password || "",
},
},
],
},
icon: {
rich_text: [
{
text: {
content: params.favicon || "",
},
},
],
},
date: {
date: {
start: params.datetime || new Date().toISOString(),
},
},
},
};
if (params.tags && params.tags.length > 0) {
pageProperties.properties.tags = {
multi_select: params.tags.map((tag) => ({name: tag})),
};
}
if (params.emoji) {
pageProperties.icon = {
emoji: params.emoji,
};
}
if (params.slug) {
pageProperties.properties.slug = {
rich_text: [
{
text: {
content: params.slug,
},
},
],
};
}
if (params.summary) {
pageProperties.properties.summary = {
rich_text: [
{
text: {
content: params.summary,
},
},
],
};
}
return {
...pageProperties,
children: params.firstChunk,
};
}
private buildCustomBody(params: {
customValues: Record<string, string>;
firstChunk: any[];
}): any {
const {customProperties, databaseID} = this.dbDetails;
const properties: { [key: string]: any } = {};
if (customProperties) {
customProperties.forEach(({customName, customType}) => {
if (params.customValues[customName] !== undefined) {
const propertyValue = this.buildCustomProperty(customName, customType, params.customValues);
if (propertyValue !== undefined) {
properties[customName] = propertyValue;
}
}
});
}
return {
parent: {
database_id: databaseID,
},
properties,
children: params.firstChunk,
};
}
private buildCustomProperty(customName: string, customType: string, customValues: Record<string, any>) {
const value = customValues[customName] || "";
switch (customType) {
case "title":
return {
title: [
{
text: {
content: value,
},
},
],
};
case "rich_text":
return {
rich_text: [
{
text: {
content: value || "",
},
},
],
};
case "date":
return {
date: {
start: value || new Date().toISOString(),
},
};
case "number":
return {
number: Number(value),
};
case "phone_number":
return {
phone_number: value,
};
case "email":
return {
email: value,
};
case "url":
return {
url: value,
};
case "files":
return {
files: Array.isArray(value)
? value.map((url: string) => ({
name: url,
type: "external",
external: {
url,
},
}))
: [
{
name: value,
type: "external",
external: {
url: value,
},
},
],
};
case "checkbox":
return {
checkbox: Boolean(value) || false,
};
case "select":
return {
select: {
name: value,
},
};
case "multi_select":
return {
multi_select: Array.isArray(value)
? value.map((item: string) => ({name: item}))
: [{name: value}],
};
case "relation":
return {
relation: Array.isArray(value)
? value.map((item: string) => ({id: item}))
: [{id: value}],
};
default:
return undefined;
}
}
}

View File

@@ -0,0 +1,248 @@
import { Notice, requestUrl } from "obsidian";
import MyPlugin from "src/main";
import { DatabaseDetails } from "../../ui/settingTabs";
import { i18nConfig } from "../../lang/I18n";
export interface NotionPageResponse {
response: any;
data: any;
}
interface PreparedBlocks {
firstChunk: any[];
extraChunks: any[][];
}
export abstract class UploadBase {
protected plugin: MyPlugin;
protected dbDetails: DatabaseDetails;
protected constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails;
}
async deletePage(notionID: string) {
const {notionAPI} = this.dbDetails;
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: "",
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Deleting Notion page ${notionID}`),
);
}
protected prepareBlocks(childArr: any[]): PreparedBlocks {
this.stripCodeAnnotations(childArr);
const childArrLength = childArr.length;
if (childArrLength <= 100) {
this.debugLog("UploadBase", "Blocks fit into a single request", {
totalBlocks: childArrLength,
});
return {
firstChunk: childArr,
extraChunks: [],
};
}
const extraChunks: any[][] = [];
for (let i = 100; i < childArr.length; i += 100) {
extraChunks.push(childArr.slice(i, i + 100));
}
this.debugLog("UploadBase", "Blocks split into multiple chunks", {
totalBlocks: childArrLength,
firstChunkSize: 100,
extraChunkCount: extraChunks.length,
lastChunkSize: extraChunks[extraChunks.length - 1].length,
});
return {
firstChunk: childArr.slice(0, 100),
extraChunks,
};
}
protected applyCover(body: any, cover?: string) {
if (cover) {
body.cover = {
type: "external",
external: {
url: cover,
},
};
} else if (!body.cover && this.plugin.settings.bannerUrl) {
body.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl,
},
};
}
this.debugLog("UploadBase", "Cover applied to payload", {
chosenCover: body.cover?.external?.url ?? null,
defaultBannerUsed: !cover && !!this.plugin.settings.bannerUrl,
});
}
protected async resolveCoverForUpdate(cover?: string): Promise<string | undefined> {
if (cover) {
this.debugLog("UploadBase", "Existing cover retained for update", {
cover,
});
return cover;
}
const databaseCover = await this.fetchDatabaseCover();
return databaseCover ?? undefined;
}
protected async submitPage(body: any, extraChunks: any[][]): Promise<NotionPageResponse> {
const {notionAPI} = this.dbDetails;
const startedAt = Date.now();
const response = await requestUrl({
url: `https://api.notion.com/v1/pages`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(body),
throw: false,
}).catch((error) =>
this.handleRequestError(error, "Creating Notion page"),
);
const data = await response.json;
this.debugLog("UploadBase", "Page creation response received", {
status: response.status,
durationMs: Date.now() - startedAt,
notionUrl: data?.url ?? null,
pageId: data?.id ?? null,
});
if (response.status !== 200) {
new Notice(`Error ${data.status}: ${data.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${data.message}`);
} else {
if (extraChunks.length > 0) {
await this.appendExtraBlocks(data.id, extraChunks);
}
}
return {response, data};
}
private stripCodeAnnotations(childArr: any[]) {
childArr.forEach((block: any) => {
if (block.type === "code") {
block.code.rich_text.forEach((item: any) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
});
}
});
}
private async appendExtraBlocks(pageId: string, extraChunks: any[][]) {
const {notionAPI} = this.dbDetails;
for (let i = 0; i < extraChunks.length; i++) {
const chunk = extraChunks[i];
const extraBlocks = {
children: chunk,
};
const extraResponse = await requestUrl({
url: `https://api.notion.com/v1/blocks/${pageId}/children`,
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(extraBlocks),
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Appending blocks to page ${pageId}`),
);
const extraData: any = await extraResponse.json;
if (extraResponse.status !== 200) {
new Notice(`Error ${extraData.status}: ${extraData.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${pageId}`);
if (i === extraChunks.length - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${pageId}`);
new Notice(`${i18nConfig["BlockUploaded"]} page: ${pageId}`, 5000);
}
}
}
}
private async fetchDatabaseCover(): Promise<string | null> {
const {notionAPI, databaseID} = this.dbDetails;
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: "GET",
headers: {
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Fetching database ${databaseID}`),
);
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
}
return null;
}
protected debugLog(context: string, message: string, payload?: Record<string, unknown>): void {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
protected maskValue(value?: string, visibleChars = 4): string | undefined {
if (!value) {
return value;
}
if (value.length <= visibleChars * 2) {
return `${value.slice(0, visibleChars)}***`;
}
return `${value.slice(0, visibleChars)}***${value.slice(-visibleChars)}`;
}
private handleRequestError(error: unknown, context: string): never {
const message = error instanceof Error && error.message
? error.message
: String(error);
console.error(`[UploadBase] ${context} failed`, {
message,
error,
});
throw new Error(
`${context} failed: ${message}. Please check your network connection or proxy settings.`,
);
}
}

View File

@@ -1,6 +1,6 @@
import { App, Notice } from "obsidian";
import { i18nConfig } from "../../lang/I18n";
import { DatabaseDetails } from "../../ui/settingTabs";
import {App, Notice} from "obsidian";
import {i18nConfig} from "../../lang/I18n";
import {DatabaseDetails} from "../../ui/settingTabs";
export async function getNowFileMarkdownContentCustom(
app: App,
@@ -24,6 +24,7 @@ export async function getNowFileMarkdownContentCustom(
.map(property => property.customName);
// Extract custom values from the front matter based on the names
// Only collect data 'Relation' should be handled separately in the function buildBodyString
customPropertyNames.forEach(propertyName => {
if (FileCache.frontmatter && FileCache.frontmatter[propertyName] !== undefined) {
customValues[propertyName] = FileCache.frontmatter[propertyName];
@@ -31,11 +32,15 @@ export async function getNowFileMarkdownContentCustom(
});
// Check if any of the customProperties has a customType of 'title'
const titleProperty = dbDetails.customProperties.find(property => property.customType === 'title');
const titleProperty = dbDetails.customProperties
.find(property => property.customType === 'title');
// If a 'title' type property exists, use the file's basename as its value
if (titleProperty) {
customValues[titleProperty.customName] = nowFile.basename; // Use 'basename' for the file name without extension
customValues[titleProperty.customName] =
(FileCache.frontmatter && FileCache.frontmatter[titleProperty.customName]) ?
FileCache.frontmatter[titleProperty.customName] : // use the front matter value if it exists
nowFile.basename; // Use 'basename' for the file name without extension
}
} catch (error) {

View File

@@ -2,6 +2,7 @@ import { App, Notice, TFile } from "obsidian";
import ObsidianSyncNotionPlugin from "../main";
import { DatabaseDetails } from "../ui/settingTabs";
import { i18nConfig } from "src/lang/I18n";
import { ensureAutoSyncDatabaseEntry } from "src/utils/frontmatter";
export async function updateYamlInfo(
yamlContent: string,
@@ -17,6 +18,7 @@ export async function updateYamlInfo(
const { abName } = dbDetails
const notionIDKey = `NotionID-${abName}`;
const linkKey = `link-${abName}`;
const autoSyncKey = plugin.getAutoSyncFrontmatterKey();
if (notionUser !== "") {
// replace url str "www" to notionID
@@ -33,12 +35,21 @@ export async function updateYamlInfo(
// add new notionID and link
yamlContent[notionIDKey] = id;
(NotionLinkDisplay) ? yamlContent[linkKey] = url : null;
// ensure auto sync database list contains current short name
yamlContent[autoSyncKey] = ensureAutoSyncDatabaseEntry(
yamlContent[autoSyncKey],
abName
);
});
// copy url to clipboard only if autoCopyNotionLink is enabled
if (plugin.settings.autoCopyNotionLink) {
try {
await navigator.clipboard.writeText(url)
await navigator.clipboard.writeText(url);
} catch (error) {
console.log(error)
console.log(error);
new Notice(`${i18nConfig.CopyErrorMessage}`);
}
}
}

View File

@@ -1,13 +1,38 @@
import {i18nConfig} from "../lang/I18n";
import {App, Notice} from "obsidian";
import {Upload2NotionNext} from "./upload_next/Upload2NotionNext";
import {Upload2NotionGeneral} from "./upload_general/Upload2NotionGeneral";
import {Upload2NotionCustom} from "./upoload_custom/Upload2NotionCustom";
import {Upload2Notion} from "./Upload2Notion";
import type {NotionPageResponse} from "./common/UploadBase";
import {DatabaseDetails, PluginSettings} from "../ui/settingTabs";
import ObsidianSyncNotionPlugin from "../main";
import {getNowFileMarkdownContentNext} from "./upload_next/getMarkdownNext";
import {getNowFileMarkdownContentGeneral} from "./upload_general/getMarkdownGeneral";
import {getNowFileMarkdownContentCustom} from "./upoload_custom/getMarkdownCustom";
import {getNowFileMarkdownContentNext} from "./common/getMarkdownNext";
import {getNowFileMarkdownContentGeneral} from "./common/getMarkdownGeneral";
import {getNowFileMarkdownContentCustom} from "./common/getMarkdownCustom";
const SYNC_ERROR_NOTICE_DURATION = 8000;
function extractErrorMessage(error: unknown): string {
if (error instanceof Error && error.message) {
return error.message;
}
return String(error);
}
function notifySyncError(prefix: string, basename: string, error: unknown): void {
const errorMessage = extractErrorMessage(error);
console.error(`${prefix} Sync failed`, error);
new Notice(
`${i18nConfig["sync-fail"]} ${basename}. ${errorMessage}\n${i18nConfig["CheckConsole"]}`,
SYNC_ERROR_NOTICE_DURATION,
);
}
function logCommandDebug(context: string, message: string, payload?: Record<string, unknown>): void {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
export async function uploadCommandNext(
plugin: ObsidianSyncNotionPlugin,
@@ -17,6 +42,7 @@ export async function uploadCommandNext(
) {
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandNext] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPI === "" || databaseID === "") {
@@ -39,19 +65,76 @@ export async function uploadCommandNext(
paword,
favicon,
datetime
} = await getNowFileMarkdownContentNext(app, settings)
} = await getNowFileMarkdownContentNext(app, settings);
logCommandDebug("uploadCommandNext", "Metadata extracted from markdown", {
hasMarkdown: !!markDownData,
markdownLength: markDownData?.length ?? 0,
tagCount: tags?.length ?? 0,
coverIncluded: !!cover,
hasEmoji: !!emoji,
type,
slug,
hasPassword: !!paword,
datetime,
});
if (markDownData) {
const {basename} = nowFile;
logCommandDebug("uploadCommandNext", "Preparing to upload", {
filename: basename,
filePath: nowFile.path,
});
const upload = new Upload2NotionNext(plugin, dbDetails);
const res = await upload.syncMarkdownToNotionNext(basename, emoji, cover, tags, type, slug, stats, category, summary, paword, favicon, datetime, markDownData, nowFile, this.app);
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "next",
title: basename,
emoji: emoji || "",
cover: cover || "",
tags: tags || [],
type: type || "",
slug: slug || "",
stats: stats || "",
category: category || "",
summary: summary || "",
password: paword || "",
favicon: favicon || "",
datetime: datetime || "",
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandNext]", basename, error);
logCommandDebug("uploadCommandNext", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandNext", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandNext", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}
@@ -66,6 +149,7 @@ export async function uploadCommandGeneral(
) {
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandGeneral] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPI === "" || databaseID === "") {
@@ -76,17 +160,58 @@ export async function uploadCommandGeneral(
const {markDownData, nowFile, cover, tags} = await getNowFileMarkdownContentGeneral(app, settings)
new Notice(i18nConfig.StartUpload.replace('{filename}', nowFile.basename));
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const {basename} = nowFile;
logCommandDebug("uploadCommandGeneral", "Preparing to upload", {
filename: basename,
markdownLength: markDownData.length,
tagCount: tags?.length ?? 0,
hasCover: !!cover,
});
const upload = new Upload2NotionGeneral(plugin, dbDetails);
const res = await upload.syncMarkdownToNotionGeneral(basename, cover, tags, markDownData, nowFile, this.app);
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "general",
title: basename,
cover: cover || "",
tags: tags || [],
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandGeneral]", basename, error);
logCommandDebug("uploadCommandGeneral", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandGeneral", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandGeneral", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}
@@ -100,7 +225,8 @@ export async function uploadCommandCustom(
app: App,
) {
const {notionAPI, databaseID} = settings;
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandCustom] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPI === "" || databaseID === "") {
@@ -111,17 +237,58 @@ export async function uploadCommandCustom(
const {markDownData, nowFile, cover, customValues} = await getNowFileMarkdownContentCustom(app, dbDetails)
new Notice(i18nConfig.StartUpload.replace('{filename}', nowFile.basename));
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const {basename} = nowFile;
logCommandDebug("uploadCommandCustom", "Preparing to upload", {
filename: basename,
markdownLength: markDownData.length,
hasCover: !!cover,
customValueKeys: Object.keys(customValues || {}),
});
const upload = new Upload2NotionCustom(plugin, dbDetails);
const res = await upload.syncMarkdownToNotionCustom(cover, customValues, markDownData, nowFile, this.app);
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "custom",
cover: cover || "",
customValues,
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandCustom]", basename, error);
logCommandDebug("uploadCommandCustom", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandCustom", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandCustom", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}

View File

@@ -1,96 +0,0 @@
import { App, Notice, requestUrl, TFile } from "obsidian";
import { Client } from '@notionhq/client';
import { markdownToBlocks, } from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import { DatabaseDetails } from "../../ui/settingTabs";
export class UploadBaseGeneral {
plugin: MyPlugin;
notion: Client;
agent: any;
dbDetails: DatabaseDetails
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails
}
async deletePage(notionID: string) {
const { notionAPI } = this.dbDetails
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
},
body: ''
});
}
async getDataBase(databaseID: string) {
const { notionAPI } = this.dbDetails
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
}
}
)
// Check if cover is present in the JSON response and then get the URL
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
} else {
return null; // or some other default value, if you prefer
}
}
// async updateYamlInfo(yamlContent: string, nowFile: TFile, res: any, app: App, settings: any) {
// let {url, id} = res.json
// // replace www to notionID
// const {notionUser} = this.plugin.settings;
//
// if (notionUser !== "") {
// // replace url str "www" to notionID
// url = url.replace("www.notion.so", `${notionUser}.notion.site`)
// }
//
// await app.fileManager.processFrontMatter(nowFile, yamlContent => {
// if (yamlContent['notionID']) {
// delete yamlContent['notionID']
// }
// if (yamlContent['link']) {
// delete yamlContent['link']
// }
// // add new notionID and link
// yamlContent.notionID = id;
// yamlContent.link = url;
// });
//
// try {
// await navigator.clipboard.writeText(url)
// } catch (error) {
// new Notice(`复制链接失败,请手动复制${error}`)
// }
// // const __content = yamlContent.__content;
// // delete yamlContent.__content
// // const yamlhead = yaml.stringify(yamlContent)
// // // if yamlhead hava last \n remove it
// // const yamlhead_remove_n = yamlhead.replace(/\n$/, '')
// // // if __content have start \n remove it
// // const __content_remove_n = __content.replace(/^\n/, '')
// // const content = '---\n' +yamlhead_remove_n +'\n---\n' + __content_remove_n;
// // try {
// // await nowFile.vault.modify(nowFile, content)
// // } catch (error) {
// // new Notice(`write file error ${error}`)
// // }
// }
}

View File

@@ -1,248 +0,0 @@
import {App, Notice, TFile} from "obsidian";
import {Client} from "@notionhq/client";
import {markdownToBlocks} from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import {DatabaseDetails, PluginSettings} from "../../ui/settingTabs";
import {UploadBaseGeneral} from "./BaseUpload2NotionGeneral";
import {updateYamlInfo} from "../updateYaml";
import fetch from 'node-fetch';
import {i18nConfig} from "../../lang/I18n";
export class Upload2NotionGeneral extends UploadBaseGeneral {
settings: PluginSettings;
dbDetails: DatabaseDetails;
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
super(plugin, dbDetails);
this.dbDetails = dbDetails;
}
// 因为需要解析notion的block进行对比非常的麻烦
// 暂时就直接删除新建一个page
async updatePage(
notionID: string,
title: string,
cover: string,
tags: string[],
childArr: any,
) {
await this.deletePage(notionID);
const {databaseID} = this.dbDetails;
const databaseCover = await this.getDataBase(
databaseID,
);
if (cover == null) {
cover = databaseCover;
}
return await this.createPage(title, cover, tags, childArr);
}
async createPage(
title: string,
cover: string,
tags: string[],
childArr: any,
) {
const {
databaseID,
customTitleButton,
customTitleName,
tagButton,
notionAPI
} = this.dbDetails;
// remove the annotations from the childArr if type is code block
childArr.forEach((block: any) => {
if (block.type === "code") {
block.code.rich_text.forEach((item: any) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
}
);
}
}
);
// check the length of the childArr and split it into chunks of 100
const childArrLength = childArr.length;
let extraArr: any[] = [];
let firstArr: any;
let pushCount = 0;
console.log(`Page includes ${childArrLength} blocks`)
if (childArrLength > 100) {
for (let i = 0; i < childArr.length; i += 100) {
if (i == 0) {
firstArr = childArr.slice(0, 100);
} else {
const chunk = childArr.slice(i, i + 100);
extraArr.push(chunk);
pushCount++;
}
}
} else {
firstArr = childArr;
}
const bodyString: any = {
parent: {
database_id: databaseID,
},
properties: {
[customTitleButton
? customTitleName
: "title"]: {
title: [
{
text: {
content: title,
},
},
],
},
...(tagButton
? {
tags: {
multi_select: tags && true ? tags.map((tag) => ({name: tag})) : [],
},
}
: {}),
},
children: firstArr,
};
if (cover) {
bodyString.cover = {
type: "external",
external: {
url: cover,
},
};
}
if (!bodyString.cover && this.plugin.settings.bannerUrl) {
bodyString.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl,
},
};
}
console.log(bodyString)
const response = await fetch("https://api.notion.com/v1/pages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(bodyString),
});
const data: any = await response.json();
if (!response.ok) {
new Notice(`Error ${data.status}: ${data.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
} else {
console.log(`Page created: ${data.url}`);
console.log(`Page ID: ${data.id}`);
}
// upload the rest of the blocks
if (pushCount > 0) {
for (let i = 0; i < pushCount; i++) {
const extraBlocks = {
children: extraArr[i],
};
console.log(extraBlocks)
const extraResponse = await fetch(`https://api.notion.com/v1/blocks/${data.id}/children`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(extraBlocks),
});
const extraData: any = await extraResponse.json();
if (!extraResponse.ok) {
new Notice(`Error ${extraData.status}: ${extraData.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${data.id}`);
if (i === pushCount - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${data.id}`);
new Notice(`${i18nConfig["BlockUploaded"]} page: ${data.id}`, 5000);
}
}
}
}
return {
response, // for status code
data // for id and url
}
}
async syncMarkdownToNotionGeneral(
title: string,
cover: string,
tags: string[],
markdown: string,
nowFile: TFile,
app: App,
): Promise<any> {
const options = {
notionLimits: {
truncate: false,
}
}
let res: any;
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const __content = yamlContent.__content;
const file2Block = markdownToBlocks(__content, options);
const frontmasster =
app.metadataCache.getFileCache(nowFile)?.frontmatter;
const {abName} = this.dbDetails
const notionIDKey = `NotionID-${abName}`;
const notionID = frontmasster ? frontmasster[notionIDKey] : null;
if (notionID) {
res = await this.updatePage(
notionID,
title,
cover,
tags,
file2Block,
);
} else {
res = await this.createPage(title, cover, tags, file2Block);
}
let {response, data} = res;
// console.log(response)
if (response && response.status === 200) {
await updateYamlInfo(markdown, nowFile, data, app, this.plugin, this.dbDetails);
}
return res;
}
}

View File

@@ -1,96 +0,0 @@
import { App, Notice, requestUrl, TFile } from "obsidian";
import { Client } from '@notionhq/client';
import { markdownToBlocks, } from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import { DatabaseDetails } from "../../ui/settingTabs";
export class UploadBaseNext {
plugin: MyPlugin;
notion: Client;
agent: any;
dbDetails: DatabaseDetails
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails
}
async deletePage(notionID: string) {
const { notionAPI } = this.dbDetails
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
},
body: ''
});
}
async getDataBase(databaseID: string) {
const { notionAPI } = this.dbDetails
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
}
}
)
// Check if cover is present in the JSON response and then get the URL
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
} else {
return null; // or some other default value, if you prefer
}
}
// async updateYamlInfo(yamlContent: string, nowFile: TFile, res: any, app: App, settings: any) {
// let {url, id} = res.json
// // replace www to notionID
// const { notionUser} = this.plugin.settings;
//
// if (notionUser !== "") {
// // replace url str "www" to notionID
// url = url.replace("www.notion.so", `${notionUser}.notion.site`)
// }
//
// await app.fileManager.processFrontMatter(nowFile, yamlContent => {
// if (yamlContent['notionID']) {
// delete yamlContent['notionID']
// }
// if (yamlContent['link']) {
// delete yamlContent['link']
// }
// // add new notionID and link
// yamlContent.notionID = id;
// yamlContent.link = url;
// });
//
// try {
// await navigator.clipboard.writeText(url)
// } catch (error) {
// new Notice(`复制链接失败,请手动复制${error}`)
// }
// // const __content = yamlContent.__content;
// // delete yamlContent.__content
// // const yamlhead = yaml.stringify(yamlContent)
// // // if yamlhead hava last \n remove it
// // const yamlhead_remove_n = yamlhead.replace(/\n$/, '')
// // // if __content have start \n remove it
// // const __content_remove_n = __content.replace(/^\n/, '')
// // const content = '---\n' +yamlhead_remove_n +'\n---\n' + __content_remove_n;
// // try {
// // await nowFile.vault.modify(nowFile, content)
// // } catch (error) {
// // new Notice(`write file error ${error}`)
// // }
// }
}

View File

@@ -1,411 +0,0 @@
import {UploadBaseNext} from "./BaseUpload2NotionNext";
import {App, Notice, TFile} from "obsidian";
import {Client} from "@notionhq/client";
import {markdownToBlocks} from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import {DatabaseDetails, PluginSettings} from "../../ui/settingTabs";
import {updateYamlInfo} from "../updateYaml";
import {LIMITS, paragraph} from "@jxpeng98/martian/src/notion";
import fetch from "node-fetch";
import {i18nConfig} from "../../lang/I18n";
export class Upload2NotionNext extends UploadBaseNext {
settings: PluginSettings;
dbDetails: DatabaseDetails;
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
super(plugin, dbDetails);
this.dbDetails = dbDetails;
}
// 因为需要解析notion的block进行对比非常的麻烦
// 暂时就直接删除新建一个page
async updatePage(
notionID: string,
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
paword: string,
favicon: string,
datetime: string,
childArr: any,
) {
await this.deletePage(notionID);
const {databaseID} = this.dbDetails;
const databaseCover = await this.getDataBase(databaseID);
if (cover == null) {
cover = databaseCover;
}
return await this.createPage(
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
childArr,
);
}
async createPage(
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
pawrod: string,
favicon: string,
datetime: string,
childArr: any,
) {
const {databaseID, notionAPI} = this.dbDetails;
// remove the annotations from the childArr if type is code block
childArr.forEach((block: any) => {
if (block.type === "code") {
block.code.rich_text.forEach((item: any) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
}
);
}
}
);
// check the length of the childArr
// if it is too long, split it into multiple pages
const childArrLength = childArr.length;
let extraArr: any[] = [];
let firstArr: any;
let pushCount = 0;
console.log(`Page includes ${childArrLength} blocks`)
if (childArrLength > 100) {
for (let i = 0; i < childArr.length; i += 100) {
if (i == 0) {
firstArr = childArr.slice(0, 100);
} else {
const chunk = childArr.slice(i, i + 100);
extraArr.push(chunk);
pushCount++;
}
}
} else {
firstArr = childArr;
}
const pageProperties: any = {
parent: {
database_id: databaseID,
},
properties: {
title: {
title: [
{
text: {
content: title,
},
},
],
},
type: {
select: {
name: type || "Post",
},
},
status: {
select: {
name: stats || "Draft",
},
},
category: {
select: {
name: category || "Obsidian",
},
},
password: {
rich_text: [
{
text: {
content: pawrod || "",
},
},
],
},
icon: {
rich_text: [
{
text: {
content: favicon || "",
},
},
],
},
date: {
date: {
start: datetime || new Date().toISOString(),
},
},
},
};
// add tags
if (tags) {
pageProperties.properties.tags = {
multi_select: tags.map((tag) => {
return {name: tag};
}),
};
}
// add title icon
if (emoji) {
pageProperties.icon = {
emoji: emoji,
};
}
// add slug
if (slug) {
pageProperties.properties.slug = {
rich_text: [
{
text: {
content: slug,
},
},
],
};
}
// check if summary is available
if (summary) {
pageProperties.properties.summary = {
rich_text: [
{
text: {
content: summary,
},
},
],
};
}
if (cover) {
pageProperties.cover = {
type: "external",
external: {
url: cover,
},
};
}
if (!pageProperties.cover && this.plugin.settings.bannerUrl) {
pageProperties.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl,
},
};
}
const bodyString: any = {
...pageProperties,
children: firstArr,
};
console.log(bodyString);
const response = await fetch("https://api.notion.com/v1/pages", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(bodyString),
});
const data: any = await response.json();
// can use response.ok or response.status === 200
if (!response.ok) {
new Notice(`Error ${data.status}: ${data.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${data.message}`);
} else {
console.log(`Page created: ${data.url}`);
console.log(`Page ID: ${data.id}`);
}
// if the childArr is over 100, patch the rest of the blocks append to the page
if (pushCount > 0) {
for (let i = 0; i < pushCount; i++) {
const extraBlocks = {
children: extraArr[i]
}
console.log(extraBlocks)
const extraResponse = await fetch(
`https://api.notion.com/v1/blocks/${data.id}/children`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(extraBlocks),
});
const extraData: any = await extraResponse.json();
if (!extraResponse.ok) {
new Notice(
`Extra Block: Error ${extraData.status}: ${extraData.code} \n ${i18nConfig["CheckConsole"]}`,
5000,
);
console.log(`Error message: \n ${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${data.id}`);
if (i === pushCount - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${data.id}`);
new Notice(`${i18nConfig["BlockUploaded"]} page: ${data.id}`, 5000);
}
}
}
}
return {
response, // for status code
data, // for id and url
};
}
async syncMarkdownToNotionNext(
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
paword: string,
favicon: string,
datetime: string,
markdown: string,
nowFile: TFile,
app: App,
): Promise<any> {
const options = {
notionLimits: {
truncate: false,
},
};
let res: any;
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const __content = yamlContent.__content;
const file2Block = markdownToBlocks(__content, options);
const frontmatter =
app.metadataCache.getFileCache(nowFile)?.frontmatter;
const {abName} = this.dbDetails;
const notionIDKey = `NotionID-${abName}`;
const notionID = frontmatter ? frontmatter[notionIDKey] : null;
// increase the limits
// Motivated by https://github.com/tryfabric/martian/issues/51
file2Block.forEach((block, index) => {
if (
block.type === "paragraph" &&
block.paragraph.rich_text.length > LIMITS.RICH_TEXT_ARRAYS
) {
const newParagraphBlocks: any[] = [];
const chunk: any = [];
const richTextChunks = chunk(block.paragraph.rich_text, 100);
richTextChunks.forEach((chunk: any) => {
newParagraphBlocks.push(paragraph(chunk));
});
file2Block.splice(index, 1, ...newParagraphBlocks);
}
});
if (notionID) {
res = await this.updatePage(
notionID,
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
file2Block,
);
} else {
res = await this.createPage(
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
file2Block,
);
}
let {response, data} = res;
if (response && response.status === 200) {
await updateYamlInfo(
markdown,
nowFile,
data,
app,
this.plugin,
this.dbDetails,
);
}
return res;
}
}

View File

@@ -1,53 +0,0 @@
import { App, Notice, requestUrl, TFile } from "obsidian";
import { Client } from '@notionhq/client';
import { markdownToBlocks, } from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import { DatabaseDetails } from "../../ui/settingTabs";
export class UploadBaseCustom {
plugin: MyPlugin;
notion: Client;
agent: any;
dbDetails: DatabaseDetails
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails
}
async deletePage(notionID: string) {
const { notionAPI } = this.dbDetails
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
},
body: ''
});
}
async getDataBase(databaseID: string) {
const { notionAPI } = this.dbDetails
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + notionAPI,
'Notion-Version': '2022-06-28',
}
}
)
// Check if cover is present in the JSON response and then get the URL
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
} else {
return null; // or some other default value, if you prefer
}
}
}

View File

@@ -1,327 +0,0 @@
import {App, Notice, TFile} from "obsidian";
import {markdownToBlocks} from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import {DatabaseDetails, PluginSettings} from "../../ui/settingTabs";
import {updateYamlInfo} from "../updateYaml";
import {UploadBaseCustom} from "./BaseUpload2NotionCustom";
import fetch from 'node-fetch';
import {i18nConfig} from "../../lang/I18n";
export class Upload2NotionCustom extends UploadBaseCustom {
settings: PluginSettings;
dbDetails: DatabaseDetails;
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
super(plugin, dbDetails);
this.dbDetails = dbDetails;
}
// 因为需要解析notion的block进行对比非常的麻烦
// 暂时就直接删除新建一个page
async updatePage(
notionID: string,
cover: string,
customValues: Record<string, string>,
childArr: any,
) {
await this.deletePage(notionID);
const {databaseID} = this.dbDetails;
const databaseCover = await this.getDataBase(
databaseID
);
if (cover == null) {
cover = databaseCover;
}
return await this.createPage(cover, customValues, childArr);
}
async createPage(
cover: string,
customValues: Record<string, string>,
childArr: any,
) {
const {
databaseID,
customProperties,
notionAPI
} = this.dbDetails;
// remove the annotations from the childArr if type is code block
childArr.forEach((block: any) => {
if (block.type === "code") {
block.code.rich_text.forEach((item: any) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
}
);
}
}
);
// check the length of the childArr and split it into chunks of 100
const childArrLength = childArr.length;
let extraArr: any[] = [];
let firstArr: any;
let pushCount = 0;
console.log(`Page includes ${childArrLength} blocks`)
if (childArrLength > 100) {
for (let i = 0; i < childArr.length; i += 100) {
if (i == 0) {
firstArr = childArr.slice(0, 100);
} else {
const chunk = childArr.slice(i, i + 100);
extraArr.push(chunk);
pushCount++;
}
}
} else {
firstArr = childArr;
}
const bodyString: any = this.buildBodyString(customProperties, customValues, firstArr);
if (cover) {
bodyString.cover = {
type: "external",
external: {
url: cover,
},
};
}
if (!bodyString.cover && this.plugin.settings.bannerUrl) {
bodyString.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl,
},
};
}
console.log(bodyString)
const response = await fetch("https://api.notion.com/v1/pages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(bodyString),
});
const data: any = await response.json();
if (!response.ok) {
new Notice(`Error ${data.status}: ${data.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${data.message}`);
} else {
console.log(`Page created: ${data.url}`);
console.log(`Page ID: ${data.id}`);
}
// upload the rest of the blocks
if (pushCount > 0) {
for (let i = 0; i < pushCount; i++) {
const extraBlocks = {
children: extraArr[i],
};
console.log(extraBlocks)
const extraResponse = await fetch(`https://api.notion.com/v1/blocks/${data.id}/children`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(extraBlocks),
});
const extraData: any = await extraResponse.json();
if (!extraResponse.ok) {
new Notice(`Error ${extraData.status}: ${extraData.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${data.id}`);
if (i === pushCount - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${data.id}`);
new Notice(`${i18nConfig["BlockUploaded"]} page: ${data.id}`, 5000);
}
}
}
}
return {
response, // for status code
data // for id and url
}
}
async syncMarkdownToNotionCustom(
cover: string,
customValues: Record<string, string>,
markdown: string,
nowFile: TFile,
app: App,
): Promise<any> {
const options = {
strictImageUrls: true,
notionLimits: {
truncate: false,
}
}
let res: any;
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const __content = yamlContent.__content;
const file2Block = markdownToBlocks(__content, options);
const frontMatter =
app.metadataCache.getFileCache(nowFile)?.frontmatter;
const {abName} = this.dbDetails
const notionIDKey = `NotionID-${abName}`;
const notionID = frontMatter ? frontMatter[notionIDKey] : null;
if (notionID) {
res = await this.updatePage(
notionID,
cover,
customValues,
file2Block,
);
} else {
res = await this.createPage(cover, customValues, file2Block);
}
let {response, data} = res;
// console.log(response)
if (response && response.status === 200) {
await updateYamlInfo(markdown, nowFile, data, app, this.plugin, this.dbDetails);
}
return res;
}
private buildPropertyObject(customName: string, customType: string, customValues: Record<string, any>) {
const value = customValues[customName] || '';
switch (customType) {
case "title":
return {
title: [
{
text: {
content: value,
},
},
],
};
case "rich_text":
return {
rich_text: [
{
text: {
content: value || '',
},
},
],
};
case "date":
return {
date: {
start: value || new Date().toISOString(),
},
};
case "number":
return {
number: Number(value),
};
case "phone_number":
return {
phone_number: value,
};
case "email":
return {
email: value,
};
case "url":
return {
url: value,
};
case "files":
return {
files: Array.isArray(value) ? value.map(url => ({
name: url,
type: "external",
external: {
url: url,
},
})) : [
{
name: value,
type: "external",
external: {
url: value,
},
},
],
};
case "checkbox":
return {
checkbox: Boolean(value) || false,
};
case "select":
return {
select: {
name: value,
},
};
case "multi_select":
return {
multi_select: Array.isArray(value) ? value.map(item => ({name: item})) : [{name: value}],
};
}
}
private buildBodyString(
customProperties: { customName: string; customType: string }[],
customValues: Record<string, string>,
childArr: any,
) {
const properties: { [key: string]: any } = {};
// Only include custom properties that have values
customProperties.forEach(({customName, customType}) => {
if (customValues[customName] !== undefined) {
properties[customName] = this.buildPropertyObject(customName, customType, customValues);
}
}
);
// console.log(properties)
return {
parent: {
database_id: this.dbDetails.databaseID,
},
properties,
children: childArr,
};
}
}

63
src/utils/frontmatter.ts Normal file
View File

@@ -0,0 +1,63 @@
export const DEFAULT_AUTO_SYNC_DATABASE_KEY = "autosync-database";
export function resolveAutoSyncKey(rawKey: unknown): string {
if (typeof rawKey === "string") {
const trimmed = rawKey.trim();
if (trimmed.length > 0) {
return trimmed;
}
}
return DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
function toCandidateList(value: unknown): string[] {
if (Array.isArray(value)) {
return value.map(item => String(item ?? "").trim());
}
if (typeof value === "string") {
if (value.includes(",")) {
return value.split(",").map(item => item.trim());
}
return [value.trim()];
}
return [];
}
export function parseAutoSyncDatabaseList(value: unknown): string[] {
const candidates = toCandidateList(value)
.map(name => name.replace(/^\[|\]$/g, "").trim()) // strip stray brackets
.filter(Boolean);
const seen = new Map<string, string>();
for (const name of candidates) {
const key = name.toLowerCase();
if (!seen.has(key)) {
seen.set(key, name);
}
}
return Array.from(seen.values());
}
export function ensureAutoSyncDatabaseEntry(value: unknown, abName: string): string[] {
const current = parseAutoSyncDatabaseList(value);
const lower = abName.toLowerCase();
let contains = false;
const updated = current.map(name => {
if (name.toLowerCase() === lower) {
contains = true;
return abName;
}
return name;
});
if (!contains) {
updated.push(abName);
}
return updated;
}

1523
yarn.lock

File diff suppressed because it is too large Load Diff