Skip to content

Commit

Permalink
11957 - Replace Auto-updater (Close #338)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ferllings committed Aug 20, 2024
1 parent dcae423 commit daa5ca0
Show file tree
Hide file tree
Showing 23 changed files with 153 additions and 177 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"electron-store": "^8.2.0",
"electron-updater": "^6.2.1",
"focus-visible": "^5.2.1",
"semver": "^7.6.3",
"simple-swizzle": "^0.2.2"
}
}
14 changes: 8 additions & 6 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,12 @@ store.onDidChange('background.picker.shortcut', (newValue) => {
})
if (store.get('allowUpdates') === true) {
// If the CheckForUpdates preference changes, we trigger (or not) the check
store.onDidChange('main.checkForUpdates', (newValue) => {
store.onDidChange('checkForUpdates', (newValue) => {
if (newValue === true) {
checkForUpdates()
} else {
setUpdatesDisabled()
.then((newVersion) => {
mainController.sendEventToAll('newVersion', newVersion)
})
}
})
}
Expand Down Expand Up @@ -248,9 +249,10 @@ app.on('ready', async () => {
// Initiate Update checking if required and allowed
if (store.get('allowUpdates') === true) {
if (store.get('checkForUpdates') === true) {
checkForUpdates()
} else {
setUpdatesDisabled()
checkForUpdates()
.then((newVersion) => {
mainController.sendEventToAll('newVersion', newVersion)
})
}
}
})
Expand Down
28 changes: 0 additions & 28 deletions src/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,34 +30,6 @@ module.exports = (browsers, mainController, store) => {
// y = Math.round(pos[1] + (size[1]/2) - (400/2))
preferences.init(parent)
}
},
{
id: 'menuUpdateDisabled',
label: i18n.menuT('Checking for update is disabled'),
enabled: false,
visible: false
},
{
id: 'menuUpdateChecking',
label: i18n.menuT('Checking for update...'),
enabled: false,
visible: false
}, {
id: 'menuUpdateNotFound',
label: i18n.menuT('Current version is up-to-date'),
enabled: false,
visible: false
}, {
id: 'menuUpdateFound',
label: i18n.menuT('Found update, downloading...'),
enabled: false,
visible: false
}, {
id: 'menuUpdateInstall',
label: i18n.menuT('Install update'),
accelerator: 'CmdOrCtrl+Shift+U',
click: installUpdate,
visible: false
}, {
type: 'separator'
}, {
Expand Down
124 changes: 63 additions & 61 deletions src/update.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,69 @@
/**
* updater.js
*
* Please use manual update only when it is really required, otherwise please use recommended non-intrusive auto update.
*
* Import steps:
* 1. create `updater.js` for the code snippet
* 2. require `updater.js` for menu implementation, and set `checkForUpdates` callback from `updater` for the click property of `Check Updates...` MenuItem.
*/
const { dialog, Menu } = require('electron')
const { autoUpdater } = require('electron-updater')

let releaseName, releaseNotes
autoUpdater.autoDownload = false

autoUpdater.on('error', (error) => {
dialog.showErrorBox('Auto Update Error: ', error == null ? "unknown" : (error.stack || error).toString())
})

autoUpdater.on('update-available', (ev) => {
autoUpdater.downloadUpdate()
var menu = Menu.getApplicationMenu();
menu.getMenuItemById('menuUpdateChecking').visible = false
menu.getMenuItemById('menuUpdateFound').visible = true
})

autoUpdater.on('update-not-available', (ev) => {
var menu = Menu.getApplicationMenu();
menu.getMenuItemById('menuUpdateChecking').visible = false
menu.getMenuItemById('menuUpdateNotFound').visible = true
})

autoUpdater.on('update-downloaded', (ev) => {
releaseName = ev.releaseName
releaseNotes = ev.releaseNotes
var menu = Menu.getApplicationMenu();
menu.getMenuItemById('menuUpdateFound').visible = false
menu.getMenuItemById('menuUpdateInstall').visible = true
})

function setUpdatesDisabled() {
var menu = Menu.getApplicationMenu();
menu.getMenuItemById('menuUpdateDisabled').visible = true
menu.getMenuItemById('menuUpdateNotFound').visible = false
menu.getMenuItemById('menuUpdateFound').visible = false
menu.getMenuItemById('menuUpdateInstall').visible = false
}
const { version } = require('../package.json')
const semver = require('semver')

const apiUrl = 'https://api.github.com/repos/ThePacielloGroup/CCAe/releases?per_page=1'
const downloadUrl = "https://github.com/ThePacielloGroup/CCAe/releases/download"
function checkForUpdates() {
var menu = Menu.getApplicationMenu();
menu.getMenuItemById('menuUpdateDisabled').visible = false
menu.getMenuItemById('menuUpdateChecking').visible = true
autoUpdater.checkForUpdates()
console.log("Checking updates")
return fetch(apiUrl)
.then((response) => response.json())
.then((json) => {
const tagName = semver.clean(json[0].tag_name)
if (semver.valid(tagName) && semver.gt(tagName, version)) {
console.log("Update found", tagName)
return {
version: tagName,
info: json[0].html_url,
download: getPackage(tagName, json[0].tag_name)
}
} else {
console.log("No update found")
return false
}
})
.catch((error) => {
console.error('error while checking for updates', error)
return false
})
}

function installUpdate() {
dialog.showMessageBox({
title: 'Install Updates',
message: `${releaseName} has been downloaded. The application will be closed to install the update.`
}, () => {
setImmediate(() => autoUpdater.quitAndInstall())
})
function getPackage(version, tagName) {
let package
if (process.platform === "win32") {
package = `CCA-Setup-${version}.msi`
} else if (process.platform === "darwin") {
package = `CCA-${version}.dmg`
} else {
package = `Colour-Contrast-Analyser-Setup-${version}.AppImage`
try {
const identity = path.join(process.resourcesPath, "package-type")
if (!existsSync(identity)) {
return package
}
console.info("Checking for beta autoupdate feature for deb/rpm distributions")
const fileType = readFileSync(identity).toString().trim()
console.info("Found package-type:", fileType)
switch (fileType) {
case "deb":
package `Colour-Contrast-Analyser-Setup-${version}.deb`
break
case "rpm":
package `Colour-Contrast-Analyser-Setup-${version}.rpm`
break
default:
break
}
} catch (error) {
console.warn(
"Unable to detect 'package-type' for autoUpdater (beta rpm/deb support)",
error.message)
}
}
if (package) {
return `${downloadUrl}/${tagName}/${package}`
} else {
return null
}
}

module.exports.setUpdatesDisabled = setUpdatesDisabled
module.exports.checkForUpdates = checkForUpdates
module.exports.installUpdate = installUpdate
module.exports.checkForUpdates = checkForUpdates
11 changes: 11 additions & 0 deletions src/views/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -351,3 +351,14 @@ section#results .contrast-level img {
width: 1.2rem;
margin-bottom: -0.2rem;
}

section#updateAvailable .flex {
display: flex;
justify-content: space-between;
align-items: center;
}

section#updateAvailable button {
font-size: 1rem;
border-radius: 1rem;
}
34 changes: 34 additions & 0 deletions src/views/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,31 @@ ipcRenderer.on('showPicker', (event, section) => {
})
})

ipcRenderer.on('newVersion', (event, newVersion) => {
const updateSection = document.querySelector("#updateAvailable")
const updateSectionContent = updateSection.querySelector(".content")
if (newVersion !== false) {
updateSectionContent.innerHTML = `${i18n['Version {version} is available.'].replace("{version}", newVersion.version)} <a href="${newVersion.info}" class="external-link">${i18n["More details"]}</a>`
if (newVersion.download) {
updateSectionContent.innerHTML += ` - <a href="${newVersion.download}" class="external-link">${i18n["Download"]}</a>`
}
var externalLinks = updateSectionContent.querySelectorAll('.external-link')

Array.from(externalLinks).forEach(link => {
var url = link.getAttribute('href')
link.addEventListener('click', function(event) {
shell.openExternal(url)
event.preventDefault()
})
});
updateSectionContent.innerHTML += ``
updateSection.removeAttribute('hidden')
} else {
updateSection.setAttribute('hidden', '')
updateSectionContent.innerHTML = ''
}
})

function initEvents () {
// Opens color picker on button click
document.querySelector('#foreground-color .picker').onclick = () => ipcRenderer.send('getColorFromPicker', 'foreground')
Expand All @@ -155,6 +180,7 @@ function initEvents () {
document.querySelector('#background-color .help').onclick = function() {showHide(this)};
document.querySelector('#foreground-color .format-selector').onchange = function() {changeFormat('foreground', this)};
document.querySelector('#background-color .format-selector').onchange = function() {changeFormat('background', this)};
document.querySelector('#updateAvailable button').onclick = function(){closeSection(this.parentElement.parentElement)}

// screen reader announcement for screen reader user.
document.querySelector('#foreground-color .switch').addEventListener("click",function() {
Expand Down Expand Up @@ -246,6 +272,12 @@ function showHide(el, force) {
ipcRenderer.send('height-changed', mainHeight);
}

function closeSection(el) {
el.setAttribute('hidden', '')
var mainHeight = document.querySelector('main').clientHeight;
ipcRenderer.send('height-changed', mainHeight);
}

function applyColor(section, color) {
applyColorPreview(section, color)
applyColorTextString(section, color)
Expand Down Expand Up @@ -539,6 +571,8 @@ function translateHTML() {
document.querySelector('details span#sc_1_4_3').innerHTML = i18n['sc_1_4_3']
document.querySelector('details span#sc_1_4_6').innerHTML = i18n['sc_1_4_6']
document.querySelector('details span#sc_1_4_11').innerHTML = i18n['sc_1_4_11']

document.querySelector('#updateAvailable button').setAttribute("aria-label", i18n['Close'])
}

function setColorScheme (v) {
Expand Down
2 changes: 1 addition & 1 deletion src/views/js/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ function translateHTML(_i18n) {
});

// Check for update
document.querySelector('label[for="option-checkForUpdates"] span').innerText = i18n["Enable update checking"];
document.querySelector('label[for="option-checkForUpdates"] span').innerText = i18n["Check for updates"];

// Language
document.querySelector('label[for="option-lang"]').textContent = i18n['Language'];
Expand Down
6 changes: 6 additions & 0 deletions src/views/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
<body>
<main>
<h1 class="sr-only">CCA Main windows</h1>
<section id="updateAvailable" hidden>
<div class="flex">
<div class="content"></div>
<button aria-label="Close">X</button>
</div>
</section>
<section id="foreground-color">
<h2>Foreground colour</h2>
<div class="container">
Expand Down
2 changes: 1 addition & 1 deletion src/views/preferences.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ <h1 class="sr-only">Preferences</h1>
<div class="option" id="checkForUpdates" hidden>
<label for="option-checkForUpdates"><input type="checkbox" id="option-checkForUpdates" />
<span>
Enable update checking
Check For Updates
</span>
</label>
</div>
Expand Down
7 changes: 1 addition & 6 deletions src/views/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
"Menu": {
"Colour Contrast Analyser (CCA)": "Colour Contrast Analyser (CCA)",
"About CCA": "Über CCA",
"Checking for update is disabled": "Automatische Updates sind deaktiviert",
"Checking for update...": "Suche nach Updates...",
"Current version is up-to-date": "Ihre Version ist aktuell",
"Found update, downloading...": "Updates gefunden, lade sie herunter...",
"Install update": "Installiere Update",
"Quit CCA": "Beende CCA",
"Preferences": "Einstellungen",
"Edit": "Bearbeiten",
Expand Down Expand Up @@ -135,7 +130,7 @@
"Contrast ratio precision": "Präzision des Kontrastverhältnisses",
"1 decimal place": "1 Dezimalstelle",
"2 decimal places": "2 Dezimalstellen",
"Enable update checking": "Automatische Updates ermöglichen",
"Check for updates": "Automatische Updates ermöglichen",
"Language": "Sprache",
"Application Theme": "Application Theme",
"System (Default)": "System (Default)",
Expand Down
13 changes: 6 additions & 7 deletions src/views/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
"Menu": {
"Colour Contrast Analyser (CCA)": "Colour Contrast Analyser (CCA)",
"About CCA": "About CCA",
"Checking for update is disabled": "Checking for update is disabled",
"Checking for update...": "Checking for update...",
"Current version is up-to-date": "Current version is up-to-date",
"Found update, downloading...": "Found update, downloading...",
"Install update": "Install update",
"Quit CCA": "Quit CCA",
"Preferences": "Preferences",
"Edit": "Edit",
Expand Down Expand Up @@ -104,7 +99,11 @@
"Between the background and foreground colors have swapped.":"Between the background and foreground colors have swapped.",
"Results copied.":"Results copied.",
"Short results copied.":"Short results copied."
}
},
"Version {version} is available.":"Version {version} is available.",
"More details":"More details",
"Download":"Download",
"Close": "Close"
},
"Deficiency": {
"Title": "Colour blindness simulation",
Expand Down Expand Up @@ -137,7 +136,7 @@
"Contrast ratio precision": "Contrast ratio precision",
"1 decimal place": "1 decimal place",
"2 decimal places": "2 decimal places",
"Enable update checking": "Enable update checking",
"Check for updates": "Check for updates",
"Language": "Language",
"Application Theme": "Application Theme",
"System (Default)": "System (Default)",
Expand Down
7 changes: 1 addition & 6 deletions src/views/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
"Menu": {
"Colour Contrast Analyser (CCA)": "Colour Contrast Analyser (CCA)",
"About CCA": "About CCA",
"Checking for update is disabled": "La actualizaciones automáticas estan desactivadas",
"Checking for update...": "Comprobando actualizaciones...",
"Current version is up-to-date": "La versión actual está al día",
"Found update, downloading...": "Actualizaciones encontradas, descargando...",
"Install update": "Instalar actualización",
"Quit CCA": "Abandonar CCA",
"Preferences": "Preferencias",
"Edit": "Editar",
Expand Down Expand Up @@ -135,7 +130,7 @@
"Contrast ratio precision": "Precisión de relacion del contraste",
"1 decimal place": "1er lugar decimal",
"2 decimal places": "2do lugares decimales",
"Enable update checking": "Habilitar actualizaciones automáticas",
"Check for updates": "Habilitar actualizaciones automáticas",
"Language": "Idioma",
"Application Theme": "Application Theme",
"System (Default)": "System (Default)",
Expand Down
Loading

0 comments on commit daa5ca0

Please sign in to comment.