Feature: finish custom config path

ISSUES CLOSED: #255
This commit is contained in:
PiEgg 2021-08-01 17:02:54 +08:00
parent 96a63ea11a
commit 7030f7a764
13 changed files with 122 additions and 65 deletions

View File

@ -43,7 +43,7 @@
"keycode": "^2.2.0", "keycode": "^2.2.0",
"lodash-id": "^0.14.0", "lodash-id": "^0.14.0",
"lowdb": "^1.0.0", "lowdb": "^1.0.0",
"picgo": "^1.4.23", "picgo": "^1.4.24",
"qrcode.vue": "^1.7.0", "qrcode.vue": "^1.7.0",
"uuidv4": "^6.2.11", "uuidv4": "^6.2.11",
"vue": "^2.6.10", "vue": "^2.6.10",

View File

@ -6,6 +6,9 @@ const APP = process.type === 'renderer' ? remote.app : app
const STORE_PATH = APP.getPath('userData') const STORE_PATH = APP.getPath('userData')
const configFilePath = path.join(STORE_PATH, 'data.json') const configFilePath = path.join(STORE_PATH, 'data.json')
const configFileBackupPath = path.join(STORE_PATH, 'data.bak.json') const configFileBackupPath = path.join(STORE_PATH, 'data.bak.json')
export const defaultConfigPath = configFilePath
let _configFilePath = ''
let hasCheckPath = false
const errorMsg = { const errorMsg = {
broken: 'PicGo 配置文件损坏,已经恢复为默认配置', broken: 'PicGo 配置文件损坏,已经恢复为默认配置',
@ -15,6 +18,17 @@ const errorMsg = {
function dbChecker () { function dbChecker () {
if (process.type !== 'renderer') { if (process.type !== 'renderer') {
if (!global.notificationList) global.notificationList = [] if (!global.notificationList) global.notificationList = []
// db save bak
try {
const { dbPath, dbBackupPath } = getGalleryDBPath()
if (fs.existsSync(dbPath)) {
fs.copyFileSync(dbPath, dbBackupPath)
}
} catch (e) {
console.error(e)
}
const configFilePath = dbPathChecker()
if (!fs.existsSync(configFilePath)) { if (!fs.existsSync(configFilePath)) {
return return
} }
@ -23,6 +37,7 @@ function dbChecker () {
title: '注意', title: '注意',
body: '' body: ''
} }
// config save bak
try { try {
configFile = fs.readFileSync(configFilePath, { encoding: 'utf-8' }) configFile = fs.readFileSync(configFilePath, { encoding: 'utf-8' })
JSON.parse(configFile) JSON.parse(configFile)
@ -55,35 +70,63 @@ function dbChecker () {
* Get config path * Get config path
*/ */
function dbPathChecker (): string { function dbPathChecker (): string {
const defaultConfigPath = configFilePath if (_configFilePath) {
if (process.type !== 'renderer') { return _configFilePath
}
// defaultConfigPath
_configFilePath = defaultConfigPath
// if defaultConfig path is not exit // if defaultConfig path is not exit
// do not parse the content of config // do not parse the content of config
if (!fs.existsSync(defaultConfigPath)) { if (!fs.existsSync(defaultConfigPath)) {
return defaultConfigPath return _configFilePath
} }
try { try {
const configString = fs.readFileSync(configFilePath, { encoding: 'utf-8' }) const configString = fs.readFileSync(defaultConfigPath, { encoding: 'utf-8' })
const config = JSON.parse(configString) const config = JSON.parse(configString)
const userConfigPath: string = config.configPath || '' const userConfigPath: string = config.configPath || ''
if (userConfigPath) { if (userConfigPath) {
if (fs.existsSync(userConfigPath) && userConfigPath.endsWith('.json')) { if (fs.existsSync(userConfigPath) && userConfigPath.endsWith('.json')) {
return userConfigPath _configFilePath = userConfigPath
return _configFilePath
} }
} }
return defaultConfigPath return _configFilePath
} catch (e) { } catch (e) {
// TODO: local logger is needed // TODO: local logger is needed
if (!hasCheckPath) {
let optionsTpl = {
title: '注意',
body: '自定义文件解析出错,请检查路径内容是否正确'
}
global.notificationList.push(optionsTpl)
hasCheckPath = true
}
console.error(e) console.error(e)
return defaultConfigPath _configFilePath = defaultConfigPath
return _configFilePath
} }
} }
return defaultConfigPath
}
export const defaultConfigPath = configFilePath function dbPathDir () {
return path.dirname(dbPathChecker())
}
function getGalleryDBPath (): {
dbPath: string
dbBackupPath: string
} {
const configPath = dbPathChecker()
const dbPath = path.join(path.dirname(configPath), 'picgo.db')
const dbBackupPath = path.join(path.dirname(dbPath), 'picgo.bak.db')
return {
dbPath,
dbBackupPath
}
}
export { export {
dbChecker, dbChecker,
dbPathChecker dbPathChecker,
dbPathDir,
getGalleryDBPath
} }

View File

@ -3,20 +3,16 @@ import Datastore from 'lowdb'
import LodashId from 'lodash-id' import LodashId from 'lodash-id'
import FileSync from 'lowdb/adapters/FileSync' import FileSync from 'lowdb/adapters/FileSync'
import fs from 'fs-extra' import fs from 'fs-extra'
import path from 'path' import { dbPathChecker, dbPathDir, getGalleryDBPath } from './dbChecker'
import { app } from 'electron'
import { dbPathChecker } from './dbChecker'
import { DBStore } from '@picgo/store' import { DBStore } from '@picgo/store'
const APP = app const STORE_PATH = dbPathDir()
const STORE_PATH = APP.getPath('userData')
if (!fs.pathExistsSync(STORE_PATH)) { if (!fs.pathExistsSync(STORE_PATH)) {
fs.mkdirpSync(STORE_PATH) fs.mkdirpSync(STORE_PATH)
} }
const CONFIG_PATH: string = dbPathChecker() const CONFIG_PATH: string = dbPathChecker()
const CONFIG_DIR = path.dirname(CONFIG_PATH) const DB_PATH: string = getGalleryDBPath().dbPath
const DB_PATH = path.join(CONFIG_DIR, 'picgo.db')
// TODO: use JSONStore with @picgo/store // TODO: use JSONStore with @picgo/store
class ConfigStore { class ConfigStore {

View File

@ -1,11 +1,14 @@
import PicGoCore from '~/universal/types/picgo' import PicGoCore from '~/universal/types/picgo'
import { dbPathChecker } from 'apis/core/datastore/dbChecker' import { dbChecker, dbPathChecker } from 'apis/core/datastore/dbChecker'
import fs from 'fs-extra'
// eslint-disable-next-line // eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore const PicGo = requireFunc('picgo') as typeof PicGoCore
const CONFIG_PATH = dbPathChecker() const CONFIG_PATH = dbPathChecker()
dbChecker()
const picgo = new PicGo(CONFIG_PATH) const picgo = new PicGo(CONFIG_PATH)
picgo.saveConfig({ picgo.saveConfig({
debug: true, debug: true,

View File

@ -6,7 +6,7 @@ import {
} from 'electron' } from 'electron'
import path from 'path' import path from 'path'
import db, { GalleryDB } from 'apis/core/datastore' import db, { GalleryDB } from 'apis/core/datastore'
import { dbPathChecker, defaultConfigPath } from 'apis/core/datastore/dbChecker' import { dbPathChecker, defaultConfigPath, getGalleryDBPath } from 'apis/core/datastore/dbChecker'
import uploader from 'apis/app/uploader' import uploader from 'apis/app/uploader'
import pasteTemplate from '#/utils/pasteTemplate' import pasteTemplate from '#/utils/pasteTemplate'
import { handleCopyUrl } from '~/main/utils/common' import { handleCopyUrl } from '~/main/utils/common'
@ -138,7 +138,7 @@ class GuiApi implements IGuiApi {
*/ */
async getConfigPath () { async getConfigPath () {
const currentConfigPath = dbPathChecker() const currentConfigPath = dbPathChecker()
const galleryDBPath = path.join(path.dirname(currentConfigPath), 'picgo.db') const galleryDBPath = getGalleryDBPath().dbPath
return { return {
defaultConfigPath, defaultConfigPath,
currentConfigPath, currentConfigPath,

View File

@ -4,8 +4,7 @@ import {
dialog, dialog,
shell, shell,
IpcMainEvent, IpcMainEvent,
ipcMain, ipcMain
app
} from 'electron' } from 'electron'
import PicGoCore from '~/universal/types/picgo' import PicGoCore from '~/universal/types/picgo'
import { IPicGoHelperType } from '#/types/enum' import { IPicGoHelperType } from '#/types/enum'
@ -16,6 +15,7 @@ import { IGuiMenuItem } from 'picgo/dist/src/types'
import windowManager from 'apis/app/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from 'apis/app/window/constants' import { IWindowList } from 'apis/app/window/constants'
import { showNotification } from '~/main/utils/common' import { showNotification } from '~/main/utils/common'
import { dbPathChecker } from 'apis/core/datastore/dbChecker'
import { import {
PICGO_SAVE_CONFIG, PICGO_SAVE_CONFIG,
PICGO_GET_CONFIG, PICGO_GET_CONFIG,
@ -24,7 +24,8 @@ import {
PICGO_INSERT_MANY_DB, PICGO_INSERT_MANY_DB,
PICGO_UPDATE_BY_ID_DB, PICGO_UPDATE_BY_ID_DB,
PICGO_GET_BY_ID_DB, PICGO_GET_BY_ID_DB,
PICGO_REMOVE_BY_ID_DB PICGO_REMOVE_BY_ID_DB,
PICGO_OPEN_FILE
} from '#/events/constants' } from '#/events/constants'
import { GalleryDB } from 'apis/core/datastore' import { GalleryDB } from 'apis/core/datastore'
@ -33,7 +34,7 @@ import { IObject, IFilter } from '@picgo/store/dist/types'
// eslint-disable-next-line // eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
// const PluginHandler = requireFunc('picgo/dist/lib/PluginHandler').default // const PluginHandler = requireFunc('picgo/dist/lib/PluginHandler').default
const STORE_PATH = app.getPath('userData') const STORE_PATH = path.dirname(dbPathChecker())
// const CONFIG_PATH = path.join(STORE_PATH, '/data.json') // const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
type PicGoNotice = { type PicGoNotice = {
@ -320,6 +321,13 @@ const handlePicGoGalleryDB = () => {
}) })
} }
const handleOpenFile = () => {
ipcMain.on(PICGO_OPEN_FILE, (event: IpcMainEvent, fileName: string) => {
const abFilePath = path.join(STORE_PATH, fileName)
shell.openItem(abFilePath)
})
}
export default { export default {
listen () { listen () {
handleGetPluginList() handleGetPluginList()
@ -333,5 +341,6 @@ export default {
handlePicGoGetConfig() handlePicGoGetConfig()
handlePicGoGalleryDB() handlePicGoGalleryDB()
handleImportLocalPlugin() handleImportLocalPlugin()
handleOpenFile()
} }
} }

View File

@ -1,9 +1,9 @@
import { app } from 'electron'
import fse from 'fs-extra' import fse from 'fs-extra'
import path from 'path' import path from 'path'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import util from 'util' import util from 'util'
const STORE_PATH = app.getPath('userData') import { dbPathDir } from 'apis/core/datastore/dbChecker'
const STORE_PATH = dbPathDir()
const LOG_PATH = path.join(STORE_PATH, '/picgo.log') const LOG_PATH = path.join(STORE_PATH, '/picgo.log')
// since the error may occur in picgo-core // since the error may occur in picgo-core

View File

@ -34,6 +34,7 @@ import db, { GalleryDB } from '~/main/apis/core/datastore'
import bus from '@core/bus' import bus from '@core/bus'
import { privacyManager } from '~/main/utils/privacyManager' import { privacyManager } from '~/main/utils/privacyManager'
import logger from 'apis/core/picgo/logger' import logger from 'apis/core/picgo/logger'
import picgo from 'apis/core/picgo'
const isDevelopment = process.env.NODE_ENV !== 'production' const isDevelopment = process.env.NODE_ENV !== 'production'
@ -55,7 +56,7 @@ const handleStartUpFiles = (argv: string[], cwd: string) => {
} }
class LifeCycle { class LifeCycle {
private beforeReady () { private async beforeReady () {
protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }]) protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }])
// fix the $PATH in macOS // fix the $PATH in macOS
fixPath() fixPath()
@ -63,11 +64,11 @@ class LifeCycle {
ipcList.listen() ipcList.listen()
busEventList.listen() busEventList.listen()
updateShortKeyFromVersion212(db, db.get('settings.shortKey')) updateShortKeyFromVersion212(db, db.get('settings.shortKey'))
await migrateGalleryFromVersion230(db, GalleryDB.getInstance(), picgo)
} }
private onReady () { private onReady () {
app.on('ready', async () => { const readyFunction = async () => {
console.log('on ready') console.log('on ready')
await migrateGalleryFromVersion230(db, GalleryDB.getInstance())
createProtocol('picgo') createProtocol('picgo')
if (isDevelopment && !process.env.IS_TEST) { if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools // Install Vue Devtools
@ -102,7 +103,12 @@ class LifeCycle {
notice.show() notice.show()
} }
} }
}) }
if (!app.isReady()) {
app.on('ready', readyFunction)
} else {
readyFunction()
}
} }
private onRunning () { private onRunning () {
app.on('second-instance', (event, commandLine, workingDirectory) => { app.on('second-instance', (event, commandLine, workingDirectory) => {
@ -170,7 +176,7 @@ class LifeCycle {
if (!gotTheLock) { if (!gotTheLock) {
app.quit() app.quit()
} else { } else {
this.beforeReady() await this.beforeReady()
this.onReady() this.onReady()
this.onRunning() this.onRunning()
this.onQuit() this.onQuit()

View File

@ -2,6 +2,7 @@ import { DBStore } from '@picgo/store'
import ConfigStore from '~/main/apis/core/datastore' import ConfigStore from '~/main/apis/core/datastore'
import path from 'path' import path from 'path'
import fse from 'fs-extra' import fse from 'fs-extra'
import PicGoCore from '#/types/picgo'
// from v2.1.2 // from v2.1.2
const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IShortKeyConfigs | IOldShortKeyConfigs) => { const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IShortKeyConfigs | IOldShortKeyConfigs) => {
// #557 极端情况可能会出现配置不存在,需要重新写入 // #557 极端情况可能会出现配置不存在,需要重新写入
@ -31,18 +32,19 @@ const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IS
return false return false
} }
const migrateGalleryFromVersion230 = async (configDB: typeof ConfigStore, galleryDB: DBStore) => { const migrateGalleryFromVersion230 = async (configDB: typeof ConfigStore, galleryDB: DBStore, picgo: PicGoCore) => {
const originGallery: ImgInfo[] = configDB.get('uploaded') const originGallery: ImgInfo[] = configDB.get('uploaded')
const configPath = configDB.getConfigPath() const configPath = configDB.getConfigPath()
const configBakPath = path.join(path.dirname(configPath), 'config-bak.json') const configBakPath = path.join(path.dirname(configPath), 'config.bak.json')
if (fse.existsSync(configBakPath)) {
return
}
// migrate gallery from config to gallery db // migrate gallery from config to gallery db
if (originGallery && originGallery?.length > 0) { if (originGallery && originGallery?.length > 0) {
if (fse.existsSync(configBakPath)) {
fse.copyFileSync(configPath, configBakPath) fse.copyFileSync(configPath, configBakPath)
}
await galleryDB.insertMany(originGallery) await galleryDB.insertMany(originGallery)
configDB.set('uploaded', []) picgo.saveConfig({
uploaded: []
})
} }
} }

View File

@ -5,9 +5,9 @@ import {
import logger from '@core/picgo/logger' import logger from '@core/picgo/logger'
import windowManager from 'apis/app/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis' import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis'
import { app } from 'electron'
import path from 'path' import path from 'path'
const STORE_PATH = app.getPath('userData') import { dbPathDir } from 'apis/core/datastore/dbChecker'
const STORE_PATH = dbPathDir()
const LOG_PATH = path.join(STORE_PATH, 'picgo.log') const LOG_PATH = path.join(STORE_PATH, 'picgo.log')
const errorMessage = `upload error. see ${LOG_PATH} for more detail.` const errorMessage = `upload error. see ${LOG_PATH} for more detail.`

View File

@ -338,8 +338,8 @@
<script lang="ts"> <script lang="ts">
import keyDetect from '@/utils/key-binding' import keyDetect from '@/utils/key-binding'
import pkg from 'root/package.json' import pkg from 'root/package.json'
import path from 'path'
import { IConfig } from 'picgo/dist/src/types/index' import { IConfig } from 'picgo/dist/src/types/index'
import { PICGO_OPEN_FILE } from '#/events/constants'
import { import {
ipcRenderer, ipcRenderer,
remote remote
@ -471,10 +471,7 @@ export default class extends Vue {
}) as string[] }) as string[]
} }
openFile (file: string) { openFile (file: string) {
const { app, shell } = remote ipcRenderer.send(PICGO_OPEN_FILE, file)
const STORE_PATH = app.getPath('userData')
const FILE = path.join(STORE_PATH, `/${file}`)
shell.openItem(FILE)
} }
openLogSetting () { openLogSetting () {
this.logFileVisible = true this.logFileVisible = true

View File

@ -12,3 +12,4 @@ export const PICGO_INSERT_MANY_DB = 'PICGO_INSERT_MANY_DB'
export const PICGO_UPDATE_BY_ID_DB = 'PICGO_UPDATE_BY_ID_DB' export const PICGO_UPDATE_BY_ID_DB = 'PICGO_UPDATE_BY_ID_DB'
export const PICGO_GET_BY_ID_DB = 'PICGO_GET_BY_ID_DB' export const PICGO_GET_BY_ID_DB = 'PICGO_GET_BY_ID_DB'
export const PICGO_REMOVE_BY_ID_DB = 'PICGO_REMOVE_BY_ID_DB' export const PICGO_REMOVE_BY_ID_DB = 'PICGO_REMOVE_BY_ID_DB'
export const PICGO_OPEN_FILE = 'PICGO_OPEN_FILE'

View File

@ -8390,10 +8390,10 @@ performance-now@^2.1.0:
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=
picgo@^1.4.23: picgo@^1.4.24:
version "1.4.23" version "1.4.24"
resolved "https://registry.yarnpkg.com/picgo/-/picgo-1.4.23.tgz#01232185a3c4cbf4972d9924a5968dd0f9726d04" resolved "https://registry.yarnpkg.com/picgo/-/picgo-1.4.24.tgz#0d5a492e1f4d29823912535122fdc14928a6ddad"
integrity sha512-/QCbiye7Trw+hXGU67YYb2tOiBy/BoGn7bI2vOHejHlwRFQuKQxLXYHK97sRSlSCWubTFSv9QNrvXz6/jTr69A== integrity sha512-4QVTRIMLJes9c5vDuUl/c0TOEtUJycQhVdsXYtwx0fkKk/vhvfh0pRYUc33DEW88eGRi2CzAE2JJ93KHy5A8cg==
dependencies: dependencies:
chalk "^2.4.1" chalk "^2.4.1"
commander "^2.17.0" commander "^2.17.0"