Skip to content

Commit

Permalink
✨ Feature: finish custom config path
Browse files Browse the repository at this point in the history
ISSUES CLOSED: #255
  • Loading branch information
Molunerfinn committed Aug 1, 2021
1 parent 96a63ea commit 7030f7a
Show file tree
Hide file tree
Showing 13 changed files with 119 additions and 62 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"keycode": "^2.2.0",
"lodash-id": "^0.14.0",
"lowdb": "^1.0.0",
"picgo": "^1.4.23",
"picgo": "^1.4.24",
"qrcode.vue": "^1.7.0",
"uuidv4": "^6.2.11",
"vue": "^2.6.10",
Expand Down
87 changes: 65 additions & 22 deletions src/main/apis/core/datastore/dbChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ const APP = process.type === 'renderer' ? remote.app : app
const STORE_PATH = APP.getPath('userData')
const configFilePath = path.join(STORE_PATH, 'data.json')
const configFileBackupPath = path.join(STORE_PATH, 'data.bak.json')
export const defaultConfigPath = configFilePath
let _configFilePath = ''
let hasCheckPath = false

const errorMsg = {
broken: 'PicGo 配置文件损坏,已经恢复为默认配置',
Expand All @@ -15,6 +18,17 @@ const errorMsg = {
function dbChecker () {
if (process.type !== 'renderer') {
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)) {
return
}
Expand All @@ -23,6 +37,7 @@ function dbChecker () {
title: '注意',
body: ''
}
// config save bak
try {
configFile = fs.readFileSync(configFilePath, { encoding: 'utf-8' })
JSON.parse(configFile)
Expand Down Expand Up @@ -55,35 +70,63 @@ function dbChecker () {
* Get config path
*/
function dbPathChecker (): string {
const defaultConfigPath = configFilePath
if (process.type !== 'renderer') {
// if defaultConfig path is not exit
// do not parse the content of config
if (!fs.existsSync(defaultConfigPath)) {
return defaultConfigPath
if (_configFilePath) {
return _configFilePath
}
// defaultConfigPath
_configFilePath = defaultConfigPath
// if defaultConfig path is not exit
// do not parse the content of config
if (!fs.existsSync(defaultConfigPath)) {
return _configFilePath
}
try {
const configString = fs.readFileSync(defaultConfigPath, { encoding: 'utf-8' })
const config = JSON.parse(configString)
const userConfigPath: string = config.configPath || ''
if (userConfigPath) {
if (fs.existsSync(userConfigPath) && userConfigPath.endsWith('.json')) {
_configFilePath = userConfigPath
return _configFilePath
}
}
try {
const configString = fs.readFileSync(configFilePath, { encoding: 'utf-8' })
const config = JSON.parse(configString)
const userConfigPath: string = config.configPath || ''
if (userConfigPath) {
if (fs.existsSync(userConfigPath) && userConfigPath.endsWith('.json')) {
return userConfigPath
}
return _configFilePath
} catch (e) {
// TODO: local logger is needed
if (!hasCheckPath) {
let optionsTpl = {
title: '注意',
body: '自定义文件解析出错,请检查路径内容是否正确'
}
return defaultConfigPath
} catch (e) {
// TODO: local logger is needed
console.error(e)
return defaultConfigPath
global.notificationList.push(optionsTpl)
hasCheckPath = true
}
console.error(e)
_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 {
dbChecker,
dbPathChecker
dbPathChecker,
dbPathDir,
getGalleryDBPath
}
10 changes: 3 additions & 7 deletions src/main/apis/core/datastore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,16 @@ import Datastore from 'lowdb'
import LodashId from 'lodash-id'
import FileSync from 'lowdb/adapters/FileSync'
import fs from 'fs-extra'
import path from 'path'
import { app } from 'electron'
import { dbPathChecker } from './dbChecker'
import { dbPathChecker, dbPathDir, getGalleryDBPath } from './dbChecker'
import { DBStore } from '@picgo/store'

const APP = app
const STORE_PATH = APP.getPath('userData')
const STORE_PATH = dbPathDir()

if (!fs.pathExistsSync(STORE_PATH)) {
fs.mkdirpSync(STORE_PATH)
}
const CONFIG_PATH: string = dbPathChecker()
const CONFIG_DIR = path.dirname(CONFIG_PATH)
const DB_PATH = path.join(CONFIG_DIR, 'picgo.db')
const DB_PATH: string = getGalleryDBPath().dbPath

// TODO: use JSONStore with @picgo/store
class ConfigStore {
Expand Down
5 changes: 4 additions & 1 deletion src/main/apis/core/picgo/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
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
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore

const CONFIG_PATH = dbPathChecker()

dbChecker()

const picgo = new PicGo(CONFIG_PATH)
picgo.saveConfig({
debug: true,
Expand Down
4 changes: 2 additions & 2 deletions src/main/apis/gui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from 'electron'
import path from 'path'
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 pasteTemplate from '#/utils/pasteTemplate'
import { handleCopyUrl } from '~/main/utils/common'
Expand Down Expand Up @@ -138,7 +138,7 @@ class GuiApi implements IGuiApi {
*/
async getConfigPath () {
const currentConfigPath = dbPathChecker()
const galleryDBPath = path.join(path.dirname(currentConfigPath), 'picgo.db')
const galleryDBPath = getGalleryDBPath().dbPath
return {
defaultConfigPath,
currentConfigPath,
Expand Down
17 changes: 13 additions & 4 deletions src/main/events/picgoCoreIPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import {
dialog,
shell,
IpcMainEvent,
ipcMain,
app
ipcMain
} from 'electron'
import PicGoCore from '~/universal/types/picgo'
import { IPicGoHelperType } from '#/types/enum'
Expand All @@ -16,6 +15,7 @@ import { IGuiMenuItem } from 'picgo/dist/src/types'
import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from 'apis/app/window/constants'
import { showNotification } from '~/main/utils/common'
import { dbPathChecker } from 'apis/core/datastore/dbChecker'
import {
PICGO_SAVE_CONFIG,
PICGO_GET_CONFIG,
Expand All @@ -24,7 +24,8 @@ import {
PICGO_INSERT_MANY_DB,
PICGO_UPDATE_BY_ID_DB,
PICGO_GET_BY_ID_DB,
PICGO_REMOVE_BY_ID_DB
PICGO_REMOVE_BY_ID_DB,
PICGO_OPEN_FILE
} from '#/events/constants'

import { GalleryDB } from 'apis/core/datastore'
Expand All @@ -33,7 +34,7 @@ import { IObject, IFilter } from '@picgo/store/dist/types'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
// 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')

type PicGoNotice = {
Expand Down Expand Up @@ -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 {
listen () {
handleGetPluginList()
Expand All @@ -333,5 +341,6 @@ export default {
handlePicGoGetConfig()
handlePicGoGalleryDB()
handleImportLocalPlugin()
handleOpenFile()
}
}
4 changes: 2 additions & 2 deletions src/main/lifeCycle/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { app } from 'electron'
import fse from 'fs-extra'
import path from 'path'
import dayjs from 'dayjs'
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')

// since the error may occur in picgo-core
Expand Down
16 changes: 11 additions & 5 deletions src/main/lifeCycle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import db, { GalleryDB } from '~/main/apis/core/datastore'
import bus from '@core/bus'
import { privacyManager } from '~/main/utils/privacyManager'
import logger from 'apis/core/picgo/logger'
import picgo from 'apis/core/picgo'

const isDevelopment = process.env.NODE_ENV !== 'production'

Expand All @@ -55,19 +56,19 @@ const handleStartUpFiles = (argv: string[], cwd: string) => {
}

class LifeCycle {
private beforeReady () {
private async beforeReady () {
protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }])
// fix the $PATH in macOS
fixPath()
beforeOpen()
ipcList.listen()
busEventList.listen()
updateShortKeyFromVersion212(db, db.get('settings.shortKey'))
await migrateGalleryFromVersion230(db, GalleryDB.getInstance(), picgo)
}
private onReady () {
app.on('ready', async () => {
const readyFunction = async () => {
console.log('on ready')
await migrateGalleryFromVersion230(db, GalleryDB.getInstance())
createProtocol('picgo')
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
Expand Down Expand Up @@ -102,7 +103,12 @@ class LifeCycle {
notice.show()
}
}
})
}
if (!app.isReady()) {
app.on('ready', readyFunction)
} else {
readyFunction()
}
}
private onRunning () {
app.on('second-instance', (event, commandLine, workingDirectory) => {
Expand Down Expand Up @@ -170,7 +176,7 @@ class LifeCycle {
if (!gotTheLock) {
app.quit()
} else {
this.beforeReady()
await this.beforeReady()
this.onReady()
this.onRunning()
this.onQuit()
Expand Down
16 changes: 9 additions & 7 deletions src/main/migrate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { DBStore } from '@picgo/store'
import ConfigStore from '~/main/apis/core/datastore'
import path from 'path'
import fse from 'fs-extra'
import PicGoCore from '#/types/picgo'
// from v2.1.2
const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IShortKeyConfigs | IOldShortKeyConfigs) => {
// #557 极端情况可能会出现配置不存在,需要重新写入
Expand Down Expand Up @@ -31,18 +32,19 @@ const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IS
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 configPath = configDB.getConfigPath()
const configBakPath = path.join(path.dirname(configPath), 'config-bak.json')
if (fse.existsSync(configBakPath)) {
return
}
const configBakPath = path.join(path.dirname(configPath), 'config.bak.json')
// migrate gallery from config to gallery db
if (originGallery && originGallery?.length > 0) {
fse.copyFileSync(configPath, configBakPath)
if (fse.existsSync(configBakPath)) {
fse.copyFileSync(configPath, configBakPath)
}
await galleryDB.insertMany(originGallery)
configDB.set('uploaded', [])
picgo.saveConfig({
uploaded: []
})
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/server/routerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
import logger from '@core/picgo/logger'
import windowManager from 'apis/app/window/windowManager'
import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis'
import { app } from 'electron'
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 errorMessage = `upload error. see ${LOG_PATH} for more detail.`
Expand Down
7 changes: 2 additions & 5 deletions src/renderer/pages/PicGoSetting.vue
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,8 @@
<script lang="ts">
import keyDetect from '@/utils/key-binding'
import pkg from 'root/package.json'
import path from 'path'
import { IConfig } from 'picgo/dist/src/types/index'
import { PICGO_OPEN_FILE } from '#/events/constants'
import {
ipcRenderer,
remote
Expand Down Expand Up @@ -471,10 +471,7 @@ export default class extends Vue {
}) as string[]
}
openFile (file: string) {
const { app, shell } = remote
const STORE_PATH = app.getPath('userData')
const FILE = path.join(STORE_PATH, `/${file}`)
shell.openItem(FILE)
ipcRenderer.send(PICGO_OPEN_FILE, file)
}
openLogSetting () {
this.logFileVisible = true
Expand Down
1 change: 1 addition & 0 deletions src/universal/events/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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_GET_BY_ID_DB = 'PICGO_GET_BY_ID_DB'
export const PICGO_REMOVE_BY_ID_DB = 'PICGO_REMOVE_BY_ID_DB'
export const PICGO_OPEN_FILE = 'PICGO_OPEN_FILE'
Loading

0 comments on commit 7030f7a

Please sign in to comment.