Skip to content

Commit

Permalink
feat: config update
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Mar 21, 2024
1 parent 95ebc61 commit af4a2f1
Show file tree
Hide file tree
Showing 9 changed files with 166 additions and 62 deletions.
95 changes: 63 additions & 32 deletions libs/Universal-PicGo-Core/src/api/SiyuanPicGoUploadApi.ts
Expand Up @@ -45,35 +45,26 @@ export const SIYUAN_PICGO_FILE_MAP_KEY = "custom-picgo-file-map-key"
class SiyuanPicGoUploadApi {
private readonly picgo: IPicGo
private readonly logger: ILogger
public cfgUpdating: boolean

constructor(isDev?: boolean) {
let cfgfolder = ""
let picgo_cfg_160 = ""
// 初始化 PicGO
this.picgo = new UniversalPicGo("", "", isDev)
this.logger = this.picgo.getLogger("siyuan-picgo-upload-api")
this.cfgUpdating = false

// =================================================================================================================

// 迁移旧插件配置
let legacyCfgfolder = ""
// 初始化思源 PicGO 配置
const workspaceDir = win?.siyuan?.config?.system?.workspaceDir ?? ""
if (hasNodeEnv && workspaceDir !== "") {
const path = win.require("path")
cfgfolder = path.join(workspaceDir, "data", "storage", "syp", "picgo")
picgo_cfg_160 = path.join(cfgfolder, "picgo.cfg.json")
}

// 初始化 PicGO
this.picgo = new UniversalPicGo(picgo_cfg_160, "", isDev)
this.logger = this.picgo.getLogger("siyuan-picgo-upload-api")

// 迁移旧插件
if (hasNodeEnv && cfgfolder !== "") {
legacyCfgfolder = path.join(workspaceDir, "data", "storage", "syp", "picgo")
// 如果新插件采用了不同的目录,需要迁移旧插件 node_modules 文件夹
if (cfgfolder !== this.picgo.pluginBaseDir) {
const path = win.require("path")

const plugin_dir_070 = path.join(cfgfolder, "node_modules")
const pkg_070 = path.join(cfgfolder, "package.json")
const plugin_dir_160 = path.join(this.picgo.pluginBaseDir, "node_modules")
const pkg_160 = path.join(this.picgo.pluginBaseDir, "package.json")

this.moveFile(plugin_dir_070, plugin_dir_160)
this.moveFile(pkg_070, pkg_160)
if (legacyCfgfolder !== this.picgo.baseDir) {
void this.moveFile(legacyCfgfolder, this.picgo.baseDir)
}
}

Expand Down Expand Up @@ -101,27 +92,67 @@ class SiyuanPicGoUploadApi {

// ===================================================================================================================

private moveFile(from: string, to: string) {
private async moveFile(from: string, to: string) {
const fs = win.fs
const path = win.require("path")
const exist = pathExistsSync(fs, path, from)
const existFrom = pathExistsSync(fs, path, from)
const existTo = pathExistsSync(fs, path, to)

if (!existFrom) {
return
}

// 存在旧文件采取迁移
if (exist) {
this.logger.info(`will move ${from} to ${to}`)
// 目的地存在复制
if (existTo) {
fs.promises.cp(from, to).catch((e: any) => {
this.cfgUpdating = true
this.logger.info(`will move ${from} to ${to}`)
// 目的地存在复制
if (existTo) {
this.copyFolder(from, to)
.then(() => {
this.cfgUpdating = false
})
.catch((e: any) => {
this.cfgUpdating = false
this.logger.error(`copy ${from} to ${to} failed: ${e}`)
})
} else {
// 不存在移动过去
fs.promises.rename(from, to).catch((e: any) => {
} else {
// 不存在移动过去
fs.promises
.rename(from, to)
.then(() => {
this.cfgUpdating = false
})
.catch((e: any) => {
this.cfgUpdating = false
this.logger.error(`move ${from} to ${to} failed: ${e}`)
})
}
}

private async copyFolder(from: string, to: string) {
const fs = win.fs
const path = win.require("path")

const files = await fs.promises.readdir(from)
for (const file of files) {
if (file.startsWith(".")) {
continue
}
const sourcePath = path.join(from, file)
const destPath = path.join(to, file)

const stats = await fs.promises.lstat(sourcePath)
if (stats.isDirectory()) {
await fs.promises.mkdir(destPath, { recursive: true })
// 递归复制子文件夹
await this.copyFolder(sourcePath, destPath)
} else {
await fs.promises.copyFile(sourcePath, destPath)
}
}

// 删除源文件夹
await fs.promises.rmdir(from, { recursive: true })
}
}

Expand Down
16 changes: 11 additions & 5 deletions libs/Universal-PicGo-Core/src/core/UniversalPicGo.ts
Expand Up @@ -17,9 +17,8 @@ import {
IPicGo,
IPicGoPlugin,
IPicGoPluginInterface,
IPicGoRequest,
IPluginLoader,
IStringKeyMap,
IStringKeyMap
} from "../types"
import { Lifecycle } from "./Lifecycle"
import uploaders from "../plugins/uploader"
Expand Down Expand Up @@ -91,7 +90,7 @@ class UniversalPicGo extends EventEmitter implements IPicGo {
uploader: new LifecyclePlugins("uploader"),
beforeTransformPlugins: new LifecyclePlugins("beforeTransformPlugins"),
beforeUploadPlugins: new LifecyclePlugins("beforeUploadPlugins"),
afterUploadPlugins: new LifecyclePlugins("afterUploadPlugins"),
afterUploadPlugins: new LifecyclePlugins("afterUploadPlugins")
}
this.initConfigPath()
// this.cmd = new Commander(this)
Expand Down Expand Up @@ -166,7 +165,7 @@ class UniversalPicGo extends EventEmitter implements IPicGo {
_.set(this._config, name, config[name])
eventBus.emit(IBusEvent.CONFIG_CHANGE, {
configName: name,
value: config[name],
value: config[name]
})
})
}
Expand Down Expand Up @@ -233,8 +232,9 @@ class UniversalPicGo extends EventEmitter implements IPicGo {
if (hasNodeEnv) {
const os = win.require("os")
const fs = win.fs
const path = win.require("path")
const { homedir } = os
const dir = homedir() + "/.universal-picgo"
const dir = path.join(homedir(), ".universal-picgo")
ensureFolderSync(fs, dir)
return dir
} else {
Expand All @@ -245,6 +245,12 @@ class UniversalPicGo extends EventEmitter implements IPicGo {
private initConfigPath(): void {
if (this.configPath === "") {
this.baseDir = this.getDefautBaseDir()
if (hasNodeEnv) {
const path = win.require("path")
this.configPath = path.join(this.baseDir, "picgo.cfg.json")
} else {
this.configPath = browserPathJoin(this.baseDir, "picgo.cfg.json")
}
} else {
if (hasNodeEnv) {
const fs = win.fs
Expand Down
34 changes: 34 additions & 0 deletions packages/picgo-plugin-app/README.md
Expand Up @@ -6,4 +6,38 @@ picgo plugin app for siyuan-note

```
├── universal-picgo
```

## Docs

New store path from 1.6.0

```
1.5.6 之前的配置位置
[工作空间]/data/storage/syp/picgo/picgo.cfg.json
[工作空间]/data/storage/syp/picgo/mac.applescript
[工作空间]/data/storage/syp/picgo/i18n-cli
[工作空间]/data/storage/syp/picgo/picgo-clipboard-images
[工作空间]/data/storage/syp/picgo/external-picgo-cfg.json
[工作空间]/data/storage/syp/picgo/picgo.log
[工作空间]/data/storage/syp/picgo/picgo.log
[工作空间]/data/storage/syp/picgo/package.json
[工作空间]/data/storage/syp/picgo/package-lock.json
[工作空间]/data/storage/syp/picgo/node_modules
1.6.0+ 默认插件位置
~/.universal-picgo/picgo.cfg.json
~/.universal-picgo/mac.applescript
~/.universal-picgo/i18n-cli
~/.universal-picgo/picgo-clipboard-images
~/.universal-picgo/external-picgo-cfg.json
~/.universal-picgo/picgo.log
~/.universal-picgo/package.json
~/.universal-picgo/package-lock.json
~/.universal-picgo/node_modules
~/.universal-picgo/node_modules/plugin-1
~/.universal-picgo/node_modules/plugin-2
```
Expand Up @@ -9,16 +9,15 @@

<script setup lang="ts">
import { createAppLogger } from "@/utils/appLogger.ts"
import { isDev } from "@/utils/Constants.ts"
import { ElMessage, UploadRequestOptions } from "element-plus"
import { SiyuanPicGoUploadApi } from "universal-picgo"
import { UploadFilled } from "@element-plus/icons-vue"
import { onBeforeMount, onBeforeUnmount, ref } from "vue"
import { retrieveImageFromClipboardAsBlob } from "@/utils/browserClipboard.ts"
import { useVueI18n } from "$composables/useVueI18n.ts"
import MaterialSymbolsImageSearchRounded from "~icons/material-symbols/image-search-rounded"
import MaterialSymbolsSettingsAccountBoxOutlineSharp from "~icons/material-symbols/settings-account-box-outline-sharp"
import SettingIndex from "$pages/SettingIndex.vue"
import { SiyuanPicGo } from "@/utils/siyuanPicgo.ts"
const logger = createAppLogger("picgo-browser-index")
const { t } = useVueI18n()
Expand All @@ -29,7 +28,7 @@ const activeMenu = ref("upload")
const handleDragAction = async (file: Blob) => {
let res: any
try {
const picgo = new SiyuanPicGoUploadApi(isDev)
const picgo = await SiyuanPicGo.getInstance()
logger.debug("picgo =>", picgo)
const result = await picgo.upload([file])
Expand Down
7 changes: 3 additions & 4 deletions packages/picgo-plugin-app/src/components/test/BrowserTest.vue

Large diffs are not rendered by default.

20 changes: 10 additions & 10 deletions packages/picgo-plugin-app/src/components/test/ElectronTest.vue

Large diffs are not rendered by default.

8 changes: 2 additions & 6 deletions packages/picgo-plugin-app/src/routes/index.ts
Expand Up @@ -16,6 +16,7 @@ import SettingIndex from "$pages/SettingIndex.vue"
import PicgoSetting from "$components/setting/PicgoSetting.vue"
import TestIndex from "$pages/TestIndex.vue"
import BrowserTest from "$components/test/BrowserTest.vue"
import ElectronTest from "$components/test/ElectronTest.vue"

/**
* 路由定义
Expand All @@ -29,10 +30,5 @@ export const routes: RouteRecordRaw[] = [
{ path: "/setting/transport", component: TransportSelect },
{ path: "/test", component: TestIndex },
{ path: "/test/browser", component: BrowserTest },
{
path: "/test/electron",
component: () => {
return import("$components/test/ElectronTest.vue")
},
},
{ path: "/test/electron", component: ElectronTest },
]
39 changes: 39 additions & 0 deletions packages/picgo-plugin-app/src/utils/siyuanPicgo.ts
@@ -0,0 +1,39 @@
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/

import { SiyuanPicGoUploadApi } from "universal-picgo"
import { isDev } from "@/utils/Constants.ts"
import { ElMessage } from "element-plus"
import { createAppLogger } from "@/utils/appLogger.ts"

/**
* 思源笔记 PicGp 实例
*/
class SiyuanPicGo {
private static logger = createAppLogger("siyuan-pigo")

public static async getInstance(): Promise<SiyuanPicGoUploadApi> {
return new Promise((resolve, reject) => {
const picgo = new SiyuanPicGoUploadApi(isDev)
const checkConfig = () => {
if (picgo.cfgUpdating) {
ElMessage.warning("检测到旧配置,正在迁移配置,请勿进行任何操作...")
setTimeout(checkConfig, 1000)
} else {
this.logger.info("picgo instance is ready")
ElMessage.success("配置迁移完成")
resolve(picgo)
}
}
checkConfig()
})
}
}

export { SiyuanPicGo }
4 changes: 2 additions & 2 deletions packages/picgo-plugin-app/tsconfig.json
Expand Up @@ -16,8 +16,8 @@

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,

"baseUrl": ".",
Expand Down

0 comments on commit af4a2f1

Please sign in to comment.