Skip to content

Commit

Permalink
refactor(updateChecker):Fix bugs and refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
ni00 committed Jun 6, 2023
1 parent 802ea60 commit a7274d6
Showing 1 changed file with 140 additions and 66 deletions.
206 changes: 140 additions & 66 deletions src/main/updateChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,84 +7,163 @@ const { autoUpdater } = require('electron-updater')
const Store = require('electron-store')
const electronStore = new Store()

const release = 'https://api.github.com/repos/emqx/MQTTX/releases/latest'
let language: string = 'en'
const log4js = require('log4js')

const isUpdate = (latest: string, current: string): boolean => {
const latestVersion: number[] = latest.split('.').map((item) => parseInt(item, 10))
const currentVersion: number[] = current.split('.').map((item) => parseInt(item, 10))
let update: boolean = false
log4js.configure({
appenders: {
console: {
type: 'console',
},
file: {
type: 'file',
filename: './logs/app.log', // 指定日志文件路径
},
},
categories: {
default: {
appenders: ['console', 'file'],
level: 'debug',
},
},
})

for (let i: number = 0; i < 3; i++) {
if (currentVersion[i] < latestVersion[i]) {
update = true
}
}
const logger = log4js.getLogger('file')

return update
interface versionDetail {
version: string
detail: string
}

const autoDownload = (latest: string, language: string): void => {
const urlLang = language === 'zh' ? 'zh' : 'en'
const downloadUrl = `https://www.emqx.com/${urlLang}/downloads/MQTTX/${latest}`
autoUpdater.setFeedURL(downloadUrl)
autoUpdater.checkForUpdatesAndNotify()
autoUpdater.on('checking-for-update', () => {})
autoUpdater.on('update-available', () => {})
autoUpdater.on('update-not-available', () => {})
autoUpdater.on('error', () => {})
autoUpdater.on('download-progress', () => {})
autoUpdater.on('update-downloaded', () => {
electronStore.set('isShow', true)
dialog
.showMessageBox({
type: 'info',
title: 'New Version',
buttons: ['Install', 'No'],
message: `Update available: ${latest}`,
})
.then((res) => {
if (res.response === 0) {
// if selected yes
autoUpdater.quitAndInstall()
} else {
dialog.showMessageBox({
type: 'info',
message: 'Automatic update on do not shut down the computer immediately',
})
}
})
})
}

const updateChecker = async (isAuto: boolean = true): Promise<void | boolean> => {
const response = await axios.get(release)
const getCurrentLang = async (): Promise<string> => {
let language: string = 'en'
const { settingService } = useServices()
await settingService.set()
const setting = await settingService.get()
if (setting) {
language = setting.currentLang
}
if (response.status === 200) {
const latest: string = response.data.name
const isPrerelease: boolean = response.data.prerelease
if (latest && isUpdate(latest.slice(1, 6), version) && !isPrerelease) {
autoDownload(latest, language)
} else {
if (!isAuto) {
dialog.showMessageBox({
return language === 'zh' ? 'zh' : 'en'
}

const closeAutoCheck = async (): Promise<void> => {
const { settingService } = useServices()
await settingService.set()
await settingService.update({ autoCheck: false })
}

const getUpdateDtail = async (current: string): Promise<versionDetail | null> => {
const tagsUrl = 'https://api.github.com/repos/emqx/MQTTX/tags'
const tagsRes = await axios.get(tagsUrl)
if (tagsRes.status === 200) {
const tagsList: string[] = tagsRes.data.map((item: any) => item.name)
const latestTagsList: string[] = tagsList.slice(0, tagsList.indexOf(current))
while (latestTagsList.length > 0) {
const latestVersion = latestTagsList.shift()
const versionRes = await axios.get(`https://api.github.com/repos/emqx/MQTTX/releases/tags/${latestVersion}`)
if (versionRes.status === 200 && !versionRes.data.prerelease) {
return {
version: versionRes.data.name,
detail: versionRes.data.body,
}
}
}
}
return null
}

const autoDownload = (currentVersion: string, updateDatail: versionDetail, language: string): void => {
let msgClick: boolean = false
let updateAvailable: boolean = true
let updateDownloaded: boolean = true
logger.debug('####autoDownload####')
const downloadUrl = `https://www.emqx.com/${language}/downloads/MQTTX/${updateDatail.version}`
autoUpdater.setFeedURL(downloadUrl)
autoUpdater.checkForUpdatesAndNotify()
autoUpdater.on('update-available', () => {
// TODO: Replace dialog.showMessageBox with BrowserWindow and display the update logs (versionDetail.detail).
logger.debug('####update-available####', updateAvailable)
if (updateAvailable) {
updateAvailable = false
dialog
.showMessageBox({
type: 'info',
title: '',
buttons: ['OK'],
message: 'There are currently no updates available.',
title: `Update Infomation ${currentVersion}->${updateDatail.version}`,
message: `The software needs to be updated. Do you want to update it immediately?\n${
updateDatail.detail.slice(0, 250) + '...'
}`,
buttons: ['Remind me next time', 'Update now', 'Never Update', 'Ignore this Verion Update'],
})
.then((res) => {
if (res.response === 0) {
autoUpdater.autoDownload = false
} else if (res.response === 1) {
msgClick = true
autoUpdater.downloadUpdate()
} else if (res.response === 2) {
// FIXME: The settings page did not change in time.(will change on the next launch)
closeAutoCheck()
} else {
electronStore.set('isIgnore', updateDatail.version)
}
})
}
})
autoUpdater.on('error', (e: any) => {
logger.debug(e)
})
autoUpdater.on('download-progress', (progressObj: any) => {
// TODO:Add a progress bar for updates.
//progressWindow.webContents.send("downloadProgress", progressObj);
logger.debug('progressObj', progressObj)
})
autoUpdater.on('update-downloaded', () => {
logger.debug('####update-available####', msgClick, updateDownloaded)
if (msgClick && updateDownloaded) {
updateDownloaded = false
dialog
.showMessageBox({
type: 'info',
title: `New Version`,
buttons: ['Quit and Install Now', 'No'],
message: `Update available: ${updateDatail.version}`,
})
.then((res) => {
if (res.response === 0) {
electronStore.set('isShow', true)
autoUpdater.quitAndInstall()
} else {
dialog.showMessageBox({
type: 'info',
message: 'MQTTX will be updated automatically after the next launch.',
})
}
})
}
}
})
}

const updateChecker = async (isAuto: boolean = true): Promise<void | boolean> => {
logger.debug('####updateChecker####')
const currentVersion = `v${version}`
const updateDatail: versionDetail | null = await getUpdateDtail(currentVersion)
const language: string = await getCurrentLang()
if (updateDatail) {
if (isAuto && electronStore.get('isIgnore') === updateDatail.version) {
return false
}
autoDownload(currentVersion, updateDatail, language)
} else if (!isAuto) {
dialog.showMessageBox({
type: 'info',
title: '',
buttons: ['OK'],
message: 'There are currently no updates available.',
})
} else {
return false
}
}
//what's new window

export async function createUpdateWindow() {
const updateWindow = new BrowserWindow({
width: 600,
Expand All @@ -95,12 +174,7 @@ export async function createUpdateWindow() {
enableRemoteModule: true,
},
})
const { settingService } = useServices()
await settingService.set()
const setting = await settingService.get()
if (setting) {
language = setting.currentLang
}
const language: string = await getCurrentLang()
let link: string = 'https://mqttx.app'
link = language === 'zh' ? `${link}/zh` : link
updateWindow.loadURL(`${link}/changelogs/v${version}`)
Expand Down

0 comments on commit a7274d6

Please sign in to comment.