Skip to content

Commit

Permalink
🐛 Fix(db): fix some db bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Molunerfinn committed Jun 12, 2022
1 parent 8d861be commit d3bb5ca
Show file tree
Hide file tree
Showing 27 changed files with 238 additions and 107 deletions.
48 changes: 23 additions & 25 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,38 +1,36 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"name": "Electron: Main",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/src/main/index.dev.js",
"env": {
"DEBUG_ENV": "debug"
},
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
// this points to the electron task runner
"protocol": "inspector",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"runtimeArgs": [
"--nolazy"
],
"sourceMaps": true
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
},
"preLaunchTask": "electron-debug",
"args": ["--remote-debugging-port=9223", "./dist_electron"],
"outFiles": ["${workspaceFolder}/dist_electron/**/*.js"]
},
{
"name": "Attach",
"type": "node",
"name": "Electron: Renderer",
"type": "chrome",
"request": "attach",
"port": 5858,
"sourceMaps": true,
"restart": true,
"outFiles": [],
"localRoot": "${workspaceRoot}",
"protocol": "inspector",
"remoteRoot": null
"port": 9223,
"urlFilter": "http://localhost:*",
"timeout": 30000,
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///./src/*": "${webRoot}/*"
}
}
],
"compounds": [
{
"name": "Electron: All",
"configurations": ["Electron: Main", "Electron: Renderer"]
}
]
}
27 changes: 27 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "electron-debug",
"type": "process",
"command": "./node_modules/.bin/vue-cli-service",
"windows": {
"command": "./node_modules/.bin/vue-cli-service.cmd"
},
"isBackground": true,
"args": ["electron:serve", "--debug"],
"problemMatcher": {
"owner": "custom",
"pattern": {
"regexp": ""
},
"background": {
"beginsPattern": "Starting development server\\.\\.\\.",
"endsPattern": "Not launching electron as debug argument was passed\\."
}
}
}
]
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"bump": "bump-version",
"release": "vue-cli-service electron:build --publish always"
},
"main": "background.js",
"main": "index.js",
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
Expand All @@ -36,15 +36,15 @@
},
"dependencies": {
"@picgo/i18n": "^1.0.0",
"@picgo/store": "^1.0.3",
"@picgo/store": "2.0.1",
"axios": "^0.19.0",
"core-js": "^3.3.2",
"element-ui": "^2.13.0",
"fs-extra": "^10.0.0",
"keycode": "^2.2.0",
"lodash-id": "^0.14.0",
"lowdb": "^1.0.0",
"picgo": "^1.5.0-alpha.3",
"picgo": "^1.5.0-alpha.4",
"qrcode.vue": "^1.7.0",
"shell-path": "2.1.0",
"uuidv4": "^6.2.11",
Expand Down
2 changes: 1 addition & 1 deletion src/main/apis/app/shortKey/shortKeyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ class ShortKeyHandler {
keyList.forEach(item => {
globalShortcut.unregister(item.key)
shortKeyService.unregisterCommand(item.command)
picgo.unsetConfig('settings.shortKey', item.command)
db.unset('settings.shortKey', item.command)
})
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/apis/app/uploader/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import logger from '@core/picgo/logger'
import { T } from '~/universal/i18n'
import fse from 'fs-extra'
import path from 'path'
import { privacyManager } from '~/main/utils/privacyManager'

const waitForShow = (webcontent: WebContents) => {
return new Promise<void>((resolve) => {
Expand Down Expand Up @@ -140,6 +141,10 @@ class Uploader {

async upload (img?: IUploadOption): Promise<ImgInfo[]|false> {
try {
const privacyCheckRes = await privacyManager.check()
if (!privacyCheckRes) {
throw Error(T('PRIVACY_TIPS'))
}
const startTime = Date.now()
const output = await picgo.upload(img)
if (Array.isArray(output) && output.some((item: ImgInfo) => item.imgUrl)) {
Expand Down
63 changes: 24 additions & 39 deletions src/main/apis/core/datastore/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import Datastore from 'lowdb'
// @ts-ignore
import LodashId from 'lodash-id'
import FileSync from 'lowdb/adapters/FileSync'
import fs from 'fs-extra'
import { dbPathChecker, dbPathDir, getGalleryDBPath } from './dbChecker'
import { DBStore } from '@picgo/store'
import { DBStore, JSONStore } from '@picgo/store'
import { T } from '~/universal/i18n'

const STORE_PATH = dbPathDir()
Expand All @@ -15,76 +11,65 @@ if (!fs.pathExistsSync(STORE_PATH)) {
const CONFIG_PATH: string = dbPathChecker()
const DB_PATH: string = getGalleryDBPath().dbPath

// TODO: use JSONStore with @picgo/store
class ConfigStore {
private db: Datastore.LowdbSync<Datastore.AdapterSync>
private db: JSONStore
constructor () {
const adapter = new FileSync(CONFIG_PATH)
this.db = new JSONStore(CONFIG_PATH)

this.db = Datastore(adapter)
this.db._.mixin(LodashId)

if (!this.db.has('picBed').value()) {
if (!this.db.has('picBed')) {
this.db.set('picBed', {
current: 'smms', // deprecated
uploader: 'smms',
smms: {
token: ''
}
}).write()
})
}

if (!this.db.has('settings.shortKey').value()) {
if (!this.db.has('settings.shortKey')) {
this.db.set('settings.shortKey[picgo:upload]', {
enable: true,
key: 'CommandOrControl+Shift+P',
name: 'upload',
label: T('QUICK_UPLOAD')
}).write()
})
}
this.read()
}

read () {
return this.db.read()
read (flush = false) {
// if flush -> true, read origin file again
this.db.read(flush)
return this.db
}

get (key = '') {
return this.read().get(key).value()
get (key = ''): any {
if (key === '') {
return this.db.read()
}
return this.db.get(key)
}

set (key: string, value: any) {
return this.read().set(key, value).write()
set (key: string, value: any): void {
return this.db.set(key, value)
}

has (key: string) {
return this.read().has(key).value()
}

insert (key: string, value: any): void {
// @ts-ignore
return this.read().get(key).insert(value).write()
return this.db.has(key)
}

unset (key: string, value: any): boolean {
return this.read().get(key).unset(value).value()
}

getById (key: string, id: string) {
// @ts-ignore
return this.read().get(key).getById(id).value()
}

removeById (key: string, id: string) {
// @ts-ignore
return this.read().get(key).removeById(id).write()
return this.db.unset(key, value)
}

getConfigPath () {
return CONFIG_PATH
}
}

export default new ConfigStore()
const db = new ConfigStore()

export default db

// v2.3.0 add gallery db
class GalleryDB {
Expand Down
11 changes: 11 additions & 0 deletions src/main/apis/core/picgo/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { dbChecker, dbPathChecker } from 'apis/core/datastore/dbChecker'
import pkg from 'root/package.json'
import { PicGo } from 'picgo'
import db from 'apis/core/datastore'

const CONFIG_PATH = dbPathChecker()

Expand All @@ -15,4 +16,14 @@ picgo.saveConfig({
global.PICGO_GUI_VERSION = pkg.version
picgo.GUI_VERSION = global.PICGO_GUI_VERSION

const originPicGoSaveConfig = picgo.saveConfig.bind(picgo)

picgo.saveConfig = (config: IStringKeyMap) => {
originPicGoSaveConfig(config)
// flush electron's db
setTimeout(() => {
db.read(true)
}, 0)
}

export default picgo
21 changes: 21 additions & 0 deletions src/main/apis/gui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,27 @@ class GuiApi implements IGuiApi {
get galleryDB (): DBStore {
return new Proxy<DBStore>(GalleryDB.getInstance(), {
get (target, prop: keyof DBStore) {
if (prop === 'overwrite') {
return new Proxy(GalleryDB.getInstance().overwrite, {
apply (target, ctx, args) {
return new Promise((resolve) => {
const guiApi = GuiApi.getInstance()
guiApi.showMessageBox({
title: T('TIPS_WARNING'),
message: T('TIPS_PLUGIN_REMOVE_GALLERY_ITEM'),
type: 'info',
buttons: ['Yes', 'No']
}).then(res => {
if (res.result === 0) {
resolve(Reflect.apply(target, ctx, args))
} else {
resolve(undefined)
}
})
})
}
})
}
if (prop === 'removeById') {
return new Proxy(GalleryDB.getInstance().removeById, {
apply (target, ctx, args) {
Expand Down
31 changes: 24 additions & 7 deletions src/main/events/picgoCoreIPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import { IPasteStyle, IPicGoHelperType, IWindowList } from '#/types/enum'
import shortKeyHandler from 'apis/app/shortKey/shortKeyHandler'
import picgo from '@core/picgo'
import { handleStreamlinePluginName } from '~/universal/utils/common'
import { handleStreamlinePluginName, simpleClone } from '~/universal/utils/common'
import { IGuiMenuItem, PicGo as PicGoCore } from 'picgo'
import windowManager from 'apis/app/window/windowManager'
import { showNotification } from '~/main/utils/common'
Expand Down Expand Up @@ -128,10 +128,19 @@ const getPluginList = (): IPicGoPlugin[] => {

const handleGetPluginList = () => {
ipcMain.on('getPluginList', (event: IpcMainEvent) => {
const list = getPluginList()
// here can just send JS Object not function
// or will cause [Failed to serialize arguments] error
event.sender.send('pluginList', list)
try {
const list = simpleClone(getPluginList())
// here can just send JS Object not function
// or will cause [Failed to serialize arguments] error
event.sender.send('pluginList', list)
} catch (e: any) {
event.sender.send('pluginList', [])
showNotification({
title: T('TIPS_GET_PLUGIN_LIST_FAILED'),
body: e.message
})
picgo.log.error(e)
}
})
}

Expand Down Expand Up @@ -267,8 +276,16 @@ const handleImportLocalPlugin = () => {
if (filePaths.length > 0) {
const res = await picgo.pluginHandler.install(filePaths)
if (res.success) {
const list = getPluginList()
event.sender.send('pluginList', list)
try {
const list = simpleClone(getPluginList())
event.sender.send('pluginList', list)
} catch (e: any) {
event.sender.send('pluginList', [])
showNotification({
title: T('TIPS_GET_PLUGIN_LIST_FAILED'),
body: e.message
})
}
showNotification({
title: T('PLUGIN_IMPORT_SUCCEED'),
body: ''
Expand Down
5 changes: 0 additions & 5 deletions src/main/lifeCycle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import shortKeyHandler from 'apis/app/shortKey/shortKeyHandler'
import { getUploadFiles } from '~/main/utils/handleArgv'
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'
import fixPath from './fixPath'
Expand Down Expand Up @@ -81,10 +80,6 @@ class LifeCycle {
console.error('Vue Devtools failed to install:', e.toString())
}
}
const res = await privacyManager.init()
if (!res) {
return app.quit()
}
windowManager.create(IWindowList.TRAY_WINDOW)
windowManager.create(IWindowList.SETTING_WINDOW)
createTray()
Expand Down
2 changes: 1 addition & 1 deletion src/main/migrate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const updateShortKeyFromVersion212 = (db: typeof ConfigStore, shortKeyConfig: IS
}

const migrateGalleryFromVersion230 = async (configDB: typeof ConfigStore, galleryDB: DBStore, picgo: PicGoCore) => {
const originGallery: ImgInfo[] = configDB.get('uploaded')
const originGallery: ImgInfo[] = picgo.getConfig('uploaded')
// if hasMigrate, we don't need to migrate
const hasMigrate: boolean = configDB.get('__migrateUploaded')
if (hasMigrate) {
Expand Down
Loading

0 comments on commit d3bb5ca

Please sign in to comment.