202 lines
6.9 KiB
JavaScript
202 lines
6.9 KiB
JavaScript
import puppeteer from 'puppeteer-core';
|
|
import fetch from 'node-fetch';
|
|
import { app, BrowserWindow, Notification } from 'electron';
|
|
import pie from 'puppeteer-in-electron';
|
|
|
|
// Configuración
|
|
const CONFIG = {
|
|
URL: 'https://rpa.mind.brm.co/app',
|
|
APP_CODE: 'SHP030',
|
|
URL_CONFIRM: 'https://cs.shopee.com.mx/portal/inhouse/',
|
|
TIMEOUT: 10000,
|
|
WAIT_TIME: 5000
|
|
};
|
|
|
|
// Inicialización de puppeteer
|
|
(async () => {
|
|
await pie.initialize(app);
|
|
})();
|
|
|
|
async function queryEndpoint(user) {
|
|
console.log('>> Iniciando consulta al endpoint para el usuario:', user);
|
|
try {
|
|
const response = await fetch(CONFIG.URL, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
user: user,
|
|
code: CONFIG.APP_CODE
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
console.log('>> Respuesta del endpoint recibida');
|
|
const data = await response.json();
|
|
return data;
|
|
} catch (error) {
|
|
console.error('>> Error en consulta al endpoint:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function fillForm(url_app, user, password, xpath_user, xpath_pass) {
|
|
// Agregar notificación al inicio
|
|
new Notification({
|
|
title: 'RPA Shopee',
|
|
body: 'Abriendo Shopee'
|
|
}).show();
|
|
|
|
console.log('>> Iniciando proceso de automatizacion');
|
|
try {
|
|
console.log('>> Creando ventana de Electron');
|
|
const window = new BrowserWindow({
|
|
width: 1200,
|
|
height: 800,
|
|
webPreferences: {
|
|
nodeIntegration: true,
|
|
contextIsolation: false
|
|
}
|
|
});
|
|
|
|
console.log('>> Conectando navegador puppeteer');
|
|
const browser = await pie.connect(app, puppeteer);
|
|
const page = await pie.getPage(browser, window);
|
|
|
|
console.log('>> Navegando a:', url_app);
|
|
await page.goto(url_app);
|
|
console.log('>> Pagina cargada correctamente');
|
|
|
|
console.log('>> Buscando boton de login');
|
|
await page.waitForSelector('.login-button');
|
|
await page.click('.login-button');
|
|
console.log('>> Boton de login clickeado');
|
|
|
|
const isExistingAccount = await checkExistingAccount(page, user);
|
|
|
|
if (!isExistingAccount && !await checkLoginStatus(page)) {
|
|
console.log('>> No se detectó sesión activa, iniciando login manual');
|
|
await performLogin(page, user, password, xpath_user, xpath_pass);
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('>> Error en el proceso de automatizacion:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function checkExistingAccount(page, user) {
|
|
console.log('>> Verificando cuenta existente');
|
|
try {
|
|
console.log('>> Buscando selector de cuentas');
|
|
await page.waitForSelector('::-p-xpath(//h1[contains(text(), "Choose an account")])', { timeout: CONFIG.TIMEOUT });
|
|
console.log('>> Buscando cuenta del usuario:', user);
|
|
const account_active = await page.waitForSelector('::-p-xpath(//span[contains(text(), "'+user+'")])', { timeout: CONFIG.TIMEOUT });
|
|
await account_active.click();
|
|
console.log('>> Cuenta seleccionada');
|
|
|
|
try {
|
|
console.log('>> Buscando boton Allow');
|
|
await new Promise(resolve => setTimeout(resolve, CONFIG.WAIT_TIME));
|
|
const input_continue = await page.waitForSelector('::-p-xpath(//button[contains(text(), "Allow")])', { timeout: CONFIG.TIMEOUT });
|
|
await input_continue.click();
|
|
console.log('>> Boton Allow clickeado');
|
|
|
|
// Agregar verificación de login
|
|
console.log('>> Verificando login después de Allow');
|
|
const loginStatus = await checkLoginStatus(page);
|
|
if (loginStatus) {
|
|
console.log('>> Login exitoso con cuenta existente');
|
|
return true;
|
|
}
|
|
console.log('>> Login no exitoso con cuenta existente');
|
|
} catch (error) {
|
|
console.log('>> No se encontro boton Allow');
|
|
}
|
|
return true;
|
|
} catch (error) {
|
|
console.log('>> No se encontraron cuentas existentes');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function checkLoginStatus(page) {
|
|
console.log('>> Verificando estado de login');
|
|
const startTime = Date.now();
|
|
|
|
while (Date.now() - startTime < CONFIG.TIMEOUT) {
|
|
const currentUrl = page.url();
|
|
console.log('>> URL actual:', currentUrl);
|
|
|
|
if (currentUrl.includes(CONFIG.URL_CONFIRM)) {
|
|
console.log('>> Usuario logueado exitosamente');
|
|
// Agregar notificación de login exitoso
|
|
new Notification({
|
|
title: 'RPA Shopee',
|
|
body: 'Usuario logueado exitosamente'
|
|
}).show();
|
|
return true;
|
|
}
|
|
await new Promise(resolve => setTimeout(resolve, 500));
|
|
}
|
|
console.log('>> Timeout en verificación de login');
|
|
return false;
|
|
}
|
|
|
|
async function performLogin(page, user, password, xpath_user, xpath_pass) {
|
|
console.log('>> Iniciando proceso de login manual');
|
|
|
|
console.log('>> Ingresando usuario');
|
|
const input_user = await page.waitForSelector('::-p-xpath(' + xpath_user + ')');
|
|
await input_user.type(user);
|
|
await input_user.press('Enter');
|
|
console.log('>> Usuario ingresado');
|
|
|
|
await new Promise(resolve => setTimeout(resolve, CONFIG.WAIT_TIME));
|
|
|
|
console.log('>> Ingresando contraseña');
|
|
const input_pass = await page.waitForSelector('::-p-xpath(' + xpath_pass + ')');
|
|
await input_pass.type(password);
|
|
await input_pass.press('Enter');
|
|
console.log('>> Contraseña ingresada');
|
|
|
|
try {
|
|
console.log('>> Buscando botón Allow');
|
|
const input_continue = await page.waitForSelector('::-p-xpath(//button[contains(text(), "Allow")])');
|
|
await input_continue.click();
|
|
console.log('>> Botón Allow clickeado');
|
|
} catch (error) {
|
|
console.log('>> No se encontró botón Allow');
|
|
}
|
|
|
|
return await checkLoginStatus(page);
|
|
}
|
|
|
|
// Modified main process
|
|
app.on('ready', async () => {
|
|
console.log('Aplicacion lista');
|
|
try {
|
|
const data_user = await queryEndpoint('45957768');
|
|
console.log(data_user);
|
|
if (data_user.App) {
|
|
console.log('Se obtuvo la info del usuario');
|
|
await fillForm(data_user.App, data_user.User, data_user.Password, data_user.Xpath_user, data_user.Xpath_pass);
|
|
} else {
|
|
console.log('No se pudo obtener la info del usuario');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error in main process:', error);
|
|
}
|
|
});
|
|
|
|
// Prevent app from closing when all windows are closed
|
|
app.on('window-all-closed', () => {
|
|
if (process.platform !== 'darwin') {
|
|
app.quit();
|
|
}
|
|
});
|