|
| 1 | +<!-- |
| 2 | + - Copyright (c) 2023, Terwer . All rights reserved. |
| 3 | + - DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 4 | + - |
| 5 | + - This code is free software; you can redistribute it and/or modify it |
| 6 | + - under the terms of the GNU General Public License version 2 only, as |
| 7 | + - published by the Free Software Foundation. Terwer designates this |
| 8 | + - particular file as subject to the "Classpath" exception as provided |
| 9 | + - by Terwer in the LICENSE file that accompanied this code. |
| 10 | + - |
| 11 | + - This code is distributed in the hope that it will be useful, but WITHOUT |
| 12 | + - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 13 | + - FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 14 | + - version 2 for more details (a copy is included in the LICENSE file that |
| 15 | + - accompanied this code). |
| 16 | + - |
| 17 | + - You should have received a copy of the GNU General Public License version |
| 18 | + - 2 along with this work; if not, write to the Free Software Foundation, |
| 19 | + - Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
| 20 | + - |
| 21 | + - Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com |
| 22 | + - or visit www.terwer.space if you need additional information or have any |
| 23 | + - questions. |
| 24 | + --> |
| 25 | + |
| 26 | +<script lang="ts"> |
| 27 | + import { showMessage } from "siyuan" |
| 28 | + import ImporterPlugin from "../index" |
| 29 | + import { removeEmptyLines, removeFootnotes, removeLinks, replaceImagePath } from "../utils/utils" |
| 30 | + import { onMount } from "svelte" |
| 31 | + import { loadImporterConfig, saveImporterConfig } from "../store/config" |
| 32 | + import { isDev, workspaceDir } from "../Constants" |
| 33 | +
|
| 34 | + export let pluginInstance: ImporterPlugin |
| 35 | + export let dialog |
| 36 | +
|
| 37 | + let importerConfig |
| 38 | + let notebooks = [] |
| 39 | + let toNotebookId |
| 40 | + let toNotebookName |
| 41 | + //用户指南不应该作为可以写入的笔记本 |
| 42 | + const hiddenNotebook: Set<string> = new Set(["思源笔记用户指南", "SiYuan User Guide"]) |
| 43 | + let tempCount = 0 |
| 44 | +
|
| 45 | + // ================= |
| 46 | + // 单文件转换开始 |
| 47 | + // ================= |
| 48 | + const selectFile = async ( |
| 49 | + event: InputEvent & { |
| 50 | + target: HTMLInputElement |
| 51 | + } |
| 52 | + ) => { |
| 53 | + pluginInstance.logger.debug(`${pluginInstance.i18n.startImport}...`) |
| 54 | + dialog.destroy() |
| 55 | +
|
| 56 | + // showMessage(`文件上传中,请稍后...`, 1000, "info") |
| 57 | + const files = event.target.files ?? [] |
| 58 | + if (files.length === 0) { |
| 59 | + showMessage(`${pluginInstance.i18n.msgFileNotEmpty}`, 7000, "error") |
| 60 | + return |
| 61 | + } |
| 62 | + const file = files[0] |
| 63 | +
|
| 64 | + // 给个提示,免得用户以为界面是卡主了 |
| 65 | + showMessage(`${pluginInstance.i18n.msgConverting} ${file.name}...`, 1000, "info") |
| 66 | + await doImport(file) |
| 67 | + } |
| 68 | +
|
| 69 | + const doImport = async function (file: any) { |
| 70 | + const fromFilename = file.name |
| 71 | + let filename = fromFilename.substring(0, fromFilename.lastIndexOf(".")) |
| 72 | + // 去除标题多余的空格,包括开始中间以及结尾的空格 |
| 73 | + filename = filename.replace(/\s+/g, "") |
| 74 | +
|
| 75 | + const fromFilePath = `/temp/convert/pandoc/${fromFilename}` |
| 76 | + const uploadResult = await pluginInstance.kernelApi.putFile(fromFilePath, file) |
| 77 | + if (uploadResult.code !== 0) { |
| 78 | + showMessage(`${pluginInstance.i18n.msgFileUploadError}:${uploadResult.msg}`, 7000, "error") |
| 79 | + return |
| 80 | + } |
| 81 | +
|
| 82 | + // 文件转换 |
| 83 | + let toFilename = `${filename}.md` |
| 84 | + let toFilePath = `/temp/convert/pandoc/${toFilename}` |
| 85 | + const ext = fromFilename.split(".").pop().toLowerCase() |
| 86 | + // 不是 md 才需要转换 |
| 87 | + if (ext !== "md") { |
| 88 | + const convertResult = await pluginInstance.kernelApi.convertPandoc( |
| 89 | + "markdown_strict-raw_html", |
| 90 | + fromFilename, |
| 91 | + toFilename |
| 92 | + ) |
| 93 | + if (convertResult.code !== 0) { |
| 94 | + showMessage(`${pluginInstance.i18n.msgFileConvertError}:${convertResult.msg}`, 7000, "error") |
| 95 | + return |
| 96 | + } |
| 97 | +
|
| 98 | + // 读取文件 |
| 99 | + let mdText = (await pluginInstance.kernelApi.getFile(toFilePath, "text")) ?? "" |
| 100 | + if (mdText === "") { |
| 101 | + showMessage(pluginInstance.i18n.msgFileConvertEmpty, 7000, "error") |
| 102 | + return |
| 103 | + } |
| 104 | +
|
| 105 | + // 文本处理 |
| 106 | + // 删除目录中链接 |
| 107 | + mdText = removeLinks(mdText) |
| 108 | + // 去除空行 |
| 109 | + mdText = removeEmptyLines(mdText) |
| 110 | + // 资源路径 |
| 111 | + mdText = replaceImagePath(mdText) |
| 112 | + // 去除脚注 |
| 113 | + mdText = removeFootnotes(mdText) |
| 114 | + await pluginInstance.kernelApi.saveTextData(`${toFilename}`, mdText) |
| 115 | + } |
| 116 | +
|
| 117 | + // 导入 MD 文档 |
| 118 | + const localPath = `${workspaceDir}/temp/convert/pandoc/${toFilename}` |
| 119 | + const mdResult = await pluginInstance.kernelApi.importStdMd(localPath, toNotebookId, `/`) |
| 120 | + if (mdResult.code !== 0) { |
| 121 | + showMessage(`${pluginInstance.i18n.msgDocCreateFailed}=>${toFilePath}`, 7000, "error") |
| 122 | + } |
| 123 | +
|
| 124 | + // 打开笔记本 |
| 125 | + await pluginInstance.kernelApi.openNotebook(toNotebookId) |
| 126 | +
|
| 127 | + showMessage(pluginInstance.i18n.msgImportSuccess, 5000, "info") |
| 128 | + } |
| 129 | + // ================= |
| 130 | + // 单文件转换结束 |
| 131 | + // ================= |
| 132 | +
|
| 133 | + // ================= |
| 134 | + // 批量转换开始 |
| 135 | + // ================= |
| 136 | + const selectFolder = async () => { |
| 137 | + // 批量导入之前先清空临时文件 |
| 138 | + if (tempCount > 0) { |
| 139 | + showMessage(`${pluginInstance.i18n.tempCountExists}`, 1000, "error") |
| 140 | + return |
| 141 | + } |
| 142 | +
|
| 143 | + const result = await window.showDirectoryPicker() |
| 144 | + dialog.destroy() |
| 145 | +
|
| 146 | + const allowedExtensions = ["docx", "epub", "md", "html", "opml"] |
| 147 | +
|
| 148 | + const entries = await result.values() |
| 149 | + for await (const entry of entries) { |
| 150 | + if (entry.kind === "directory") { |
| 151 | + continue |
| 152 | + } |
| 153 | +
|
| 154 | + const fileName = entry.name |
| 155 | + const ext = fileName.split(".").pop().toLowerCase() |
| 156 | +
|
| 157 | + if (!allowedExtensions.includes(ext)) { |
| 158 | + console.warn(`${pluginInstance.i18n.importTipNotAllowed} ${fileName}`) |
| 159 | + continue |
| 160 | + } |
| 161 | +
|
| 162 | + // 循环上传并转换 |
| 163 | + showMessage(`${fileName} ${pluginInstance.i18n.msgConverting}...`, 5000, "info") |
| 164 | + const file = await readFile(entry) |
| 165 | + await doUploadAndConvert(file) |
| 166 | + } |
| 167 | +
|
| 168 | + // 文件夹批量导入 |
| 169 | + await doBatchImport() |
| 170 | + } |
| 171 | +
|
| 172 | + const doUploadAndConvert = async (file: any) => { |
| 173 | + const fromFilename = file.name |
| 174 | + let filename = fromFilename.substring(0, fromFilename.lastIndexOf(".")) |
| 175 | + // 去除标题多余的空格,包括开始中间以及结尾的空格 |
| 176 | + filename = filename.replace(/\s+/g, "") |
| 177 | +
|
| 178 | + const fromFilePath = `/temp/convert/pandoc/${fromFilename}` |
| 179 | + const uploadResult = await pluginInstance.kernelApi.putFile(fromFilePath, file) |
| 180 | + if (uploadResult.code !== 0) { |
| 181 | + showMessage(`${pluginInstance.i18n.msgFileUploadError}:${uploadResult.msg}`, 7000, "error") |
| 182 | + return |
| 183 | + } |
| 184 | +
|
| 185 | + // 文件转换 |
| 186 | + let toFilename = `${filename}.md` |
| 187 | + let toFilePath = `/temp/convert/pandoc/${toFilename}` |
| 188 | + const ext = fromFilename.split(".").pop().toLowerCase() |
| 189 | + // 不是 md 才需要转换 |
| 190 | + if (ext !== "md") { |
| 191 | + const convertResult = await pluginInstance.kernelApi.convertPandoc( |
| 192 | + "markdown_strict-raw_html", |
| 193 | + fromFilename, |
| 194 | + toFilename |
| 195 | + ) |
| 196 | + if (convertResult.code !== 0) { |
| 197 | + showMessage(`${pluginInstance.i18n.msgFileConvertError}:${convertResult.msg}`, 7000, "error") |
| 198 | + return |
| 199 | + } |
| 200 | +
|
| 201 | + // 读取文件 |
| 202 | + let mdText = (await pluginInstance.kernelApi.getFile(toFilePath, "text")) ?? "" |
| 203 | + if (mdText === "") { |
| 204 | + showMessage(pluginInstance.i18n.msgFileConvertEmpty, 7000, "error") |
| 205 | + return |
| 206 | + } |
| 207 | +
|
| 208 | + // 文本处理 |
| 209 | + // 删除目录中链接 |
| 210 | + mdText = removeLinks(mdText) |
| 211 | + // 去除空行 |
| 212 | + mdText = removeEmptyLines(mdText) |
| 213 | + // 资源路径 |
| 214 | + mdText = replaceImagePath(mdText) |
| 215 | + // 去除脚注 |
| 216 | + mdText = removeFootnotes(mdText) |
| 217 | + await pluginInstance.kernelApi.saveTextData(`${toFilename}`, mdText) |
| 218 | + } |
| 219 | + } |
| 220 | +
|
| 221 | + const doBatchImport = async (toNotebookId,) => { |
| 222 | + // 导入 MD 文档 |
| 223 | + const localPath = `${workspaceDir}/temp/convert/pandoc` |
| 224 | + const mdResult = await pluginInstance.kernelApi.importStdMd(localPath, toNotebookId, `/`) |
| 225 | + if (mdResult.code !== 0) { |
| 226 | + showMessage(`${pluginInstance.i18n.msgDocCreateFailed}=>${toFilePath}`, 7000, "error") |
| 227 | + } |
| 228 | +
|
| 229 | + // 打开笔记本 |
| 230 | + await pluginInstance.kernelApi.openNotebook(toNotebookId) |
| 231 | +
|
| 232 | + showMessage(pluginInstance.i18n.msgImportSuccess, 5000, "info") |
| 233 | + } |
| 234 | +
|
| 235 | + /** |
| 236 | + * 读取文件 |
| 237 | + * @param entry |
| 238 | + */ |
| 239 | + const readFile = async (entry) => { |
| 240 | + const file = await entry.getFile() |
| 241 | + const reader = new FileReader() |
| 242 | + reader.readAsArrayBuffer(file) |
| 243 | + return new Promise((resolve, reject) => { |
| 244 | + reader.onload = () => { |
| 245 | + const arrayBuffer = reader.result |
| 246 | + const fileContent = new Blob([arrayBuffer], { type: file.type }) |
| 247 | + const fileName = file.name |
| 248 | + resolve(new File([fileContent], fileName)) |
| 249 | + } |
| 250 | + reader.onerror = reject |
| 251 | + }) |
| 252 | + } |
| 253 | + // ================= |
| 254 | + // 批量转换结束 |
| 255 | + // ================= |
| 256 | +
|
| 257 | + const cleanTemp = async () => { |
| 258 | + const tempPath = `/temp/convert/pandoc` |
| 259 | + await pluginInstance.kernelApi.removeFile(`${tempPath}`) |
| 260 | + await reloadTempFiles() |
| 261 | +
|
| 262 | + showMessage(pluginInstance.i18n.msgTempFileCleaned, 5000, "info") |
| 263 | + } |
| 264 | +
|
| 265 | + const notebookChange = async function () { |
| 266 | + // 显示当前选择的名称 |
| 267 | + const currentNotebook = notebooks.find((n) => n.id === toNotebookId) |
| 268 | + toNotebookName = currentNotebook.name |
| 269 | +
|
| 270 | + importerConfig = await loadImporterConfig(pluginInstance) |
| 271 | + importerConfig.notebook = toNotebookId |
| 272 | +
|
| 273 | + await saveImporterConfig(pluginInstance, importerConfig) |
| 274 | + pluginInstance.logger.info(`${pluginInstance.i18n.notebookConfigUpdated}=>`, toNotebookId) |
| 275 | + } |
| 276 | +
|
| 277 | + const reloadTempFiles = async () => { |
| 278 | + const tempPath = `/temp/convert/pandoc` |
| 279 | + // 临时文件 |
| 280 | + const tempFiles = await pluginInstance.kernelApi.readDir(tempPath) |
| 281 | + if (tempFiles.code === 0 && tempFiles.data.length > 0) { |
| 282 | + tempCount = tempFiles.data.length |
| 283 | + } |
| 284 | + if (tempFiles.code === 404) { |
| 285 | + tempCount = 0 |
| 286 | + } |
| 287 | + } |
| 288 | +
|
| 289 | + onMount(async () => { |
| 290 | + await reloadTempFiles() |
| 291 | +
|
| 292 | + // 加载配置 |
| 293 | + importerConfig = await loadImporterConfig(pluginInstance) |
| 294 | +
|
| 295 | + const res = await pluginInstance.kernelApi.lsNotebooks() |
| 296 | + const data = res.data as any |
| 297 | + notebooks = data.notebooks ?? [] |
| 298 | + // 没有必要把所有笔记本都列出来 |
| 299 | + notebooks = notebooks.filter((notebook) => !notebook.closed && !hiddenNotebook.has(notebook.name)) |
| 300 | + // 选中,若是没保存,获取第一个 |
| 301 | + toNotebookId = importerConfig?.notebook ?? notebooks[0].id |
| 302 | + const currentNotebook = notebooks.find((n) => n.id === toNotebookId) |
| 303 | + toNotebookName = currentNotebook.name |
| 304 | +
|
| 305 | + pluginInstance.logger.info(`${pluginInstance.i18n.selected} [${toNotebookName}] toNotebookId=>`, toNotebookId) |
| 306 | + }) |
| 307 | +</script> |
| 308 | + |
| 309 | +<div class="b3-dialog__content importer-form-container"> |
| 310 | + <div class="config__tab-container"> |
| 311 | + <label class="fn__flex b3-label config__item"> |
| 312 | + <div class="fn__flex-1"> |
| 313 | + {pluginInstance.i18n.targetNotebook} |
| 314 | + <div class="b3-label__text"> |
| 315 | + {pluginInstance.i18n.selectNotebookTip}<span class="selected">[{toNotebookName}]</span> |
| 316 | + </div> |
| 317 | + </div> |
| 318 | + <span class="fn__space" /> |
| 319 | + <select |
| 320 | + id="blockEmbedMode" |
| 321 | + class="b3-select fn__flex-center fn__size200" |
| 322 | + bind:value={toNotebookId} |
| 323 | + on:change={notebookChange} |
| 324 | + > |
| 325 | + {#each notebooks as notebook} |
| 326 | + <option value={notebook.id}>{notebook.name}</option> |
| 327 | + {:else} |
| 328 | + <option value="0">{pluginInstance.i18n.loading}...</option> |
| 329 | + {/each} |
| 330 | + </select> |
| 331 | + </label> |
| 332 | + |
| 333 | + <div class="fn__flex b3-label config__item"> |
| 334 | + <div class="fn__flex-1 fn__flex-center"> |
| 335 | + {pluginInstance.i18n.importFile} |
| 336 | + <div class="b3-label__text">{pluginInstance.i18n.importTip}</div> |
| 337 | + </div> |
| 338 | + <span class="fn__space" /> |
| 339 | + <button class="b3-button b3-button--outline fn__flex-center fn__size200" style="position: relative"> |
| 340 | + <input |
| 341 | + id="importData" |
| 342 | + class="b3-form__upload" |
| 343 | + type="file" |
| 344 | + accept=".md,.docx,.epub,.html,.opml" |
| 345 | + on:change={selectFile} |
| 346 | + /> |
| 347 | + <svg> |
| 348 | + <use xlink:href="#iconDownload" /> |
| 349 | + </svg>{pluginInstance.i18n.startImport} |
| 350 | + </button> |
| 351 | + </div> |
| 352 | + |
| 353 | + <div class="fn__flex b3-label config__item"> |
| 354 | + <div class="fn__flex-1 fn__flex-center"> |
| 355 | + {pluginInstance.i18n.importFolder} |
| 356 | + <div class="b3-label__text"> |
| 357 | + {pluginInstance.i18n.importFolderTip}<span class="selected">{pluginInstance.i18n.importNotRecursive}</span> |
| 358 | + </div> |
| 359 | + </div> |
| 360 | + <span class="fn__space" /> |
| 361 | + <button class="b3-button b3-button--outline fn__flex-center fn__size200" style="position: relative"> |
| 362 | + <input id="batchImportData" class="b3-form__upload" on:click={selectFolder} /> |
| 363 | + <svg> |
| 364 | + <use xlink:href="#iconDownload" /> |
| 365 | + </svg>{pluginInstance.i18n.importFolder} |
| 366 | + </button> |
| 367 | + </div> |
| 368 | + |
| 369 | + <div class="fn__flex b3-label config__item"> |
| 370 | + <div class="fn__flex-1 fn__flex-center"> |
| 371 | + {pluginInstance.i18n.cleanTemp} |
| 372 | + <div class="b3-label__text"> |
| 373 | + {pluginInstance.i18n.tempTotal} <span class="selected"> [ {tempCount} ] </span> |
| 374 | + {pluginInstance.i18n.tempCount} |
| 375 | + </div> |
| 376 | + </div> |
| 377 | + <span class="fn__space" /> |
| 378 | + <button |
| 379 | + id="removeAll" |
| 380 | + class="b3-button b3-button--outline fn__flex-center fn__size200" |
| 381 | + style="position: relative" |
| 382 | + > |
| 383 | + <input id="batchRemoveData" class="b3-form__upload" on:click={cleanTemp} /> |
| 384 | + <svg class="svg"><use xlink:href="#iconTrashcan" /></svg> |
| 385 | + {pluginInstance.i18n.clean} |
| 386 | + </button> |
| 387 | + </div> |
| 388 | + |
| 389 | + <div class="fn__flex b3-label config__item">{pluginInstance.i18n.supportedTypes}</div> |
| 390 | + </div> |
| 391 | +</div> |
| 392 | + |
| 393 | +<style> |
| 394 | + .importer-form-container .config__tab-container { |
| 395 | + height: unset; |
| 396 | + } |
| 397 | +
|
| 398 | + .selected { |
| 399 | + color: red; |
| 400 | + padding: 0 4px; |
| 401 | + } |
| 402 | +</style> |
0 commit comments