correção para o sistema de atualização

This commit is contained in:
Eder Moraes 2025-05-31 13:45:33 -03:00
parent 34a4d5a681
commit e3c741d7e0
6 changed files with 128 additions and 25 deletions

84
main.js
View File

@ -2,18 +2,23 @@ const { app, BrowserWindow, ipcMain, screen, net } = require('electron');
const path = require('path');
const fs = require('fs');
const { autoUpdater } = require('electron-updater');
const { autoUpdater, AppUpdater } = require('electron-updater');
const pjson = require(path.join(__dirname,'','package.json'));
let floatingWin;
let mainWin;
let loginWin;
let operatorWin;
let updateWin;
const dataPath = path.join(__dirname, 'data.json'); // Caminho para o JSON (backup local)
const apiUrl = 'https://autoatend.linco.work/api/v1/';
const updUrl = 'https://autoatend.linco.work/public/aa_upd/';
autoUpdater.setFeedURL(updUrl);
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;
// autoUpdater.autoDownloadOnStartup = true;
if(!pjson.isBuildNow){
require('electron-reload')(__dirname,{
@ -127,6 +132,29 @@ function createOperatorWindow() {
});
}
function createUpdateWindow() {
updateWin = new BrowserWindow({
width: 600,
height: 300,
show: false, // Inicia oculta
frame: true,
autoHideMenuBar: true, // Oculta a barra de menus
menuBarVisible: false, // Garante que a barra de menus começa
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: true,
},
});
updateWin.loadFile('update.html');
updateWin.on('closed', () => {
updateWin = null;
});
}
function createFloatingWindow() {
const primaryDisplay = screen.getPrimaryDisplay();
const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize;
@ -207,24 +235,26 @@ function createMainWindow() {
});
}
function verifyUpdates(){
if(pjson.isBuildNow){
autoUpdater.on('update-available', () => {
let pth = autoUpdater.downloadUpdate();
updateWin.show(); updateWin.focus();
updateWin.webContents.send('update_message',`Uma nova versão está dispinível.`);
})
autoUpdater.on('download-progress',(obj) => {
mainWin.webContents.send('update_version',`Estamos baixando uma nova atualização: ${obj.percent.toFixed(2)}%`);
updateWin.webContents.send('update_message',`Estamos baixando uma nova atualização.`);
});
autoUpdater.on('update-downloaded',(obj) => {
mainWin.webContents.send('update_version',`Atualização concluída: ${obj.percent.toFixed(2)}%`);
updateWin.webContents.send('update_message',`Atualização concluída. Aguarde!`);
setTimeout(()=>{
autoUpdater.quitAndInstall();
},5000);
});
autoUpdater.on('update-available', () => {
mainWin.webContents.send('update_version',`Uma nova versão está dispinível.`);
})
autoUpdater.on('error',err => {
mainWin.webContents.send('error',err);
updateWin.webContents.send('update_message',err);
});
}
verifyUpdates();
@ -239,7 +269,7 @@ app.whenReady().then(async () => {
createLoginWindow();
} else {
// Se já estiver autenticado, verifica se tem operador selecionado
const operator = await getSelectedOperator();
// const operator = await getSelectedOperator();
if (!operator || operator === 'null' || operator === null || operator === undefined || operator === '') {
// Se não tiver operador selecionado, mostra a tela de seleção
@ -249,8 +279,9 @@ app.whenReady().then(async () => {
createFloatingWindow();
createMainWindow();
}
}
createUpdateWindow();
app.on('activate', () => {
// No macOS é comum recriar uma janela no aplicativo quando o
@ -260,8 +291,14 @@ app.whenReady().then(async () => {
// mas como temos a flutuante, talvez não precise.
if (!floatingWin) createFloatingWindow();
if (!mainWin) createMainWindow();
if (!updateWin) createUpdateWindow();
}
});
if(pjson.isBuildNow){
autoUpdater.checkForUpdates();
}
});
// Função para verificar se já existe um operador selecionado
@ -306,6 +343,24 @@ async function getSelectedOperatorId() {
}
ipcMain.on('update_version', async (event, arg) => {
if(updateWin){
if(!updateWin.isVisible()){
updateWin.show();
updateWin.focus();
}else{
updateWin.focus();
}
} else {
createUpdateWindow();
updateWin.webContents.on('did-finish-load', () => {
updateWin.show();
updateWin.focus();
});
}
});
// Ouvir pedido para obter contagem (ex: se o JSON for atualizado)
ipcMain.handle('get-count', async () => {
const data = readData();
@ -566,6 +621,7 @@ ipcMain.on('select-operator', async (event, operator) => {
operatorWin.close();
createFloatingWindow();
createMainWindow();
createUpdateWindow();
});
} catch (error) {
event.reply('operator-response', {
@ -685,6 +741,8 @@ ipcMain.on('token-exists', async () => {
createFloatingWindow();
createMainWindow();
}
//TODO sempre que já existir um token ele checa por novas atualizações
createUpdateWindow();
});

View File

@ -9,6 +9,7 @@
</head>
<body class="operator-page">
<div class="operator-container">
<h5>App Version: <span id="version"></span></h5>
<h1>Selecione o Operador</h1>
<div id="error-message" class="error-message"></div>

View File

@ -6,15 +6,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
iniciaAtendimento: (itemId) => ipcRenderer.send('iniciar-atendimento', itemId),
logoutApp: () => ipcRenderer.send('logout'),
saveObservation: (data) => ipcRenderer.send('save-observation', data), // data = { itemId, observation }
saveObservation: (data) => ipcRenderer.send('save-observation', data),
updVersion: (callback) => ipcRenderer.on('update_version',(_event,arg) => callback(arg)),
updMessage: (callback) => ipcRenderer.on('update_message', (_event,data) => callback(data)),
updPercent: (callback) => ipcRenderer.on('update_percent', (_event,data) => callback(data)),
atualVersion: (callback) => ipcRenderer.on('atual_version', (_event,data) => callback(data)),
updNVersion: (callback) => ipcRenderer.on('update_new_version', (_event,data) => callback(data)),
updAvailable: () => ipcRenderer.on('update-available',(event,arg)=>{
console.log(arg);
}),
currVersion: () => ipcRenderer.on('current_version',(event,arg)=>{
console.log('Versão atual = ' + arg);
}),
updError: () => ipcRenderer.on('error',(event,arg)=>{
console.log('error = ' + arg);
}),
// updateMessage: (data) => ipcRenderer.send('update_message', data),
// updPercent: (data) => ipcRenderer.send('update_percent', data),
// atualVersion: (data) => ipcRenderer.send('atual_version', data),
// updNVersion: (data) => ipcRenderer.send('update_new_version', data),
});

View File

@ -22,7 +22,7 @@ let selectedItemName = '';
//chama o proximo da fila ao abrir a janela de atendimentos
window.electronAPI.selectAtendID((data)=>{
selectedItemId = data.id;
queueNumber.innerHTML = data ? 'Chamando: '+data.senhaGen + ' - '+ data.clientName.toUpperCase() + ' - ' + data.descricaoServico.toUpperCase() : 'Ninguem aguardando atendimento';
queueNumber.innerHTML = data ? 'Chamando: '+ /*data.senhaGen + ' - '+*/ data.clientName.toUpperCase() + ' - ' + data.descricaoServico.toUpperCase() : 'Ninguem aguardando atendimento';
});
// Função para popular a lista de itens
@ -46,7 +46,7 @@ function populateList() {
selectedItemId = itemToProcess.id;
selectedItemName = itemToProcess.clientName;
const li = document.createElement('li');
li.textContent = `${itemToProcess.senhaGen}: ${itemToProcess.clientName.toUpperCase()} - ${itemToProcess.attendanceType.toUpperCase()} - ${itemToProcess.descricaoServico.toUpperCase()}`;
li.textContent = /*${itemToProcess.senhaGen}: */ `${itemToProcess.clientName.toUpperCase()} - ${itemToProcess.attendanceType.toUpperCase()} - ${itemToProcess.descricaoServico.toUpperCase()}`;
li.dataset.id = itemToProcess.id; // Armazena o ID no elemento
li.classList.add('selected'); // Marca como selecionado visualmente (precisa de CSS)
itemList.appendChild(li);

19
update.html Normal file
View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">
<title>Update</title>
<link rel="stylesheet" href="style.css">
<script src="js/jquery/jquery.js"></script>
</head>
<body class="login-page">
<div class="login-container">
<h1>Atualização de <span id="version"></span> para <span id="newversion"></span></h1>
<div id="message" class="message"></div>
<div id="percent">0%</div>
</div>
<script src="update_renderer.js"></script>
</body>
</html>

22
update_renderer.js Normal file
View File

@ -0,0 +1,22 @@
//janela update
const aVersion = document.getElementById('version');
const uVersion = document.getElementById('newversion');
const updMessage = document.getElementById('message');
const updpercent = document.getElementById('percent');
window.electronAPI.updMessage((data)=>{
updMessage.innerHTML = data;
});
window.electronAPI.updPercent((data)=>{
updpercent.innerHTML = data + '%';
});
window.electronAPI.atualVersion((data)=>{
aVersion.innerHTML = data;
});
window.electronAPI.updNVersion((data)=>{
uVersion.innerHTML = data;
});