696 lines
31 KiB
JavaScript
696 lines
31 KiB
JavaScript
const fs = require('fs');
|
||
const path = require('path');
|
||
const { dialog } = require('electron');
|
||
const os = require('os');
|
||
|
||
// Función para verificar y encontrar la DLL de AutoIt
|
||
function findAutoItDLL() {
|
||
const { app } = require('electron');
|
||
const isPackaged = app ? app.isPackaged : false;
|
||
|
||
console.log(`[DLL] Aplicación empaquetada: ${isPackaged}`);
|
||
|
||
let possiblePaths;
|
||
|
||
if (isPackaged) {
|
||
possiblePaths = [
|
||
// 1. PRIMERA PRIORIDAD: Ruta fija del sistema
|
||
'C:/RpaClaro/AutoItX3_x64.dll',
|
||
|
||
// 2. extraResources (copiados por electron-builder)
|
||
path.join(process.resourcesPath, 'dlls', 'AutoItX3_x64.dll'),
|
||
|
||
// 3. app.asar.unpacked (desempaquetados)
|
||
path.join(process.resourcesPath, 'app.asar.unpacked', 'dlls', 'AutoItX3_x64.dll'),
|
||
path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', 'node-autoit-koffi', 'lib', 'AutoItX3_x64.dll'),
|
||
|
||
// 4. extraFiles (directorio de instalación)
|
||
path.join(path.dirname(process.execPath), 'dlls', 'AutoItX3_x64.dll'),
|
||
path.join(path.dirname(process.execPath), 'lib', 'autoit', 'AutoItX3_x64.dll'),
|
||
|
||
// 5. Fallbacks
|
||
'C:/RpaClaro/AutoItX3.dll',
|
||
path.join(process.resourcesPath, 'dlls', 'AutoItX3.dll')
|
||
];
|
||
} else {
|
||
possiblePaths = [
|
||
// Desarrollo
|
||
'C:/RpaClaro/AutoItX3_x64.dll',
|
||
path.join(__dirname, 'dlls', 'AutoItX3_x64.dll'),
|
||
path.join(process.cwd(), 'dlls', 'AutoItX3_x64.dll'),
|
||
'C:/Users/TARS/Desktop/rpa/dlls/AutoItX3_x64.dll'
|
||
];
|
||
}
|
||
|
||
console.log('[DLL] Buscando AutoIt DLL en rutas posibles...');
|
||
|
||
for (const dllPath of possiblePaths) {
|
||
console.log(`[DLL] Verificando: ${dllPath}`);
|
||
try {
|
||
if (fs.existsSync(dllPath)) {
|
||
console.log(`[DLL] ✓ DLL encontrada en: ${dllPath}`);
|
||
|
||
const stats = fs.statSync(dllPath);
|
||
console.log(`[DLL] ✓ Tamaño del archivo: ${stats.size} bytes`);
|
||
|
||
if (stats.size > 100000) {
|
||
console.log(`[DLL] ✓ DLL válida encontrada: ${dllPath}`);
|
||
return dllPath;
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.log(`[DLL] ✗ Error verificando ${dllPath}: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
console.log('[DLL] ✗ No se encontró AutoIt DLL válida en ninguna ruta');
|
||
return null;
|
||
}
|
||
|
||
|
||
|
||
// Función mejorada para copiar DLLs
|
||
function ensureDLLsAvailable() {
|
||
const { app } = require('electron');
|
||
const isPackaged = app ? app.isPackaged : false;
|
||
|
||
if (!isPackaged) {
|
||
console.log('[DLL_COPY] Modo desarrollo, no se requiere copia de DLLs');
|
||
return;
|
||
}
|
||
|
||
console.log('[DLL_COPY] Verificando disponibilidad de DLLs para aplicación empaquetada...');
|
||
|
||
// Verificar primero en extraResources
|
||
const resourcesPath = process.resourcesPath;
|
||
const resourcesDllPath = path.join(resourcesPath, 'dlls', 'AutoItX3_x64.dll');
|
||
|
||
if (fs.existsSync(resourcesDllPath)) {
|
||
console.log(`[DLL_COPY] ✓ DLL encontrada en extraResources: ${resourcesDllPath}`);
|
||
return; // No necesitamos copiar, ya está disponible
|
||
}
|
||
|
||
// Si no está en extraResources, intentar copiar desde sistema
|
||
const sourcePaths = [
|
||
'C:/RpaClaro/AutoItX3_x64.dll',
|
||
'C:/RpaClaro/AutoItX3.dll'
|
||
];
|
||
|
||
const targetDir = path.join(path.dirname(process.execPath), 'dlls');
|
||
|
||
// Crear directorio dlls si no existe
|
||
if (!fs.existsSync(targetDir)) {
|
||
try {
|
||
fs.mkdirSync(targetDir, { recursive: true });
|
||
console.log(`[DLL_COPY] ✓ Directorio creado: ${targetDir}`);
|
||
} catch (error) {
|
||
console.log(`[DLL_COPY] ✗ Error creando directorio: ${error.message}`);
|
||
return;
|
||
}
|
||
}
|
||
|
||
for (const sourcePath of sourcePaths) {
|
||
if (fs.existsSync(sourcePath)) {
|
||
const fileName = path.basename(sourcePath);
|
||
const targetPath = path.join(targetDir, fileName);
|
||
|
||
if (!fs.existsSync(targetPath)) {
|
||
try {
|
||
fs.copyFileSync(sourcePath, targetPath);
|
||
console.log(`[DLL_COPY] ✓ DLL copiada: ${sourcePath} → ${targetPath}`);
|
||
} catch (error) {
|
||
console.log(`[DLL_COPY] ✗ Error copiando DLL: ${error.message}`);
|
||
}
|
||
} else {
|
||
console.log(`[DLL_COPY] ℹ DLL ya existe: ${targetPath}`);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
function debugPaths() {
|
||
const { app } = require('electron');
|
||
console.log('\n=== DEBUGGING PATHS ===');
|
||
console.log(`process.execPath: ${process.execPath}`);
|
||
console.log(`process.resourcesPath: ${process.resourcesPath}`);
|
||
console.log(`app.getAppPath(): ${app ? app.getAppPath() : 'N/A'}`);
|
||
console.log(`__dirname: ${__dirname}`);
|
||
console.log(`process.cwd(): ${process.cwd()}`);
|
||
console.log(`app.isPackaged: ${app ? app.isPackaged : 'N/A'}`);
|
||
|
||
// Verificar si existen las rutas críticas
|
||
const criticalPaths = [
|
||
path.join(process.resourcesPath, 'dlls'),
|
||
path.join(path.dirname(process.execPath), 'dlls'),
|
||
'C:/RpaClaro'
|
||
];
|
||
|
||
criticalPaths.forEach(criticalPath => {
|
||
console.log(`${criticalPath}: ${fs.existsSync(criticalPath) ? '✓ EXISTS' : '✗ NOT FOUND'}`);
|
||
if (fs.existsSync(criticalPath)) {
|
||
try {
|
||
const files = fs.readdirSync(criticalPath);
|
||
console.log(` Files: ${files.join(', ')}`);
|
||
} catch (e) {
|
||
console.log(` Error reading directory: ${e.message}`);
|
||
}
|
||
}
|
||
});
|
||
console.log('========================\n');
|
||
}
|
||
|
||
// Función principal actualizada
|
||
function rr(usuario, password) {
|
||
console.log('\n=== INICIANDO FUNCIÓN RR() ===');
|
||
|
||
debugPaths();
|
||
|
||
console.log(`[AUTH] Usuario: ${usuario}`);
|
||
console.log(`[AUTH] Password: ${'*'.repeat(password.length)} (longitud: ${password.length})`);
|
||
|
||
// Verificar arquitectura del sistema
|
||
const systemArch = checkSystemArchitecture();
|
||
|
||
// PASO CRÍTICO: Asegurar que las DLLs estén disponibles
|
||
ensureDLLsAvailable();
|
||
|
||
// Generar contenido del archivo de macro (código existente...)
|
||
const texto = `<HAScript name="macrologin" description="" timeout="60000" pausetime="300" promptall="true" blockinput="true" author="Usuario" creationdate="19/07/2023 07:57:48 PM" supressclearevents="false" usevars="true" ignorepauseforenhancedtn="true" delayifnotenhancedtn="0" ignorepausetimeforenhancedtn="true" continueontimeout="false">
|
||
<screen name="Pantalla1" entryscreen="true" exitscreen="true" transient="false">
|
||
<description >
|
||
<oia status="NOTINHIBITED" optional="false" invertmatch="false" />
|
||
<numfields number="184" optional="true" invertmatch="false" />
|
||
<numinputfields number="6" optional="true" invertmatch="false" />
|
||
</description>
|
||
<actions>
|
||
<input value="'${usuario}[tab]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'${password}'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[enter]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[sysreq]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'1'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[enter]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'${usuario}[tab]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'${password}'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[enter]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[sysreq]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'1'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
<input value="'[enter]'" row="0" col="0" movecursor="true" xlatehostkeys="true" encrypted="false" />
|
||
</actions>
|
||
<nextscreens timeout="0" >
|
||
</nextscreens>
|
||
</screen>
|
||
</HAScript>`;
|
||
|
||
console.log(`[MACRO] Contenido de macro generado con ${texto.split('\n').length} líneas`);
|
||
|
||
// Verificar y eliminar archivo existente
|
||
const nombreArchivo = path.join('C:', 'RpaClaro', 'macrologin.mac');
|
||
verificarYEliminarArchivo(nombreArchivo);
|
||
|
||
// Generar nuevo archivo
|
||
generarArchivo(nombreArchivo, texto);
|
||
|
||
|
||
async function loadAutoItWithDependencies(autoItDllPath) {
|
||
const { app } = require('electron');
|
||
const path = require('path');
|
||
const fs = require('fs');
|
||
|
||
console.log('[AUTOIT_LOADER] Iniciando carga de AutoIt con dependencias...');
|
||
|
||
try {
|
||
// 1. Configurar rutas de módulos nativos
|
||
if (app.isPackaged) {
|
||
const unpackedPath = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules');
|
||
const nodeModulesPath = path.join(process.resourcesPath, 'node_modules');
|
||
|
||
// Agregar rutas a la resolución de módulos
|
||
if (fs.existsSync(unpackedPath)) {
|
||
require('module').globalPaths.unshift(unpackedPath);
|
||
console.log(`[AUTOIT_LOADER] ✓ Ruta desempaquetada agregada: ${unpackedPath}`);
|
||
}
|
||
|
||
if (fs.existsSync(nodeModulesPath)) {
|
||
require('module').globalPaths.unshift(nodeModulesPath);
|
||
console.log(`[AUTOIT_LOADER] ✓ Ruta node_modules agregada: ${nodeModulesPath}`);
|
||
}
|
||
|
||
// Configurar PATH para DLLs nativas
|
||
const dllDir = path.dirname(autoItDllPath);
|
||
const currentPath = process.env.PATH || '';
|
||
if (!currentPath.includes(dllDir)) {
|
||
process.env.PATH = `${dllDir};${currentPath}`;
|
||
console.log(`[AUTOIT_LOADER] ✓ PATH actualizado con: ${dllDir}`);
|
||
}
|
||
}
|
||
|
||
// 2. Cargar node-gyp-build manualmente si está disponible
|
||
try {
|
||
const nodeGypBuild = require('node-gyp-build');
|
||
console.log('[AUTOIT_LOADER] ✓ node-gyp-build cargado exitosamente');
|
||
} catch (nodeGypError) {
|
||
console.log(`[AUTOIT_LOADER] ⚠ node-gyp-build no disponible: ${nodeGypError.message}`);
|
||
|
||
// Intentar cargar desde ruta desempaquetada
|
||
if (app.isPackaged) {
|
||
const nodeGypPath = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', 'node-gyp-build');
|
||
if (fs.existsSync(nodeGypPath)) {
|
||
try {
|
||
require(nodeGypPath);
|
||
console.log('[AUTOIT_LOADER] ✓ node-gyp-build cargado desde ruta desempaquetada');
|
||
} catch (e) {
|
||
console.log(`[AUTOIT_LOADER] ✗ Error cargando node-gyp-build: ${e.message}`);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3. Cargar koffi
|
||
console.log('[AUTOIT_LOADER] Cargando koffi...');
|
||
const koffi = require('koffi');
|
||
console.log('[AUTOIT_LOADER] ✓ Koffi cargado exitosamente');
|
||
|
||
// 4. Cargar node-autoit-koffi
|
||
console.log('[AUTOIT_LOADER] Cargando node-autoit-koffi...');
|
||
let autoit;
|
||
|
||
if (app.isPackaged) {
|
||
// Intentar desde ruta desempaquetada primero
|
||
const autoitModulePath = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', 'node-autoit-koffi');
|
||
if (fs.existsSync(autoitModulePath)) {
|
||
autoit = require(autoitModulePath);
|
||
console.log('[AUTOIT_LOADER] ✓ node-autoit-koffi cargado desde ruta desempaquetada');
|
||
} else {
|
||
autoit = require('node-autoit-koffi');
|
||
console.log('[AUTOIT_LOADER] ✓ node-autoit-koffi cargado normalmente');
|
||
}
|
||
} else {
|
||
autoit = require('node-autoit-koffi');
|
||
console.log('[AUTOIT_LOADER] ✓ node-autoit-koffi cargado (modo desarrollo)');
|
||
}
|
||
|
||
// 5. Configurar DLL si el módulo lo soporta
|
||
if (autoit.setDllPath && typeof autoit.setDllPath === 'function') {
|
||
autoit.setDllPath(autoItDllPath);
|
||
console.log('[AUTOIT_LOADER] ✓ Ruta DLL configurada manualmente');
|
||
}
|
||
|
||
console.log('[AUTOIT_LOADER] ✓ AutoIt cargado exitosamente');
|
||
return autoit;
|
||
|
||
} catch (error) {
|
||
console.error(`[AUTOIT_LOADER] ✗ Error crítico cargando AutoIt: ${error.message}`);
|
||
console.error(`[AUTOIT_LOADER] Stack trace: ${error.stack}`);
|
||
|
||
// Diagnóstico específico para node-gyp-build
|
||
if (error.message.includes('Cannot find module \'node-gyp-build\'')) {
|
||
console.log('[AUTOIT_LOADER] ℹ Error específico: node-gyp-build faltante');
|
||
|
||
const suggestions = [
|
||
'1. Ejecutar: npm install node-gyp-build --save',
|
||
'2. Agregar node-gyp-build a asarUnpack en package.json',
|
||
'3. Ejecutar: npm run rebuild',
|
||
'4. Verificar que todas las dependencias nativas estén instaladas'
|
||
];
|
||
|
||
console.log('[AUTOIT_LOADER] Sugerencias para solucionar:');
|
||
suggestions.forEach(suggestion => console.log(`[AUTOIT_LOADER] ${suggestion}`));
|
||
}
|
||
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
|
||
async function runAS400Launcher() {
|
||
console.log('\n=== INICIANDO AS400 LAUNCHER ===');
|
||
|
||
try {
|
||
|
||
// Buscar la DLL de AutoIt
|
||
const autoItDllPath = findAutoItDLL();
|
||
|
||
if (!autoItDllPath) {
|
||
console.log('[DLL] ✗ ERROR CRÍTICO: No se pudo encontrar AutoItX3.dll');
|
||
return;
|
||
}
|
||
|
||
// Usar el nuevo cargador
|
||
const autoit = await loadAutoItWithDependencies(autoItDllPath);
|
||
|
||
// Continuar con el resto del código AS400...
|
||
console.log('[SETUP] ✓ AutoIt configurado, continuando con AS400...');
|
||
|
||
// Reemplaza la sección de carga de Koffi en runAS400Launcher()
|
||
try {
|
||
console.log(`[DLL] Cargando AutoIt DLL desde: ${autoItDllPath}`);
|
||
|
||
// Cargar koffi y autoit con manejo de errores mejorado
|
||
//let autoit, koffi;
|
||
|
||
try {
|
||
console.log(`[DLL] Cargando AutoIt DLL desde: ${autoItDllPath}`);
|
||
|
||
// Verificar acceso a la DLL
|
||
console.log('[DLL] Verificando acceso a la DLL...');
|
||
fs.accessSync(autoItDllPath, fs.constants.R_OK);
|
||
console.log('[DLL] ✓ DLL accesible para lectura');
|
||
|
||
// Configurar variables de entorno para librerías nativas
|
||
const { app } = require('electron');
|
||
if (app.isPackaged) {
|
||
// Agregar rutas de DLLs al PATH del proceso
|
||
const dllDir = path.dirname(autoItDllPath);
|
||
const currentPath = process.env.PATH || '';
|
||
if (!currentPath.includes(dllDir)) {
|
||
process.env.PATH = `${dllDir};${currentPath}`;
|
||
console.log(`[ENV] ✓ Agregada ruta DLL al PATH: ${dllDir}`);
|
||
}
|
||
|
||
// Configurar ruta de librerías desempaquetadas
|
||
const unpackedPath = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules');
|
||
if (fs.existsSync(unpackedPath)) {
|
||
require('module').globalPaths.push(unpackedPath);
|
||
console.log(`[ENV] ✓ Agregada ruta de módulos desempaquetados: ${unpackedPath}`);
|
||
}
|
||
}
|
||
|
||
// Cargar koffi primero
|
||
console.log('[KOFFI] Cargando koffi...');
|
||
const koffi = require("koffi");
|
||
console.log('[KOFFI] ✓ Koffi cargado exitosamente');
|
||
|
||
// Cargar node-autoit-koffi
|
||
console.log('[AUTOIT] Cargando node-autoit-koffi...');
|
||
let autoit;
|
||
|
||
if (app.isPackaged) {
|
||
// En aplicación empaquetada, cargar desde ruta desempaquetada
|
||
const autoitModulePath = path.join(process.resourcesPath, 'app.asar.unpacked', 'node_modules', 'node-autoit-koffi');
|
||
if (fs.existsSync(autoitModulePath)) {
|
||
autoit = require(autoitModulePath);
|
||
console.log('[AUTOIT] ✓ node-autoit-koffi cargado desde ruta desempaquetada');
|
||
} else {
|
||
autoit = require("node-autoit-koffi");
|
||
console.log('[AUTOIT] ✓ node-autoit-koffi cargado normalmente');
|
||
}
|
||
} else {
|
||
autoit = require("node-autoit-koffi");
|
||
console.log('[AUTOIT] ✓ node-autoit-koffi cargado (modo desarrollo)');
|
||
}
|
||
|
||
// Configurar la DLL manualmente si es necesario
|
||
if (autoit.setDllPath && typeof autoit.setDllPath === 'function') {
|
||
autoit.setDllPath(autoItDllPath);
|
||
console.log('[AUTOIT] ✓ Ruta DLL configurada manualmente');
|
||
}
|
||
|
||
console.log('[SETUP] ✓ Configuración de AutoIt completada exitosamente');
|
||
|
||
} catch (loadError) {
|
||
console.error(`[DLL] ✗ Error cargando DLL: ${loadError.message}`);
|
||
console.error(`[DLL] Stack trace: ${loadError.stack}`);
|
||
|
||
// Diagnóstico del error
|
||
if (loadError.message.includes('Failed to load shared library')) {
|
||
console.log('[DLL] ℹ Error de dependencias detectado');
|
||
|
||
// Verificar dependencias del sistema
|
||
const dependencyChecks = [
|
||
'C:/Windows/System32/msvcr120.dll',
|
||
'C:/Windows/System32/msvcp120.dll',
|
||
'C:/Windows/System32/vcruntime140.dll',
|
||
'C:/Windows/System32/msvcp140.dll',
|
||
'C:/Windows/System32/vcruntime140_1.dll',
|
||
'C:/Windows/System32/api-ms-win-crt-runtime-l1-1-0.dll'
|
||
];
|
||
|
||
console.log('[DLL] Verificando dependencias del sistema...');
|
||
const missingDeps = [];
|
||
|
||
for (const dep of dependencyChecks) {
|
||
try {
|
||
if (fs.existsSync(dep)) {
|
||
console.log(`[DLL] ✓ Dependencia encontrada: ${dep}`);
|
||
} else {
|
||
console.log(`[DLL] ✗ Dependencia faltante: ${dep}`);
|
||
missingDeps.push(path.basename(dep));
|
||
}
|
||
} catch (e) {
|
||
console.log(`[DLL] ⚠ Error verificando ${dep}: ${e.message}`);
|
||
}
|
||
}
|
||
|
||
let errorMessage = 'No se pudo cargar la librería AutoIt debido a dependencias faltantes.\n\n';
|
||
|
||
if (missingDeps.length > 0) {
|
||
errorMessage += `Dependencias faltantes: ${missingDeps.join(', ')}\n\n`;
|
||
}
|
||
|
||
errorMessage += 'Por favor instala:\n' +
|
||
'1. Visual C++ Redistributable 2015-2022 (x64)\n' +
|
||
'2. Visual C++ Redistributable 2013 (x64)\n' +
|
||
'3. Windows Universal C Runtime\n\n' +
|
||
'Enlaces de descarga:\n' +
|
||
'- https://aka.ms/vs/17/release/vc_redist.x64.exe\n' +
|
||
'- https://www.microsoft.com/download/details.aspx?id=40784\n\n' +
|
||
'Reinicia la aplicación después de la instalación.';
|
||
|
||
dialog.showErrorBox('Error - Dependencias AutoIt', errorMessage);
|
||
}
|
||
|
||
throw loadError;
|
||
}
|
||
|
||
// Resto del código AS400...
|
||
console.log('[SETUP] Configuración de AutoIt completada, continuando con AS400...');
|
||
|
||
} catch (error) {
|
||
console.error(`[ERROR] ✗ Error crítico en AS400 Launcher: ${error.message}`);
|
||
|
||
const { dialog } = require('electron');
|
||
dialog.showErrorBox('Error - AutoIt',
|
||
`Error cargando AutoIt: ${error.message}\n\n` +
|
||
'Por favor reporta este error al desarrollador.'
|
||
);
|
||
|
||
throw error;
|
||
}
|
||
|
||
|
||
|
||
// Verificar las rutas de los ejecutables
|
||
const as400LauncherPath = 'C:/Users/Public/IBM/ClientSolutions/Start_Programs/Windows_i386-32/acslaunch_win-32.exe';
|
||
const as400ConfigPath = 'C:/RpaClaro/AS400.hod';
|
||
|
||
console.log(`[EXEC] Verificando ejecutable AS400: ${as400LauncherPath}`);
|
||
if (!fs.existsSync(as400LauncherPath)) {
|
||
console.log('[EXEC] ✗ ERROR: No se encontró el ejecutable AS400');
|
||
dialog.showErrorBox('Error - AS400',
|
||
`No se encontró el ejecutable AS400 en:\n${as400LauncherPath}\n\n` +
|
||
'Por favor verifica que IBM Client Solutions esté instalado.'
|
||
);
|
||
return;
|
||
}
|
||
|
||
console.log(`[EXEC] Verificando configuración AS400: ${as400ConfigPath}`);
|
||
if (!fs.existsSync(as400ConfigPath)) {
|
||
console.log('[EXEC] ⚠ ADVERTENCIA: No se encontró el archivo de configuración AS400');
|
||
}
|
||
|
||
// Continuar con el resto del código AS400...
|
||
console.log('[EXEC] Ejecutando AS400 Launcher...');
|
||
console.log(`[EXEC] Comando: ${as400LauncherPath} ${as400ConfigPath}`);
|
||
|
||
await autoit.run(`"${as400LauncherPath}" "${as400ConfigPath}"`);
|
||
console.log('[EXEC] ✓ Comando ejecutado, esperando ventana...');
|
||
|
||
console.log('[WAIT] Esperando ventana "Iniciar sesión en IBM i" (timeout: 35s)...');
|
||
const result = await autoit.winWait("Iniciar sesión en IBM i", "", 35);
|
||
|
||
if (result) {
|
||
console.log('[WINDOW] ✓ Ventana "Iniciar sesión en IBM i" detectada');
|
||
|
||
let ventana_error = 0;
|
||
let ventana_contrasena = 0;
|
||
let ventana_mensaje1 = 0;
|
||
let ventana_mensaje2 = 0;
|
||
|
||
console.log('[INPUT] Activando ventana y enviando credenciales...');
|
||
await autoit.winActivate("Iniciar sesión en IBM i");
|
||
await autoit.winSetState("A - ", '', 3);
|
||
|
||
console.log(`[INPUT] Enviando usuario: ${usuario}`);
|
||
await autoit.controlSend("Iniciar sesión en IBM i", '', null, usuario);
|
||
|
||
await autoit.winActivate("Iniciar sesión en IBM i");
|
||
console.log('[INPUT] Enviando TAB');
|
||
await autoit.controlSend("Iniciar sesión en IBM i", '', null, "{TAB}");
|
||
|
||
await autoit.winActivate("Iniciar sesión en IBM i");
|
||
console.log('[INPUT] Enviando contraseña');
|
||
await autoit.controlSend("Iniciar sesión en IBM i", '', null, password);
|
||
|
||
console.log('[INPUT] Enviando ENTER para login');
|
||
await autoit.controlSend("Iniciar sesión en IBM i", '', null, "{ENTER}");
|
||
|
||
console.log('[WAIT] Verificando mensaje de error (timeout: 8s)...');
|
||
ventana_error = await autoit.winWait("Mensaje de error", "", 8);
|
||
|
||
if (ventana_error == 1) {
|
||
console.log('[ERROR] ✗ Apareció mensaje de error, presionando ENTER para continuar');
|
||
await autoit.controlSend("Mensaje de error", '', null, "{ENTER}");
|
||
} else {
|
||
console.log('[ERROR] ✓ No apareció mensaje de error');
|
||
}
|
||
|
||
console.log('[WAIT] Verificando error de credenciales (timeout: 35s)...');
|
||
const ventana_login_error = await autoit.winWait("Iniciar sesión en IBM i", "", 35);
|
||
|
||
if (ventana_login_error) {
|
||
console.log('[LOGIN] ✗ Error de credenciales detectado');
|
||
console.log('[CLEANUP] Cerrando ventanas...');
|
||
await autoit.winClose("Iniciar sesión en IBM i");
|
||
await autoit.winClose("A - ");
|
||
console.log('[DIALOG] Mostrando dialog de error al usuario');
|
||
dialog.showErrorBox('Error', 'Parece que hubo un problema con el ingreso. Por favor, repórtalo al Coordinador');
|
||
} else {
|
||
console.log('[LOGIN] ✓ No hay error de credenciales');
|
||
}
|
||
|
||
console.log('[WAIT] Verificando cambio de contraseña (timeout: 1s)...');
|
||
ventana_contrasena = await autoit.winWait("Cambiar contraseña de IBM i", "", 1);
|
||
|
||
if (ventana_contrasena == 1) {
|
||
console.log('[PASSWORD] ⚠ Apareció solicitud de cambio de contraseña');
|
||
} else {
|
||
console.log('[PASSWORD] ✓ No hay solicitud de cambio de contraseña');
|
||
}
|
||
|
||
console.log('[WAIT] Verificando mensaje de consulta 1 (timeout: 1s)...');
|
||
ventana_mensaje1 = await autoit.winWait("Mensaje de consulta", "", 1);
|
||
|
||
if (ventana_mensaje1 == 1) {
|
||
console.log('[MSG1] ✓ Apareció mensaje de consulta 1, presionando ENTER');
|
||
await autoit.controlSend("Mensaje de consulta", '', null, "{ENTER}");
|
||
} else {
|
||
console.log('[MSG1] ✓ No apareció mensaje de consulta 1');
|
||
}
|
||
|
||
console.log('[WAIT] Verificando mensaje de consulta 2 (timeout: 1s)...');
|
||
ventana_mensaje2 = await autoit.winWait("Mensaje de consulta", "", 1);
|
||
|
||
if (ventana_mensaje2 == 1) {
|
||
console.log('[MSG2] ✓ Apareció mensaje de consulta 2, presionando ENTER');
|
||
await autoit.controlSend("Mensaje de consulta", '', null, "{ENTER}");
|
||
} else {
|
||
console.log('[MSG2] ✓ No apareció mensaje de consulta 2');
|
||
}
|
||
|
||
console.log(`[STATUS] Estado ventana_contrasena: ${ventana_contrasena}`);
|
||
console.log(`[STATUS] Estado ventana_error: ${ventana_error}`);
|
||
|
||
if (ventana_contrasena == 0 && ventana_error == 0) {
|
||
console.log('[SECOND_LOGIN] Condiciones para segundo login cumplidas');
|
||
console.log('[DELAY] Esperando 3 segundos...');
|
||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||
|
||
console.log('[WINDOW] Obteniendo texto de ventana "A - "');
|
||
let segundo_login = await autoit.winGetText('A - ');
|
||
console.log(`[WINDOW] Texto obtenido: ${segundo_login}`);
|
||
|
||
if (segundo_login == 128) {
|
||
console.log('[SECOND_LOGIN] ✓ Se encontró segundo login');
|
||
await autoit.winActivate("A - ");
|
||
console.log('[DELAY] Esperando 2 segundos adicionales...');
|
||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||
|
||
try {
|
||
console.log('[HOTKEY] Ejecutando hotkey Shift+Ctrl+W');
|
||
await autoit.controlSend("A - ", '', null, "+^w");
|
||
console.log('[HOTKEY] ✓ Hotkey ejecutado exitosamente');
|
||
|
||
console.log(`[INPUT] Enviando usuario en segundo login: ${usuario}`);
|
||
await autoit.controlSend("A - ", '', null, usuario);
|
||
|
||
await autoit.winActivate("A - ");
|
||
console.log('[INPUT] Enviando TAB en segundo login');
|
||
await autoit.controlSend("A - ", '', null, "{TAB}");
|
||
|
||
await autoit.winActivate("A - ");
|
||
console.log('[INPUT] Enviando contraseña en segundo login');
|
||
await autoit.controlSend("A - ", '', null, password);
|
||
|
||
console.log('[INPUT] Enviando ENTER para segundo login');
|
||
await autoit.controlSend("A - ", '', null, "{ENTER}");
|
||
|
||
} catch (error) {
|
||
console.log(`[HOTKEY] ✗ Error ejecutando hotkey: ${error}`);
|
||
}
|
||
} else {
|
||
console.log('[SECOND_LOGIN] ✓ No se encontró segundo login necesario');
|
||
}
|
||
}
|
||
|
||
console.log('[AS400] ✓ Proceso AS400 completado exitosamente');
|
||
|
||
} else {
|
||
console.log('[TIMEOUT] ✗ El programa no se abrió dentro del tiempo de espera (35s)');
|
||
}
|
||
|
||
|
||
} catch (error) {
|
||
console.error(`[ERROR] ✗ Error crítico en AS400 Launcher: ${error.message}`);
|
||
console.error(`[ERROR] Stack trace: ${error.stack}`);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
console.log('[ASYNC] Iniciando proceso asíncrono AS400...');
|
||
|
||
// Envolver en try-catch para manejar promesas rechazadas
|
||
runAS400Launcher().catch(error => {
|
||
console.error(`[PROMISE] ✗ Error en promesa AS400: ${error.message}`);
|
||
});
|
||
|
||
console.log('[RETURN] Función rr() completada, retornando "test"');
|
||
return 'test';
|
||
}
|
||
|
||
// Funciones auxiliares (mantener las existentes)
|
||
function verificarYEliminarArchivo(nombreArchivo) {
|
||
console.log(`[FILE] Verificando existencia del archivo: ${nombreArchivo}`);
|
||
|
||
if (fs.existsSync(nombreArchivo)) {
|
||
try {
|
||
// fs.unlinkSync(nombreArchivo); // Descomentar para eliminar el archivo
|
||
console.log(`[FILE] ✓ Archivo encontrado y eliminado: '${nombreArchivo}'`);
|
||
} catch (e) {
|
||
console.log(`[FILE] ✗ Error al eliminar el archivo '${nombreArchivo}': ${e}`);
|
||
}
|
||
} else {
|
||
console.log(`[FILE] ℹ El archivo '${nombreArchivo}' no existe.`);
|
||
}
|
||
}
|
||
|
||
function generarArchivo(nombreArchivo, contenido) {
|
||
console.log(`[FILE] Generando archivo de macro: ${nombreArchivo}`);
|
||
console.log(`[FILE] Tamaño del contenido: ${contenido.length} caracteres`);
|
||
|
||
try {
|
||
fs.writeFileSync(nombreArchivo, contenido, 'utf8');
|
||
console.log(`[FILE] ✓ Archivo generado exitosamente: '${nombreArchivo}'`);
|
||
} catch (e) {
|
||
console.log(`[FILE] ✗ Error al generar el archivo '${nombreArchivo}': ${e}`);
|
||
}
|
||
}
|
||
|
||
function checkSystemArchitecture() {
|
||
const arch = os.arch();
|
||
const platform = os.platform();
|
||
console.log(`[SYSTEM] Arquitectura: ${arch}`);
|
||
console.log(`[SYSTEM] Plataforma: ${platform}`);
|
||
return arch;
|
||
}
|
||
|
||
module.exports = { rr }; |