🔨 Refactor: improved code structure for greater clarity and understanding

This commit is contained in:
Molunerfinn 2020-04-10 23:28:46 +08:00
parent cc182b08f7
commit 3df2253ae9
26 changed files with 91 additions and 141 deletions

View File

@ -8,27 +8,27 @@ import {
installVueDevtools installVueDevtools
} from 'vue-cli-plugin-electron-builder/lib' } from 'vue-cli-plugin-electron-builder/lib'
import db from '#/datastore' import db from '#/datastore'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { import {
uploadChoosedFiles, uploadChoosedFiles,
uploadClipboardFiles uploadClipboardFiles
} from '~/main/apis/uploader/api' } from 'apis/app/uploader/apis'
import beforeOpen from '~/main/utils/beforeOpen' import beforeOpen from '~/main/utils/beforeOpen'
import updateChecker from '~/main/utils/updateChecker' import updateChecker from '~/main/utils/updateChecker'
import ipcList from '~/main/apis/eventCenter/ipcList' import ipcList from '~/main/events/ipcList'
import busEventList from '~/main/apis/eventCenter/busEventList' import busEventList from '~/main/events/busEventList'
import fixPath from 'fix-path' import fixPath from 'fix-path'
import { getUploadFiles } from '~/main/utils/handleArgv' import { getUploadFiles } from '~/main/utils/handleArgv'
import bus from '~/main/utils/eventBus' import bus from '@core/bus'
import { import {
updateShortKeyFromVersion212 updateShortKeyFromVersion212
} from '~/main/migrate' } from '~/main/migrate'
import shortKeyHandler from '~/main/apis/shortKey/shortKeyHandler' import shortKeyHandler from 'apis/app/shortKey/shortKeyHandler'
import server from '~/main/server/index' import server from '~/main/server/index'
import { import {
createTray createTray
} from '~/main/apis/app' } from 'apis/app/system'
const isDevelopment = process.env.NODE_ENV !== 'production' const isDevelopment = process.env.NODE_ENV !== 'production'
protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }]) protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }])

13
src/main/apis/README.md Normal file
View File

@ -0,0 +1,13 @@
# apis folder
## core
The lowest level APIs that are not dependent on each other. The upper APIs depend on them.
## app
Provide key API interfaces for PicGo application, including uploader, window management, shortcut key system, etc
## gui
GuiApi for PicGo plugins.

View File

@ -1,4 +1,4 @@
import bus from '../../utils/eventBus' import bus from '@core/bus'
import PicGoCore from '~/universal/types/picgo' import PicGoCore from '~/universal/types/picgo'
import path from 'path' import path from 'path'
import { import {
@ -6,11 +6,11 @@ import {
globalShortcut, globalShortcut,
BrowserWindow BrowserWindow
} from 'electron' } from 'electron'
import logger from '../../utils/logger' import logger from '@core/picgo/logger'
import GuiApi from '../gui' import GuiApi from '../../gui'
import db from '#/datastore' import db from '#/datastore'
import shortKeyService from './shortKeyService' import shortKeyService from './shortKeyService'
import picgo from '../picgo' import picgo from '@core/picgo'
class ShortKeyHandler { class ShortKeyHandler {
private isInModifiedMode: boolean = false private isInModifiedMode: boolean = false

View File

@ -1,4 +1,4 @@
import logger from '../../utils/logger' import logger from '@core/picgo/logger'
class ShortKeyService { class ShortKeyService {
private commandList: Map<string, IShortKeyHandler> = new Map() private commandList: Map<string, IShortKeyHandler> = new Map()
registerCommand (command: string, handler: IShortKeyHandler) { registerCommand (command: string, handler: IShortKeyHandler) {

View File

@ -7,12 +7,12 @@ import {
systemPreferences, systemPreferences,
Notification Notification
} from 'electron' } from 'electron'
import uploader from '~/main/apis/uploader' import uploader from 'apis/app/uploader'
import getPicBeds from '~/main/utils/getPicBeds' import getPicBeds from '~/main/utils/getPicBeds'
import db from '#/datastore' import db from '#/datastore'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
import picgo from '~/main/apis/picgo' import picgo from '@core/picgo'
import pasteTemplate from '#/utils/pasteTemplate' import pasteTemplate from '#/utils/pasteTemplate'
import pkg from 'root/package.json' import pkg from 'root/package.json'
import { handleCopyUrl } from '~/main/utils/common' import { handleCopyUrl } from '~/main/utils/common'

View File

@ -2,9 +2,9 @@ import {
Notification, Notification,
WebContents WebContents
} from 'electron' } from 'electron'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
import uploader from './' import uploader from '.'
import pasteTemplate from '#/utils/pasteTemplate' import pasteTemplate from '#/utils/pasteTemplate'
import db from '#/datastore' import db from '#/datastore'
import { handleCopyUrl } from '~/main/utils/common' import { handleCopyUrl } from '~/main/utils/common'

View File

@ -6,10 +6,10 @@ import {
WebContents WebContents
} from 'electron' } from 'electron'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import picgo from '~/main/apis/picgo' import picgo from '@core/picgo'
import db from '#/datastore' import db from '#/datastore'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
const waitForShow = (webcontent: WebContents) => { const waitForShow = (webcontent: WebContents) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View File

@ -8,11 +8,11 @@ import {
RENAME_WINDOW_URL RENAME_WINDOW_URL
} from './constants' } from './constants'
import { IWindowListItem } from '#/types/electron' import { IWindowListItem } from '#/types/electron'
import bus from '~/main/utils/eventBus' import bus from '@core/bus'
import db from '#/datastore' import db from '#/datastore'
import { getWindowId } from '~/main/apis/bus' import { getWindowId } from '@core/bus/apis'
import { BrowserWindow, app } from 'electron' import { BrowserWindow, app } from 'electron'
import { CREATE_APP_MENU } from '~/main/apis/bus/constants' import { CREATE_APP_MENU } from '@core/bus/constants'
const windowList = new Map<IWindowList, IWindowListItem>() const windowList = new Map<IWindowList, IWindowListItem>()
@ -37,14 +37,14 @@ windowList.set(IWindowList.TRAY_WINDOW, {
} }
}, },
callback (window) { callback (window) {
const id = window!.id const id = window.id
window!.loadURL(TRAY_WINDOW_URL) window.loadURL(TRAY_WINDOW_URL)
window!.on('closed', () => { window.on('closed', () => {
bus.emit(DELETE_WINDOW_EVENT, id) bus.emit(DELETE_WINDOW_EVENT, id)
}) })
window!.on('blur', () => { window.on('blur', () => {
window!.hide() window.hide()
}) })
} }
}) })
@ -82,9 +82,9 @@ windowList.set(IWindowList.SETTING_WINDOW, {
return options return options
}, },
callback (window) { callback (window) {
const id = window!.id const id = window.id
window!.loadURL(SETTING_WINDOW_URL) window.loadURL(SETTING_WINDOW_URL)
window!.on('closed', () => { window.on('closed', () => {
bus.emit('toggleShortKeyModifiedMode', false) bus.emit('toggleShortKeyModifiedMode', false)
bus.emit(DELETE_WINDOW_EVENT, id) bus.emit(DELETE_WINDOW_EVENT, id)
if (process.platform === 'linux') { if (process.platform === 'linux') {
@ -125,9 +125,9 @@ windowList.set(IWindowList.MINI_WINDOW, {
return obj return obj
}, },
callback (window) { callback (window) {
const id = window!.id const id = window.id
window!.loadURL(MINI_WINDOW_URL) window.loadURL(MINI_WINDOW_URL)
window!.on('closed', () => { window.on('closed', () => {
bus.emit(DELETE_WINDOW_EVENT, id) bus.emit(DELETE_WINDOW_EVENT, id)
}) })
} }
@ -159,7 +159,7 @@ windowList.set(IWindowList.RENAME_WINDOW, {
return options return options
}, },
async callback (window) { async callback (window) {
window!.loadURL(RENAME_WINDOW_URL) window.loadURL(RENAME_WINDOW_URL)
const currentWindowId = await getWindowId() const currentWindowId = await getWindowId()
const currentWindow = BrowserWindow.fromId(currentWindowId) const currentWindow = BrowserWindow.fromId(currentWindowId)
if (currentWindow && currentWindow.isVisible()) { if (currentWindow && currentWindow.isVisible()) {
@ -173,7 +173,7 @@ windowList.set(IWindowList.RENAME_WINDOW, {
} else { // if is the miniWindow } else { // if is the miniWindow
positionY = bounds.y + bounds.height / 2 positionY = bounds.y + bounds.height / 2
} }
window!.setPosition(positionX, positionY, false) window.setPosition(positionX, positionY, false)
} }
} }
}) })

View File

@ -8,7 +8,7 @@ import {
DELETE_WINDOW_EVENT, DELETE_WINDOW_EVENT,
CREATE_WINDOW_EVENT CREATE_WINDOW_EVENT
} from './constants' } from './constants'
import bus from '~/main/utils/eventBus' import bus from '@core/bus'
class WindowManager implements IWindowManager { class WindowManager implements IWindowManager {
private windowMap: Map<IWindowList | string, BrowserWindow> = new Map() private windowMap: Map<IWindowList | string, BrowserWindow> = new Map()

View File

@ -1,4 +1,4 @@
import bus from '../../utils/eventBus' import bus from '.'
import { import {
UPLOAD_WITH_FILES, UPLOAD_WITH_FILES,
UPLOAD_WITH_FILES_RESPONSE, UPLOAD_WITH_FILES_RESPONSE,

View File

@ -0,0 +1,5 @@
import picgo from '.'
const logger = picgo.log
export default logger

View File

@ -6,13 +6,13 @@ import {
ipcMain ipcMain
} from 'electron' } from 'electron'
import db from '#/datastore' import db from '#/datastore'
import uploader from '../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'
import { import {
getWindowId, getWindowId,
getSettingWindowId getSettingWindowId
} from '~/main/apis/bus' } from '@core/bus/apis'
import { import {
SHOW_INPUT_BOX SHOW_INPUT_BOX
} from '~/universal/events/constants' } from '~/universal/events/constants'

View File

@ -1,13 +1,13 @@
import bus from '~/main/utils/eventBus' import bus from '@core/bus'
import { import {
uploadClipboardFiles, uploadClipboardFiles,
uploadChoosedFiles uploadChoosedFiles
} from '~/main/apis/uploader/api' } from 'apis/app/uploader/apis'
import { import {
createMenu createMenu
} from '~/main/apis/app' } from 'apis/app/system'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { import {
UPLOAD_WITH_FILES, UPLOAD_WITH_FILES,
UPLOAD_WITH_FILES_RESPONSE, UPLOAD_WITH_FILES_RESPONSE,
@ -18,7 +18,7 @@ import {
GET_SETTING_WINDOW_ID, GET_SETTING_WINDOW_ID,
GET_SETTING_WINDOW_ID_RESPONSE, GET_SETTING_WINDOW_ID_RESPONSE,
CREATE_APP_MENU CREATE_APP_MENU
} from '~/main/apis/bus/constants' } from '@core/bus/constants'
function initEventCenter () { function initEventCenter () {
const eventList: any = { const eventList: any = {
'picgo:upload': uploadClipboardFiles, 'picgo:upload': uploadClipboardFiles,

View File

@ -5,19 +5,19 @@ import {
Notification, Notification,
IpcMainEvent IpcMainEvent
} from 'electron' } from 'electron'
import windowManager from '~/main/apis/window/windowManager' import windowManager from 'apis/app/window/windowManager'
import { IWindowList } from '~/main/apis/window/constants' import { IWindowList } from 'apis/app/window/constants'
import uploader from '~/main/apis/uploader' import uploader from 'apis/app/uploader'
import pasteTemplate from '#/utils/pasteTemplate' import pasteTemplate from '#/utils/pasteTemplate'
import db from '#/datastore' import db from '#/datastore'
import server from '~/main/server' import server from '~/main/server'
import getPicBeds from '~/main/utils/getPicBeds' import getPicBeds from '~/main/utils/getPicBeds'
import shortKeyHandler from '~/main/apis/shortKey/shortKeyHandler' import shortKeyHandler from 'apis/app/shortKey/shortKeyHandler'
import bus from '~/main/utils/eventBus' import bus from '@core/bus'
import { import {
uploadClipboardFiles, uploadClipboardFiles,
uploadChoosedFiles uploadChoosedFiles
} from '~/main/apis/uploader/api' } from '~/main/apis/app/uploader/apis'
import picgoCoreIPC from './picgoCoreIPC' import picgoCoreIPC from './picgoCoreIPC'
import { handleCopyUrl } from '~/main/utils/common' import { handleCopyUrl } from '~/main/utils/common'

View File

@ -1,5 +1,5 @@
import path from 'path' import path from 'path'
import GuiApi from '../gui' import GuiApi from 'apis/gui'
import { import {
dialog, dialog,
shell, shell,
@ -9,8 +9,8 @@ import {
} 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'
import shortKeyHandler from '../shortKey/shortKeyHandler' import shortKeyHandler from '../apis/app/shortKey/shortKeyHandler'
import picgo from '~/main/apis/picgo' import picgo from '@core/picgo'
// 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

View File

@ -4,8 +4,8 @@ import {
handleResponse, handleResponse,
ensureHTTPLink ensureHTTPLink
} from './utils' } from './utils'
import picgo from '~/main/apis/picgo' import picgo from '@core/picgo'
import logger from '~/main/utils/logger' import logger from '@core/picgo/logger'
import axios from 'axios' import axios from 'axios'
class Server { class Server {

View File

@ -2,11 +2,11 @@ import router from './router'
import { import {
uploadWithClipboardFiles, uploadWithClipboardFiles,
uploadWithFiles uploadWithFiles
} from '~/main/apis/bus/index' } from '@core/bus/apis'
import { import {
handleResponse handleResponse
} from './utils' } from './utils'
import logger from '../utils/logger' import logger from '@core/picgo/logger'
router.post('/upload', async ({ router.post('/upload', async ({
response, response,

View File

@ -1,4 +1,4 @@
import picgo from '../apis/picgo' import picgo from '@core/picgo'
const getPicBeds = () => { const getPicBeds = () => {
const picBedTypes = picgo.helper.uploader.getIdList() const picBedTypes = picgo.helper.uploader.getIdList()

View File

@ -1,76 +0,0 @@
import chalk from 'chalk'
import dayjs from 'dayjs'
import fs from 'fs-extra'
import path from 'path'
import util from 'util'
import db from '#/datastore'
import { app } from 'electron'
import { IChalkType } from '#/types/enum'
const baseDir = app.getPath('userData')
class Logger {
private level = {
success: IChalkType.success,
info: IChalkType.info,
warn: IChalkType.warn,
error: IChalkType.error
}
protected handleLog (type: ILogType, msg: ILoggerType): ILoggerType {
// if configPath is invalid then this.ctx.config === undefined
// if not then check config.silent
const log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]:`)
console.log(log, msg)
process.nextTick(() => {
this.handleWriteLog(type, msg)
})
return msg
}
protected handleWriteLog (type: string, msg: ILoggerType): void {
try {
const logLevel = db.get('settings.logLevel')
const logPath = db.get('settings.logPath') || path.join(baseDir, './picgo.log')
if (this.checkLogLevel(type, logLevel)) {
const picgoLog = fs.createWriteStream(logPath, { flags: 'a', encoding: 'utf8' })
let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ${type.toUpperCase()}] ${msg}`
const logger = new console.Console(picgoLog)
if (typeof msg === 'object' && type === 'error') {
log += `\n------Error Stack Begin------\n${util.format(msg.stack)}\n-------Error Stack End-------`
}
logger.log(log)
picgoLog.destroy()
}
} catch (e) {
console.log(e)
}
}
protected checkLogLevel (type: string, level: undefined | string | string[]): boolean {
if (level === undefined || level === 'all') {
return true
}
if (Array.isArray(level)) {
return level.some((item: string) => (item === type || item === 'all'))
} else {
return type === level
}
}
success (msg: ILoggerType): ILoggerType {
return this.handleLog('success', msg)
}
info (msg: ILoggerType): ILoggerType {
return this.handleLog('info', msg)
}
error (msg: ILoggerType): ILoggerType {
return this.handleLog('error', msg)
}
warn (msg: ILoggerType): ILoggerType {
return this.handleLog('warn', msg)
}
}
export default new Logger()

View File

@ -3,13 +3,13 @@ import {
} from 'electron' } from 'electron'
import { import {
IWindowList IWindowList
} from '~/main/apis/window/constants' } from 'apis/app/window/constants'
declare interface IWindowListItem { declare interface IWindowListItem {
isValid: boolean isValid: boolean
multiple: boolean multiple: boolean
options: () => IBrowserWindowOptions, options: () => IBrowserWindowOptions,
callback: (window: BrowserWindow | null) => void callback: (window: BrowserWindow) => void
} }
declare interface IWindowManager { declare interface IWindowManager {

View File

@ -30,6 +30,12 @@
], ],
"#/*": [ "#/*": [
"src/universal/*" "src/universal/*"
],
"apis/*": [
"src/main/apis/*"
],
"@core/*": [
"src/main/apis/core/*"
] ]
}, },
"lib": [ "lib": [

View File

@ -20,6 +20,8 @@ module.exports = {
.set('~', resolve('src')) .set('~', resolve('src'))
.set('root', resolve('./')) .set('root', resolve('./'))
.set('#', resolve('src/universal')) .set('#', resolve('src/universal'))
.set('apis', resolve('src/main/apis'))
.set('@core', resolve('src/main/apis/core'))
}, },
builderOptions: { builderOptions: {
productName: 'PicGo', productName: 'PicGo',