picgo-plugin-notion-migrator 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/License +21 -0
- package/README.md +163 -2
- package/README_CN.md +83 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +307 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.js +107 -0
- package/dist/gui.d.ts +26 -0
- package/dist/gui.js +203 -0
- package/dist/i18n/en.d.ts +51 -0
- package/dist/i18n/en.js +53 -0
- package/dist/i18n/index.d.ts +7 -0
- package/dist/i18n/index.js +24 -0
- package/dist/i18n/zh-CN.d.ts +2 -0
- package/dist/i18n/zh-CN.js +52 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +15 -0
- package/dist/journal.d.ts +36 -0
- package/dist/journal.js +76 -0
- package/dist/media.d.ts +58 -0
- package/dist/media.js +121 -0
- package/dist/migrator.d.ts +113 -0
- package/dist/migrator.js +342 -0
- package/dist/notion/client.d.ts +83 -0
- package/dist/notion/client.js +171 -0
- package/dist/notion/http.d.ts +38 -0
- package/dist/notion/http.js +93 -0
- package/dist/notion/ids.d.ts +20 -0
- package/dist/notion/ids.js +100 -0
- package/dist/notion/markdown.d.ts +48 -0
- package/dist/notion/markdown.js +158 -0
- package/dist/notion/rateLimit.d.ts +28 -0
- package/dist/notion/rateLimit.js +75 -0
- package/dist/notion/types.d.ts +113 -0
- package/dist/notion/types.js +6 -0
- package/dist/runner.d.ts +32 -0
- package/dist/runner.js +93 -0
- package/dist/scanner.d.ts +96 -0
- package/dist/scanner.js +302 -0
- package/dist/size.d.ts +8 -0
- package/dist/size.js +40 -0
- package/dist/upload.d.ts +31 -0
- package/dist/upload.js +116 -0
- package/package.json +73 -4
package/License
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 - present Molunerfinn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,164 @@
|
|
|
1
|
-
#
|
|
1
|
+
# picgo-plugin-notion-migrator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[中文说明](./README_CN.md)
|
|
4
|
+
|
|
5
|
+
Move images stored in Notion to the image host you use in [PicGo](https://picgo.app), and free Notion file storage.
|
|
6
|
+
|
|
7
|
+
Notion's Free plan limits a workspace to 512 MB of uploaded files. Images that are embedded by URL don't count, and per [Notion's help](https://www.notion.com/help/file-storage-limits-in-notion) neither do files you replaced or files that only remain in version history. This plugin finds image blocks whose file is hosted by Notion, downloads each one, uploads it through PicGo, and switches the same block to the new URL. The block keeps its id, position, caption and comments, so links to the block still work.
|
|
8
|
+
|
|
9
|
+
## Requirements
|
|
10
|
+
|
|
11
|
+
- PicGo 3.0.0 or later (GUI), or PicGo-Core 3.0.0 or later (CLI), on Node.js 20.19 or later.
|
|
12
|
+
- An image host that already works in PicGo. Everything you configured runs as usual: the uploader, compression or watermark plugins, rename and URL rewrite rules.
|
|
13
|
+
- A Notion token with read and update access to the pages you want to migrate.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
GUI: open PicGo → Plugins, search for `notion-migrator` and install it.
|
|
18
|
+
|
|
19
|
+
CLI:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
picgo install notion-migrator
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Get a Notion token
|
|
26
|
+
|
|
27
|
+
Either kind of token works; the plugin only sends it as a Bearer token.
|
|
28
|
+
|
|
29
|
+
**Personal access token (recommended).** It acts as you, so it sees every page you can see and needs no sharing.
|
|
30
|
+
|
|
31
|
+
1. Open [Personal access tokens](https://www.notion.so/developers/tokens) in the Notion developer portal and select **New token**.
|
|
32
|
+
2. Name it, give it the **Notion API** capability, pick the workspace and an expiration.
|
|
33
|
+
3. Select **Create token** and copy the value. Notion shows it only once.
|
|
34
|
+
|
|
35
|
+
**Internal connection.** It acts as a separate bot and only sees pages you share with it. You need to be a workspace owner to create one.
|
|
36
|
+
|
|
37
|
+
1. In the [developer portal](https://app.notion.com/developers/connections), select **New connection**, choose **API token** as the authentication method and create it.
|
|
38
|
+
2. On the **Configuration** tab, copy the API token and make sure the connection can read and update content.
|
|
39
|
+
3. Share pages with it: either **Content access → Edit access** in the developer portal, or on a page **••• → Connections → Add connection**. Sharing a page also shares its child pages.
|
|
40
|
+
|
|
41
|
+
## Configure
|
|
42
|
+
|
|
43
|
+
GUI: Plugins → notion-migrator → Config plugin. CLI: `picgo set plugin notion-migrator`.
|
|
44
|
+
|
|
45
|
+
| Field | Meaning |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| Notion token | The token from above. Stored in PicGo's config file. For the CLI you can set `NOTION_TOKEN` instead; it wins over the saved value. |
|
|
48
|
+
| Pages | Optional. Page or database URLs or ids, separated by commas, spaces or new lines. Each one is scanned with everything under it. Empty means every page that Notion's search returns for the token. |
|
|
49
|
+
| Include | Optional regular expression on the file name. Only matching images are migrated. |
|
|
50
|
+
| Exclude | Optional regular expression on the file name. Matching images are skipped. |
|
|
51
|
+
|
|
52
|
+
Page URLs can be copied from the browser or from **Share → Copy link**. Ids with or without dashes work, and so do database URLs opened in peek mode (`?p=`).
|
|
53
|
+
|
|
54
|
+
## Use
|
|
55
|
+
|
|
56
|
+
### CLI
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
# List Notion-hosted images; nothing is changed
|
|
60
|
+
picgo notion scan
|
|
61
|
+
picgo notion scan --page https://www.notion.so/My-Page-0123456789abcdef0123456789abcdef --size
|
|
62
|
+
picgo notion scan --json > images.json
|
|
63
|
+
picgo notion scan --out images.json
|
|
64
|
+
|
|
65
|
+
# See what would happen, then migrate a few, then everything
|
|
66
|
+
picgo notion migrate --dry-run
|
|
67
|
+
picgo notion migrate --limit 5
|
|
68
|
+
picgo notion migrate
|
|
69
|
+
picgo notion migrate --page <url-or-id> --yes
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`scan` options: `--page <url-or-id...>` (overrides the configured pages), `--scan-mode <markdown|blocks>` (see [Scan modes](#scan-modes)), `--json` (print JSON instead of text), `--out <file>` (also write JSON to a file), `--size` (ask Notion's storage for each file size, one extra request per image).
|
|
73
|
+
|
|
74
|
+
`migrate` options: `--page <url-or-id...>`, `--scan-mode <markdown|blocks>`, `--dry-run`, `--limit <n>`, `--yes` (skip the confirmation; required when not in a terminal), `--batch-size <n>` (images per PicGo upload, default 5).
|
|
75
|
+
|
|
76
|
+
Press Ctrl+C once to stop after the current image, twice to quit immediately.
|
|
77
|
+
|
|
78
|
+
### GUI
|
|
79
|
+
|
|
80
|
+
In the plugin's menu:
|
|
81
|
+
|
|
82
|
+
- **Scan** shows how many Notion-hosted images there are, per page.
|
|
83
|
+
- **Migrate all** scans the configured pages (or everything) and asks before changing anything.
|
|
84
|
+
- **Migrate a page** asks for one page URL or id.
|
|
85
|
+
- **Stop** stops the current run after the image in progress.
|
|
86
|
+
|
|
87
|
+
Progress shows as a notification at every 10%, and a final notification has the counts. If **Rename before upload** is on in PicGo settings, the plugin warns first, because PicGo would open a rename window for every image.
|
|
88
|
+
|
|
89
|
+
## How it works
|
|
90
|
+
|
|
91
|
+
1. Scan. Starting from the configured pages (or from Notion search), the plugin reads every page, including nested blocks such as toggles, columns, callouts, lists, tables and tabs. It follows child pages and inline databases, reading every row. Synced block copies are skipped, because their content lives in the original block. Trashed blocks and images that already use a URL are skipped.
|
|
92
|
+
2. For each image, in batches: read the block again, download it to a temporary file named after the block id, upload the batch with PicGo, then update the block with `PATCH /v1/blocks/{id}` to point at the new URL. Reading the block right before the update gets a fresh download link (Notion's links expire after an hour) and checks that it is still an image holding the same Notion-hosted file, so an image you replaced or deleted after the scan is followed or skipped instead of overwritten.
|
|
93
|
+
3. Every upload and every block update is appended to a journal. Run the same command again to resume: finished blocks are skipped, and blocks that were uploaded but not yet updated are only updated, without uploading again.
|
|
94
|
+
|
|
95
|
+
Files the plugin writes, under PicGo's config folder (`~/.picgo` by default):
|
|
96
|
+
|
|
97
|
+
- `notion-migrator/journal.jsonl`: the journal, one JSON line per event.
|
|
98
|
+
- `notion-migrator/reports/*.json`: one report per migrate run, listing each image with its new URL or the reason it failed or was skipped.
|
|
99
|
+
|
|
100
|
+
Temporary downloads go to the system temp folder and are deleted at the end of each run.
|
|
101
|
+
|
|
102
|
+
### Scan modes
|
|
103
|
+
|
|
104
|
+
- `markdown` (default) reads each page with one request, `GET /v1/pages/{id}/markdown`, which returns the whole page with nested blocks inlined. Each Notion-hosted image carries its block id in the link, so no block has to be read one by one. Pages over about 20,000 blocks come back truncated; the missing parts are fetched by id, one request each. If Notion refuses a page there (400 or 403), that page is read block by block instead, and after three refusals in a row with no success the rest of the scan switches to `blocks`.
|
|
105
|
+
- `blocks` walks `GET /v1/blocks/{id}/children`: one request per page and per block that has children (each toggle, column, callout, list item with sub-items...), plus one per 100 children. Use it if the markdown endpoint misbehaves for your workspace.
|
|
106
|
+
|
|
107
|
+
Both modes find the same images. Blocks Markdown can't show, such as template buttons, are read with the block API in either mode.
|
|
108
|
+
|
|
109
|
+
### Request cost
|
|
110
|
+
|
|
111
|
+
| Step | Requests |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| Each configured page | 1 to read its title |
|
|
114
|
+
| Each page, `markdown` mode | 1, plus 1 per truncated part of a page over about 20,000 blocks |
|
|
115
|
+
| Each page, `blocks` mode | 1 per block with children, plus 1 per 100 children |
|
|
116
|
+
| Each database | 1, plus 1 per 100 rows |
|
|
117
|
+
| Search, when no pages are configured | 1 per 100 results |
|
|
118
|
+
| Each migrated image | 2: read the block, then update it |
|
|
119
|
+
| `scan --size` | 1 per image, to Notion's file storage, not the API |
|
|
120
|
+
|
|
121
|
+
Titles for reports come from what the scan already read: search results, database rows and child page links. Downloads go to Notion's file storage and don't count toward the API limit.
|
|
122
|
+
|
|
123
|
+
For example, the test page used during development (columns, a toggle, a synced block, a child page and an inline database with one row) took 11 requests in `blocks` mode and 6 in `markdown` mode. Pages with many toggles, columns or nested lists save more.
|
|
124
|
+
|
|
125
|
+
All Notion requests share one rate limiter at about 2.5 requests per second, under Notion's limit of 180 per minute. When Notion answers 429 or 529, the plugin waits for the `Retry-After` time and retries, and it retries server errors and network errors with backoff. Requests go through PicGo's HTTP client, so the proxy in PicGo settings applies.
|
|
126
|
+
|
|
127
|
+
## Privacy
|
|
128
|
+
|
|
129
|
+
Files uploaded to Notion are private: Notion serves them through signed links that expire. Most image hosts return public URLs that anyone with the link can open, forever. Before migrating, make sure the images are fine to be public, or use a host with private buckets or access control. Use **Exclude** or `--page` to leave sensitive pages alone.
|
|
130
|
+
|
|
131
|
+
The token is stored in PicGo's config file in plain text, like other PicGo secrets. Prefer a personal access token with a short expiration, and revoke it when you are done.
|
|
132
|
+
|
|
133
|
+
## Limitations
|
|
134
|
+
|
|
135
|
+
- Only image blocks are migrated. Not yet supported: file, PDF, video and audio blocks, page covers and icons, and files in database properties.
|
|
136
|
+
- Notion's search, used when no pages are configured, is not guaranteed to return every page. If something is missing, add its parent page to **Pages**.
|
|
137
|
+
- Linked database views of a database the token can't read are reported as warnings and skipped.
|
|
138
|
+
- Notion's API lists these extensions for external images: bmp, gif, heic, jpeg, jpg, png, svg, tif, tiff. WebP and other unlisted extensions are migrated with a warning in the report, since the Notion app displays them. AVIF is skipped, because Notion doesn't list it anywhere and a working image shouldn't be replaced by one that may not render. If a compression plugin turns uploads into `.avif`, those updates fail instead of being written.
|
|
139
|
+
- Notion rejects external URLs longer than 2000 characters; such images are reported as failed.
|
|
140
|
+
- Uploaded files are named `<blockId>.<ext>` so names never collide. Rename plugins and PicGo's own rename settings still apply.
|
|
141
|
+
- Migrating changes the blocks, so pages show as edited by you or the connection.
|
|
142
|
+
- The old file stays in the page's version history, which per Notion's help no longer counts toward storage.
|
|
143
|
+
- PicGo can't cancel an upload in progress, so Stop takes effect after the current batch's uploads finish.
|
|
144
|
+
|
|
145
|
+
## Development
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
pnpm install
|
|
149
|
+
pnpm build # TypeScript → dist/ (CommonJS, loaded by PicGo with require)
|
|
150
|
+
pnpm lint # eslint + type check
|
|
151
|
+
pnpm test # build, then unit and end-to-end tests
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The end-to-end test loads `dist/index.js` into a real PicGo-Core instance and runs the CLI and GUI menu against a local mock Notion server. Two environment variables exist for that and are not meant for normal use: `NOTION_MIGRATOR_API_URL` (API base URL) and `NOTION_MIGRATOR_RPS` (requests per second).
|
|
155
|
+
|
|
156
|
+
### Commits and releases
|
|
157
|
+
|
|
158
|
+
The repo follows the PicGo commit convention through [@picgo/bump-version](https://github.com/PicGo/bump-version): use `pnpm cz` to write a commit message, and the commit-msg hook checks it with commitlint.
|
|
159
|
+
|
|
160
|
+
To release, run `pnpm release` (patch by default, `-t minor` or `-t major` for bigger bumps). It bumps `package.json`, updates `CHANGELOG.md`, commits, and creates a `v<version>` tag. Push both with `git push --follow-tags origin main`; the tag starts the release workflow, which lints, tests, builds and publishes to npm with provenance through npm trusted publishing, so no npm token is stored in the repo.
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
MIT
|
package/README_CN.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# picgo-plugin-notion-migrator
|
|
2
|
+
|
|
3
|
+
[English](./README.md)
|
|
4
|
+
|
|
5
|
+
把存放在 Notion 里的图片搬到你在 [PicGo](https://picgo.app) 里配置的图床,释放 Notion 的文件存储空间。
|
|
6
|
+
|
|
7
|
+
Notion 免费版每个工作区最多存 512 MB 上传文件。用链接嵌入的图片不占空间,按 [Notion 帮助文档](https://www.notion.com/help/file-storage-limits-in-notion) 的说法,被替换掉的文件和只留在版本历史里的文件也不算。插件会找出文件存放在 Notion 的图片块,逐张下载,通过 PicGo 上传,再把同一个块改成新链接。块的 id、位置、说明文字和评论都不变,指向这个块的链接照常可用。
|
|
8
|
+
|
|
9
|
+
## 要求
|
|
10
|
+
|
|
11
|
+
- PicGo 3.0.0 及以上,或 PicGo-Core 3.0.0 及以上,Node.js 20.19 及以上。
|
|
12
|
+
- 一个在 PicGo 里能正常上传的图床。你的上传器、压缩或水印插件、重命名和链接改写规则都照常生效。
|
|
13
|
+
- 一个对要迁移的页面有读取和更新权限的 Notion 令牌。
|
|
14
|
+
|
|
15
|
+
## 获取 Notion 令牌
|
|
16
|
+
|
|
17
|
+
- 个人访问令牌(推荐):在 [Personal access tokens](https://www.notion.so/developers/tokens) 新建,勾选 Notion API 能力,选好工作区和有效期,创建后复制令牌(只显示一次)。它以你的身份访问,能看到你能看到的所有页面,不需要额外分享。
|
|
18
|
+
- 内部连接:在 [开发者后台](https://app.notion.com/developers/connections) 新建连接,认证方式选 API token,在 Configuration 里复制令牌并确认有读取和更新内容的能力。然后在 Content access 里选择页面,或在页面右上角 ••• → Connections → Add connection 里把页面分享给它。需要工作区所有者权限。
|
|
19
|
+
|
|
20
|
+
## 配置
|
|
21
|
+
|
|
22
|
+
GUI:插件设置 → notion-migrator → 配置插件。CLI:`picgo set plugin notion-migrator`。
|
|
23
|
+
|
|
24
|
+
| 字段 | 说明 |
|
|
25
|
+
| --- | --- |
|
|
26
|
+
| Notion 令牌 | 上面拿到的令牌。CLI 下也可以用环境变量 `NOTION_TOKEN`,优先于配置。 |
|
|
27
|
+
| 页面 | 可选。页面或数据库的链接或 id,用逗号、空格或换行分隔,会连同下面的所有内容一起扫描。留空表示 Notion 搜索能返回的所有页面。 |
|
|
28
|
+
| 包含 | 可选,匹配文件名的正则表达式,只迁移匹配的图片。 |
|
|
29
|
+
| 排除 | 可选,匹配文件名的正则表达式,跳过匹配的图片。 |
|
|
30
|
+
|
|
31
|
+
## 使用
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
picgo notion scan # 只读,列出存放在 Notion 的图片
|
|
35
|
+
picgo notion scan --page <链接或id> --size
|
|
36
|
+
picgo notion scan --scan-mode blocks # 改用逐块读取
|
|
37
|
+
picgo notion migrate --dry-run # 演练,不做任何改动
|
|
38
|
+
picgo notion migrate --limit 5 # 先迁几张看看
|
|
39
|
+
picgo notion migrate # 全部迁移,开始前会确认
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
GUI 菜单里有「扫描」「全部迁移」「迁移一个页面」「停止」。进度每 10% 通知一次。如果 PicGo 设置里开着「上传前重命名」,插件会先提醒,因为每张图都会弹一次重命名窗口。
|
|
43
|
+
|
|
44
|
+
## 扫描方式
|
|
45
|
+
|
|
46
|
+
`scan` 和 `migrate` 都支持 `--scan-mode <markdown|blocks>`:
|
|
47
|
+
|
|
48
|
+
- `markdown`(默认):每个页面只发一个请求 `GET /v1/pages/{id}/markdown`,嵌套的块都在里面,每张存放在 Notion 的图片链接里带着它的块 id。超过约 20,000 个块的页面会被截断,缺的部分按 id 补读,每部分一个请求。某个页面被 Notion 拒绝(400 或 403)时,这个页面改为逐块读取;连续三次被拒且一次都没成功,剩下的扫描全部改用 `blocks`。
|
|
49
|
+
- `blocks`:逐层调用 `GET /v1/blocks/{id}/children`,每个页面和每个有子块的块(折叠块、分栏、标注……)各一个请求,每 100 个子块再加一个。
|
|
50
|
+
|
|
51
|
+
两种方式找到的图片相同。模板按钮这类 Markdown 显示不了的块,两种方式都会用块接口去读。
|
|
52
|
+
|
|
53
|
+
## 请求数
|
|
54
|
+
|
|
55
|
+
| 步骤 | 请求数 |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| 每个配置的页面 | 1,读取标题 |
|
|
58
|
+
| 每个页面,`markdown` | 1,超过约 20,000 个块时每个截断部分再加 1 |
|
|
59
|
+
| 每个页面,`blocks` | 每个有子块的块 1,每 100 个子块再加 1 |
|
|
60
|
+
| 每个数据库 | 1,每 100 行再加 1 |
|
|
61
|
+
| 没配置页面时的搜索 | 每 100 条结果 1 |
|
|
62
|
+
| 每张迁移的图片 | 2:先读块,再更新 |
|
|
63
|
+
| `scan --size` | 每张图 1,发往 Notion 文件存储,不算 API 请求 |
|
|
64
|
+
|
|
65
|
+
报告里的页面标题来自扫描时已经拿到的数据:搜索结果、数据库行和子页面链接。迁移时更新前重新读一次块,是为了拿到新的下载链接,并确认它还是同一张存放在 Notion 的图片,扫描之后被替换或删除的图片会跟随或跳过,不会被覆盖。所有请求共用一个约每秒 2.5 次的限速器,低于 Notion 每分钟 180 次的限制。
|
|
66
|
+
|
|
67
|
+
## 续跑
|
|
68
|
+
|
|
69
|
+
中断后重新运行同一条命令即可续跑:已完成的块会跳过,已上传但还没改 Notion 的块只补做更新,不会重复上传。日志和报告在 PicGo 配置目录下的 `notion-migrator/`。
|
|
70
|
+
|
|
71
|
+
## 隐私
|
|
72
|
+
|
|
73
|
+
Notion 里的文件是私有的,只能通过会过期的签名链接访问。大多数图床返回的是公开链接,任何拿到链接的人都能打开。迁移前确认这些图片可以公开,或者使用支持私有访问的图床;敏感页面可以用「排除」或 `--page` 避开。
|
|
74
|
+
|
|
75
|
+
## 限制
|
|
76
|
+
|
|
77
|
+
- 目前只迁移图片块。文件、PDF、视频、音频块,页面封面和图标,以及数据库文件属性还不支持。
|
|
78
|
+
- 不配置页面时依赖 Notion 搜索,搜索不保证返回全部页面;缺了就把父页面加到「页面」里。
|
|
79
|
+
- Notion API 列出的外链图片格式是 bmp、gif、heic、jpeg、jpg、png、svg、tif、tiff。WebP 等未列出的格式会迁移但在报告里给出警告;AVIF 会跳过。
|
|
80
|
+
- 外链超过 2000 个字符会被 Notion 拒绝,记为失败。
|
|
81
|
+
- 上传的文件名是 `<块 id>.<扩展名>`,避免重名;重命名插件和 PicGo 自己的重命名设置仍然生效。
|
|
82
|
+
|
|
83
|
+
更多细节见 [English README](./README.md)。
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.registerCli = void 0;
|
|
7
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const config_1 = require("./config");
|
|
10
|
+
const i18n_1 = require("./i18n");
|
|
11
|
+
const http_1 = require("./notion/http");
|
|
12
|
+
const ids_1 = require("./notion/ids");
|
|
13
|
+
const runner_1 = require("./runner");
|
|
14
|
+
const scanner_1 = require("./scanner");
|
|
15
|
+
const size_1 = require("./size");
|
|
16
|
+
const parseRoots = ($T, pages) => {
|
|
17
|
+
if (!pages || pages.length === 0) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
const { ids, invalid } = (0, ids_1.parseNotionIdList)(pages);
|
|
21
|
+
if (invalid.length > 0) {
|
|
22
|
+
throw new config_1.ConfigError($T('NOTION_MIGRATOR_INVALID_PAGES', { pages: invalid.join(', ') }));
|
|
23
|
+
}
|
|
24
|
+
return ids;
|
|
25
|
+
};
|
|
26
|
+
const parsePositiveInt = (value, name) => {
|
|
27
|
+
if (value === undefined) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const n = Number(value);
|
|
31
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
32
|
+
throw new config_1.ConfigError(`--${name} must be a non-negative integer`);
|
|
33
|
+
}
|
|
34
|
+
return n;
|
|
35
|
+
};
|
|
36
|
+
const parseScanMode = (value) => {
|
|
37
|
+
if (value === undefined) {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
const mode = scanner_1.SCAN_MODES.find(m => m === value.trim().toLowerCase());
|
|
41
|
+
if (!mode) {
|
|
42
|
+
throw new config_1.ConfigError(`--scan-mode must be one of: ${scanner_1.SCAN_MODES.join(', ')}`);
|
|
43
|
+
}
|
|
44
|
+
return mode;
|
|
45
|
+
};
|
|
46
|
+
const targetJson = (t) => ({
|
|
47
|
+
pageId: t.page.id,
|
|
48
|
+
pageTitle: t.page.title,
|
|
49
|
+
pageUrl: t.page.url,
|
|
50
|
+
blockId: t.blockId,
|
|
51
|
+
kind: t.kind,
|
|
52
|
+
fileName: t.fileName,
|
|
53
|
+
ext: t.ext,
|
|
54
|
+
size: t.size
|
|
55
|
+
});
|
|
56
|
+
const printScanText = (scan, withSize) => {
|
|
57
|
+
const byPage = new Map();
|
|
58
|
+
for (const t of scan.targets) {
|
|
59
|
+
byPage.set(t.page.id, [...(byPage.get(t.page.id) ?? []), t]);
|
|
60
|
+
}
|
|
61
|
+
for (const targets of byPage.values()) {
|
|
62
|
+
const page = targets[0].page;
|
|
63
|
+
console.log(`\n${page.title} ${page.url}`);
|
|
64
|
+
for (const t of targets) {
|
|
65
|
+
console.log(` ${t.blockId} ${t.fileName}${withSize ? ` ${(0, size_1.formatBytes)(t.size)}` : ''}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const handleError = (ctx, e) => {
|
|
70
|
+
if ((0, http_1.isAbortError)(e)) {
|
|
71
|
+
// Ctrl+C during the scan: nothing was changed.
|
|
72
|
+
ctx.log.warn((0, i18n_1.T)(ctx)('NOTION_MIGRATOR_STOPPED_TITLE'));
|
|
73
|
+
process.exitCode = 130;
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if ((0, runner_1.isExpectedError)(e)) {
|
|
77
|
+
ctx.log.error(e.message);
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
ctx.log.error(e);
|
|
81
|
+
}
|
|
82
|
+
process.exitCode = 1;
|
|
83
|
+
};
|
|
84
|
+
/** Ctrl+C stops after the current image; a second Ctrl+C quits immediately. */
|
|
85
|
+
const withInterrupt = async (ctx, $T, fn) => {
|
|
86
|
+
const controller = new AbortController();
|
|
87
|
+
const onSigint = () => {
|
|
88
|
+
if (controller.signal.aborted) {
|
|
89
|
+
process.exit(130);
|
|
90
|
+
}
|
|
91
|
+
ctx.log.warn($T('NOTION_MIGRATOR_STOPPING'));
|
|
92
|
+
controller.abort();
|
|
93
|
+
};
|
|
94
|
+
process.on('SIGINT', onSigint);
|
|
95
|
+
try {
|
|
96
|
+
return await fn(controller.signal);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
process.off('SIGINT', onSigint);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const scanCommand = async (ctx, flags) => {
|
|
103
|
+
const $T = (0, i18n_1.T)(ctx);
|
|
104
|
+
const quiet = flags.json === true;
|
|
105
|
+
const progress = (msg) => {
|
|
106
|
+
if (quiet) {
|
|
107
|
+
process.stderr.write(`${msg}\n`);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
ctx.log.info(msg);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const warn = (msg) => {
|
|
114
|
+
if (quiet) {
|
|
115
|
+
process.stderr.write(`warn: ${msg}\n`);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
ctx.log.warn(msg);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
await withInterrupt(ctx, $T, async (signal) => {
|
|
122
|
+
const rc = (0, runner_1.createRunContext)(ctx, $T, signal, warn);
|
|
123
|
+
const roots = parseRoots($T, flags.page);
|
|
124
|
+
const scan = await (0, runner_1.runScan)(rc, roots, {
|
|
125
|
+
mode: parseScanMode(flags.scanMode),
|
|
126
|
+
signal,
|
|
127
|
+
onPage: (page, stats) => {
|
|
128
|
+
if (stats.pages % 20 === 1) {
|
|
129
|
+
progress(`[${stats.pages}] ${page.title}`);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
onWarning: warn,
|
|
133
|
+
// Sizes are fetched as soon as a block is found, before its presigned URL expires.
|
|
134
|
+
onTarget: flags.size ? async (t) => { t.size = await (0, size_1.fetchFileSize)(rc.transport, t.url, signal); } : undefined
|
|
135
|
+
});
|
|
136
|
+
const json = scan.targets.map(targetJson);
|
|
137
|
+
if (flags.out) {
|
|
138
|
+
const out = node_path_1.default.resolve(flags.out);
|
|
139
|
+
node_fs_1.default.mkdirSync(node_path_1.default.dirname(out), { recursive: true });
|
|
140
|
+
node_fs_1.default.writeFileSync(out, `${JSON.stringify(json, null, 2)}\n`);
|
|
141
|
+
progress($T('NOTION_MIGRATOR_WROTE_FILE', { path: out }));
|
|
142
|
+
}
|
|
143
|
+
if (flags.json) {
|
|
144
|
+
console.log(JSON.stringify(json, null, 2));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
printScanText(scan, flags.size === true);
|
|
148
|
+
const total = scan.targets.reduce((sum, t) => sum + (t.size ?? 0), 0);
|
|
149
|
+
console.log('');
|
|
150
|
+
ctx.log.success($T('NOTION_MIGRATOR_SCAN_SUMMARY', {
|
|
151
|
+
images: String(scan.targets.length),
|
|
152
|
+
pages: String((0, runner_1.countByPage)(scan).length),
|
|
153
|
+
scanned: String(scan.stats.pages)
|
|
154
|
+
}) + (flags.size ? ` (${(0, size_1.formatBytes)(total)})` : ''));
|
|
155
|
+
if (scan.warnings.length > 0) {
|
|
156
|
+
ctx.log.warn($T('NOTION_MIGRATOR_SCAN_WARNINGS', { count: String(scan.warnings.length) }));
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
const printReport = (ctx, $T, report) => {
|
|
161
|
+
if (report.cancelled) {
|
|
162
|
+
ctx.log.warn($T('NOTION_MIGRATOR_CANCELLED'));
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const counts = {
|
|
166
|
+
migrated: String(report.migrated),
|
|
167
|
+
failed: String(report.failed),
|
|
168
|
+
skipped: String(report.skipped),
|
|
169
|
+
pending: String(report.pending)
|
|
170
|
+
};
|
|
171
|
+
const line = $T(report.dryRun ? 'NOTION_MIGRATOR_DRY_RUN_SUMMARY' : 'NOTION_MIGRATOR_DONE_BODY', counts);
|
|
172
|
+
if (report.failed > 0) {
|
|
173
|
+
ctx.log.warn(line);
|
|
174
|
+
for (const item of report.items.filter(i => i.status === 'failed')) {
|
|
175
|
+
ctx.log.warn(` ${item.blockId} ${item.fileName} [${item.stage ?? ''}] ${item.reason ?? ''}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
ctx.log.success(line);
|
|
180
|
+
}
|
|
181
|
+
if (report.aborted && !report.dryRun) {
|
|
182
|
+
ctx.log.warn($T('NOTION_MIGRATOR_STOPPED_TITLE'));
|
|
183
|
+
}
|
|
184
|
+
if (report.reportPath) {
|
|
185
|
+
ctx.log.info($T('NOTION_MIGRATOR_REPORT_SAVED', { path: report.reportPath }));
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const migrateCommand = async (ctx, flags) => {
|
|
189
|
+
const $T = (0, i18n_1.T)(ctx);
|
|
190
|
+
await withInterrupt(ctx, $T, async (signal) => {
|
|
191
|
+
const rc = (0, runner_1.createRunContext)(ctx, $T, signal);
|
|
192
|
+
const roots = parseRoots($T, flags.page);
|
|
193
|
+
const limit = parsePositiveInt(flags.limit, 'limit');
|
|
194
|
+
const batchSize = parsePositiveInt(flags.batchSize, 'batch-size');
|
|
195
|
+
const scan = await (0, runner_1.runScan)(rc, roots, {
|
|
196
|
+
mode: parseScanMode(flags.scanMode),
|
|
197
|
+
signal,
|
|
198
|
+
onPage: (page, stats) => {
|
|
199
|
+
if (stats.pages % 20 === 1) {
|
|
200
|
+
ctx.log.info(`[${stats.pages}] ${page.title}`);
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
onWarning: msg => { ctx.log.warn(msg); }
|
|
204
|
+
});
|
|
205
|
+
const uploader = (0, runner_1.currentUploader)(ctx);
|
|
206
|
+
const report = await (0, runner_1.runMigrate)(rc, scan, {
|
|
207
|
+
dryRun: flags.dryRun,
|
|
208
|
+
limit,
|
|
209
|
+
batchSize: batchSize && batchSize > 0 ? batchSize : undefined,
|
|
210
|
+
signal,
|
|
211
|
+
confirm: async (plan) => {
|
|
212
|
+
const resumed = plan.actionable.filter(i => i.uploadedUrl).length;
|
|
213
|
+
ctx.log.info($T('NOTION_MIGRATOR_PLAN', {
|
|
214
|
+
count: String(plan.actionable.length),
|
|
215
|
+
resumed: String(resumed),
|
|
216
|
+
skipped: String(plan.skipped.length)
|
|
217
|
+
}));
|
|
218
|
+
if (flags.yes) {
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
if (!process.stdin.isTTY) {
|
|
222
|
+
ctx.log.warn($T('NOTION_MIGRATOR_NEED_YES'));
|
|
223
|
+
// Nothing was migrated; a script must not read this as success.
|
|
224
|
+
process.exitCode = 1;
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
const answer = await ctx.cmd.inquirer.prompt([{
|
|
228
|
+
type: 'confirm',
|
|
229
|
+
name: 'ok',
|
|
230
|
+
message: $T('NOTION_MIGRATOR_CONFIRM_MESSAGE', { count: String(plan.actionable.length), uploader }),
|
|
231
|
+
default: false
|
|
232
|
+
}]);
|
|
233
|
+
return answer.ok;
|
|
234
|
+
},
|
|
235
|
+
onProgress: p => {
|
|
236
|
+
ctx.log.info(`[${p.done}/${p.total}] ${$T('NOTION_MIGRATOR_PROGRESS_BODY', { migrated: String(p.migrated), failed: String(p.failed) })}`);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
printReport(ctx, $T, report);
|
|
240
|
+
if (report.dryRun) {
|
|
241
|
+
for (const item of report.items.filter(i => i.status === 'pending')) {
|
|
242
|
+
console.log(` ${item.blockId} ${item.fileName} ${item.pageTitle}${item.resumed ? ' (uploaded, update only)' : ''}${item.warning ? ` ! ${item.warning}` : ''}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (report.failed > 0) {
|
|
246
|
+
process.exitCode = 1;
|
|
247
|
+
}
|
|
248
|
+
else if (report.aborted && !report.cancelled) {
|
|
249
|
+
process.exitCode = 130;
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
};
|
|
253
|
+
const registerCli = (ctx) => {
|
|
254
|
+
ctx.cmd.register('notion', {
|
|
255
|
+
handle(ctx) {
|
|
256
|
+
const program = ctx.cmd.program;
|
|
257
|
+
const notion = program
|
|
258
|
+
.command('notion')
|
|
259
|
+
.description('move Notion-hosted images to your image host');
|
|
260
|
+
notion
|
|
261
|
+
.command('scan')
|
|
262
|
+
.description('list Notion-hosted image blocks (read-only)')
|
|
263
|
+
.option('-p, --page <idOrUrl...>', 'page or database URL/id to scan (default: config, then everything the token can see)')
|
|
264
|
+
.option('--scan-mode <mode>', 'markdown (default, one request per page) or blocks (one request per block with children)')
|
|
265
|
+
.option('--json', 'print JSON instead of text')
|
|
266
|
+
.option('-o, --out <file>', 'write the result as JSON to a file')
|
|
267
|
+
.option('--size', 'fetch each file size (one extra request per image)')
|
|
268
|
+
.action(async (flags) => {
|
|
269
|
+
try {
|
|
270
|
+
await scanCommand(ctx, flags);
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
handleError(ctx, e);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
notion
|
|
277
|
+
.command('migrate')
|
|
278
|
+
.description('upload Notion-hosted images through PicGo and switch the blocks to the new URLs')
|
|
279
|
+
.option('-p, --page <idOrUrl...>', 'page or database URL/id to migrate (default: config, then everything the token can see)')
|
|
280
|
+
.option('--scan-mode <mode>', 'markdown (default, one request per page) or blocks (one request per block with children)')
|
|
281
|
+
.option('--dry-run', 'show what would be migrated without changing anything')
|
|
282
|
+
.option('-n, --limit <n>', 'migrate at most n images')
|
|
283
|
+
.option('-y, --yes', 'skip the confirmation')
|
|
284
|
+
.option('--batch-size <n>', 'images per upload batch (default 5)')
|
|
285
|
+
.action(async (flags) => {
|
|
286
|
+
try {
|
|
287
|
+
await migrateCommand(ctx, flags);
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
handleError(ctx, e);
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
.on('--help', () => {
|
|
294
|
+
console.log([
|
|
295
|
+
'',
|
|
296
|
+
'Examples:',
|
|
297
|
+
' $ picgo notion scan --page https://www.notion.so/My-Page-0123456789abcdef0123456789abcdef',
|
|
298
|
+
' $ picgo notion migrate --dry-run',
|
|
299
|
+
' $ picgo notion migrate --limit 5',
|
|
300
|
+
'',
|
|
301
|
+
`Progress is journaled in ${node_path_1.default.join(ctx.baseDir, 'notion-migrator', 'journal.jsonl')}; re-running resumes.`
|
|
302
|
+
].join('\n'));
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
};
|
|
307
|
+
exports.registerCli = registerCli;
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { IPicGo, IPluginConfig } from 'picgo';
|
|
2
|
+
import type { Translate } from './i18n';
|
|
3
|
+
export declare const PLUGIN_NAME = "picgo-plugin-notion-migrator";
|
|
4
|
+
export declare const CONFIG_KEY = "picgo-plugin-notion-migrator";
|
|
5
|
+
export interface UserConfig {
|
|
6
|
+
token?: string;
|
|
7
|
+
rootPages?: string;
|
|
8
|
+
include?: string;
|
|
9
|
+
exclude?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface Settings {
|
|
12
|
+
token: string;
|
|
13
|
+
rootPages: string[];
|
|
14
|
+
include?: RegExp;
|
|
15
|
+
exclude?: RegExp;
|
|
16
|
+
}
|
|
17
|
+
export declare class ConfigError extends Error {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
export declare const getUserConfig: (ctx: IPicGo) => UserConfig;
|
|
21
|
+
/**
|
|
22
|
+
* Reads and validates the plugin config. `NOTION_TOKEN` overrides the saved token.
|
|
23
|
+
* Throws ConfigError with a message meant for the user.
|
|
24
|
+
*/
|
|
25
|
+
export declare const getSettings: (ctx: IPicGo, $T: Translate, env?: NodeJS.ProcessEnv) => Settings;
|
|
26
|
+
export declare const dataDir: (ctx: IPicGo) => string;
|
|
27
|
+
export declare const journalPath: (ctx: IPicGo) => string;
|
|
28
|
+
export declare const reportsDir: (ctx: IPicGo) => string;
|
|
29
|
+
/**
|
|
30
|
+
* Test hooks, not shown in the UI: point the client at a mock server and change the request rate.
|
|
31
|
+
*/
|
|
32
|
+
export declare const apiOverrides: (env?: NodeJS.ProcessEnv) => {
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
requestsPerSecond?: number;
|
|
35
|
+
};
|
|
36
|
+
export declare const pluginConfig: (ctx: IPicGo, $T: Translate) => IPluginConfig[];
|