|
|
|
@@ -1,5 +1,5 @@
|
|
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
|
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
|
|
|
|
import { CapacitorHttp, CapacitorCookies, HttpResponse } from '@capacitor/core';
|
|
|
|
|
import { Filesystem, Directory } from '@capacitor/filesystem';
|
|
|
|
|
import { FileOpener } from '@capacitor-community/file-opener';
|
|
|
|
|
import { AuthService } from './auth.service';
|
|
|
|
@@ -11,16 +11,16 @@ export class SiuService {
|
|
|
|
|
|
|
|
|
|
async getAcademicHistory(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
|
|
|
|
try {
|
|
|
|
|
await this.authenticateSiu(dni, pass);
|
|
|
|
|
await this.selectCareer(carreraId);
|
|
|
|
|
const authCookies = await this.authenticateSiu(dni, pass);
|
|
|
|
|
const sessionCookies = await this.selectCareer(carreraId, authCookies);
|
|
|
|
|
|
|
|
|
|
// 3. OBTENER PLAN DE ESTUDIO
|
|
|
|
|
const resPlan: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/plan_estudio`,
|
|
|
|
|
});
|
|
|
|
|
const { html: rawHtml } = await this.getHtml(`${this.BASE_URL}/plan_estudio`, sessionCookies);
|
|
|
|
|
|
|
|
|
|
if (!rawHtml) {
|
|
|
|
|
throw new Error('No se recibió contenido del plan de estudios.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 4. PARSEO DEL JSON EMBEBIDO
|
|
|
|
|
const rawHtml = resPlan.data;
|
|
|
|
|
const regex = /on_arrival\((\{.*?"id":"info_plan".*?\})\);/s;
|
|
|
|
|
const match = rawHtml.match(regex);
|
|
|
|
|
|
|
|
|
@@ -30,6 +30,10 @@ export class SiuService {
|
|
|
|
|
return this.parseHtmlSubjects(contentHtml);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (rawHtml.includes('acceso?auth=form') || rawHtml.includes('id="login"')) {
|
|
|
|
|
throw new Error('La sesión de SIU Guaraní no se pudo autenticar o expiró.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new Error('No se encontró el bloque de materias');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error SIU Academic History:', error);
|
|
|
|
@@ -39,15 +43,13 @@ export class SiuService {
|
|
|
|
|
|
|
|
|
|
async getInscripcionesActivas(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
|
|
|
|
try {
|
|
|
|
|
await this.authenticateSiu(dni, pass);
|
|
|
|
|
await this.selectCareer(carreraId);
|
|
|
|
|
const authCookies = await this.authenticateSiu(dni, pass);
|
|
|
|
|
const sessionCookies = await this.selectCareer(carreraId, authCookies);
|
|
|
|
|
|
|
|
|
|
// OBTENER PÁGINA DE CURSADA
|
|
|
|
|
const resCursada: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/cursada`,
|
|
|
|
|
});
|
|
|
|
|
const { html: rawHtml } = await this.getHtml(`${this.BASE_URL}/cursada`, sessionCookies);
|
|
|
|
|
|
|
|
|
|
const rawHtml = resCursada.data;
|
|
|
|
|
if (!rawHtml) return [];
|
|
|
|
|
|
|
|
|
|
// 1. Extraer directamente de "notificaciones" donde SIU provee el array JSON "asignaciones"
|
|
|
|
|
const regexNotif = /on_arrival\((\{.*?"id":"notificaciones".*?\})\);/s;
|
|
|
|
@@ -86,25 +88,110 @@ export class SiuService {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async authenticateSiu(dni: string, pass: string): Promise<void> {
|
|
|
|
|
private async authenticateSiu(dni: string, pass: string): Promise<string> {
|
|
|
|
|
console.log('Autenticando en SIU...');
|
|
|
|
|
const loginData = `usuario=${dni}&password=${pass}&login=Ingresar`;
|
|
|
|
|
await CapacitorHttp.post({
|
|
|
|
|
const loginData = `usuario=${encodeURIComponent(dni)}&password=${encodeURIComponent(pass)}&login=Ingresar`;
|
|
|
|
|
const headers = this.getCommonHeaders();
|
|
|
|
|
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
|
|
|
|
|
|
|
|
const resLogin: HttpResponse = await CapacitorHttp.post({
|
|
|
|
|
url: `${this.BASE_URL}/acceso?auth=form`,
|
|
|
|
|
data: loginData,
|
|
|
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
|
|
|
|
|
headers
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
let cookies = this.extractCookies(resLogin.headers);
|
|
|
|
|
const stored = await this.getStoredCookies();
|
|
|
|
|
cookies = this.mergeCookieStrings(cookies, stored);
|
|
|
|
|
|
|
|
|
|
const dataStr = this.decodeResponseData(resLogin.data);
|
|
|
|
|
|
|
|
|
|
if (dataStr && (dataStr.includes('El usuario o la contraseña no son correctos') || dataStr.includes('error-login') || dataStr.includes('login_error'))) {
|
|
|
|
|
throw new Error('DNI o Contraseña incorrectos en SIU Guaraní.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return cookies;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async selectCareer(carreraId: string): Promise<void> {
|
|
|
|
|
private async selectCareer(carreraId: string, currentCookies: string): Promise<string> {
|
|
|
|
|
console.log('Seleccionando carrera:', carreraId);
|
|
|
|
|
await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/acceso/cambiar_carrera?id=${carreraId}&op=inicio_alumno`,
|
|
|
|
|
});
|
|
|
|
|
// Hit inicio_alumno to ensure context is established
|
|
|
|
|
await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/inicio_alumno`,
|
|
|
|
|
const resCambio = await this.getHtml(`${this.BASE_URL}/acceso/cambiar_carrera?id=${carreraId}&op=inicio_alumno`, currentCookies);
|
|
|
|
|
const resInicio = await this.getHtml(`${this.BASE_URL}/inicio_alumno`, resCambio.cookies);
|
|
|
|
|
return resInicio.cookies;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async getHtml(url: string, cookies: string): Promise<{ html: string; cookies: string }> {
|
|
|
|
|
let updatedCookies = cookies;
|
|
|
|
|
const res: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url,
|
|
|
|
|
headers: this.getCommonHeaders(updatedCookies)
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
updatedCookies = this.mergeCookies(updatedCookies, res.headers);
|
|
|
|
|
const stored = await this.getStoredCookies();
|
|
|
|
|
updatedCookies = this.mergeCookieStrings(updatedCookies, stored);
|
|
|
|
|
|
|
|
|
|
let html = this.decodeResponseData(res.data);
|
|
|
|
|
|
|
|
|
|
// Fallback: si html es nulo/vacío por codificación no-UTF8 (ej. ISO-8859-1 en SIU), solicitar arraybuffer y decodificar
|
|
|
|
|
if (!html) {
|
|
|
|
|
console.log(`Reintentando ${url} con arraybuffer para decodificación ISO-8859-1...`);
|
|
|
|
|
const resBuffer: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url,
|
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
|
headers: this.getCommonHeaders(updatedCookies)
|
|
|
|
|
});
|
|
|
|
|
updatedCookies = this.mergeCookies(updatedCookies, resBuffer.headers);
|
|
|
|
|
html = this.decodeBase64Response(resBuffer.data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { html, cookies: updatedCookies };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private decodeResponseData(data: any): string {
|
|
|
|
|
if (typeof data === 'string') {
|
|
|
|
|
return data;
|
|
|
|
|
}
|
|
|
|
|
if (data && typeof data === 'object') {
|
|
|
|
|
return JSON.stringify(data);
|
|
|
|
|
}
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private decodeBase64Response(base64: string): string {
|
|
|
|
|
if (!base64 || typeof base64 !== 'string') return '';
|
|
|
|
|
try {
|
|
|
|
|
const binaryString = window.atob(base64);
|
|
|
|
|
const bytes = new Uint8Array(binaryString.length);
|
|
|
|
|
for (let i = 0; i < binaryString.length; i++) {
|
|
|
|
|
bytes[i] = binaryString.charCodeAt(i);
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
|
|
|
|
|
return utf8Decoder.decode(bytes);
|
|
|
|
|
} catch {
|
|
|
|
|
const latinDecoder = new TextDecoder('iso-8859-1');
|
|
|
|
|
return latinDecoder.decode(bytes);
|
|
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error('Error decoding base64 response:', e);
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async getStoredCookies(): Promise<string> {
|
|
|
|
|
try {
|
|
|
|
|
const cookieMap = await CapacitorCookies.getCookies({ url: this.BASE_URL });
|
|
|
|
|
if (cookieMap && typeof cookieMap === 'object') {
|
|
|
|
|
return Object.entries(cookieMap)
|
|
|
|
|
.filter(([k, v]) => k && v)
|
|
|
|
|
.map(([k, v]) => `${k}=${v}`)
|
|
|
|
|
.join('; ');
|
|
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// CapacitorCookies can fail gracefully without breaking flow
|
|
|
|
|
}
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private extractTobaContent(html: string, pageletId: string = 'pagelet'): string {
|
|
|
|
@@ -132,34 +219,30 @@ export class SiuService {
|
|
|
|
|
async downloadCertificate(dni: string, pass: string): Promise<{ base64: string, filename: string }> {
|
|
|
|
|
console.log('Iniciando descarga de certificado para:', dni);
|
|
|
|
|
try {
|
|
|
|
|
await this.authenticateSiu(dni, pass);
|
|
|
|
|
await this.selectCareer('30');
|
|
|
|
|
const authCookies = await this.authenticateSiu(dni, pass);
|
|
|
|
|
const sessionCookies = await this.selectCareer('30', authCookies);
|
|
|
|
|
console.log('Login y selección de carrera (ID 30) listos');
|
|
|
|
|
|
|
|
|
|
// 1. VALIDAR SI EXISTE UNO VIGENTE (< 30 DÍAS)
|
|
|
|
|
const resSolicitudes: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/solicitudes`,
|
|
|
|
|
});
|
|
|
|
|
const { html: rawHtmlSolicitudes, cookies: solicitCookies } = await this.getHtml(`${this.BASE_URL}/solicitudes`, sessionCookies);
|
|
|
|
|
console.log('Página de solicitudes obtenida');
|
|
|
|
|
|
|
|
|
|
const contentHtmlSolicitudes = this.extractTobaContent(resSolicitudes.data, 'pagelet');
|
|
|
|
|
const contentHtmlSolicitudes = this.extractTobaContent(rawHtmlSolicitudes, 'pagelet');
|
|
|
|
|
if (contentHtmlSolicitudes) {
|
|
|
|
|
const existingCert = this.findValidCertificate(contentHtmlSolicitudes);
|
|
|
|
|
if (existingCert) {
|
|
|
|
|
console.log('Certificado vigente encontrado:', existingCert.filename);
|
|
|
|
|
return await this.downloadFile(existingCert.url, existingCert.filename);
|
|
|
|
|
return await this.downloadFile(existingCert.url, existingCert.filename, solicitCookies);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 2. GENERAR NUEVA SOLICITUD (HEADLESS)
|
|
|
|
|
console.log('No hay certificado vigente o no se pudo leer la tabla. Intentando generar uno nuevo...');
|
|
|
|
|
const resGestion: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url: `${this.BASE_URL}/solicitudes/solicitud_gestion`,
|
|
|
|
|
});
|
|
|
|
|
const { html: rawHtmlGestion, cookies: gestionCookies } = await this.getHtml(`${this.BASE_URL}/solicitudes/solicitud_gestion`, solicitCookies);
|
|
|
|
|
|
|
|
|
|
const contentHtmlGestion = this.extractTobaContent(resGestion.data, 'pagelet');
|
|
|
|
|
const contentHtmlGestion = this.extractTobaContent(rawHtmlGestion, 'pagelet');
|
|
|
|
|
if (!contentHtmlGestion) {
|
|
|
|
|
console.error('HTML completo de gestión no contiene on_arrival de pagelet. Muestra:', resGestion.data.substring(0, 1000));
|
|
|
|
|
console.error('HTML completo de gestión no contiene on_arrival de pagelet. Muestra:', rawHtmlGestion.substring(0, 1000));
|
|
|
|
|
throw new Error('No se pudo localizar el generador (content missing)');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@@ -186,7 +269,7 @@ export class SiuService {
|
|
|
|
|
: `${iframeSrc}?toba_ei_notificar=imprimir`;
|
|
|
|
|
|
|
|
|
|
console.log('Solicitando generación de PDF:', printUrl);
|
|
|
|
|
return await this.downloadFile(printUrl, `Certificado_Alumno_Regular_${new Date().getTime()}.pdf`);
|
|
|
|
|
return await this.downloadFile(printUrl, `Certificado_Alumno_Regular_${new Date().getTime()}.pdf`, gestionCookies);
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error detallado en SIU Certificate:', error);
|
|
|
|
@@ -237,13 +320,14 @@ export class SiuService {
|
|
|
|
|
return days < 30;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async downloadFile(url: string, filename: string): Promise<{ base64: string, filename: string }> {
|
|
|
|
|
private async downloadFile(url: string, filename: string, cookies?: string): Promise<{ base64: string, filename: string }> {
|
|
|
|
|
// Si la URL es relativa, completarla
|
|
|
|
|
const fullUrl = url.startsWith('http') ? url : `${this.BASE_URL}/${url.startsWith('/') ? url.substring(1) : url}`;
|
|
|
|
|
|
|
|
|
|
const response: HttpResponse = await CapacitorHttp.get({
|
|
|
|
|
url: fullUrl,
|
|
|
|
|
responseType: 'blob'
|
|
|
|
|
responseType: 'blob',
|
|
|
|
|
headers: this.getCommonHeaders(cookies)
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
@@ -252,6 +336,66 @@ export class SiuService {
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private getCommonHeaders(cookies?: string): Record<string, string> {
|
|
|
|
|
const headers: Record<string, string> = {
|
|
|
|
|
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
|
|
|
|
|
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
|
|
|
'Accept-Language': 'es-AR,es;q=0.9'
|
|
|
|
|
};
|
|
|
|
|
if (cookies) {
|
|
|
|
|
headers['Cookie'] = cookies;
|
|
|
|
|
}
|
|
|
|
|
return headers;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private extractCookies(headers: Record<string, string> | undefined): string {
|
|
|
|
|
return this.mergeCookies('', headers);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private mergeCookies(existingCookies: string, newHeaders: Record<string, string> | undefined): string {
|
|
|
|
|
if (!newHeaders) return existingCookies;
|
|
|
|
|
const rawSetCookie: string = newHeaders['set-cookie'] || newHeaders['Set-Cookie'] || '';
|
|
|
|
|
if (!rawSetCookie) return existingCookies;
|
|
|
|
|
|
|
|
|
|
const cookieMap = new Map<string, string>();
|
|
|
|
|
if (existingCookies) {
|
|
|
|
|
existingCookies.split(';').forEach(c => {
|
|
|
|
|
const [k, ...v] = c.trim().split('=');
|
|
|
|
|
if (k) cookieMap.set(k.trim(), v.join('='));
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const newCookies = rawSetCookie.split(/,(?=[^ ])/);
|
|
|
|
|
newCookies.forEach(c => {
|
|
|
|
|
const cookiePart = c.trim().split(';')[0];
|
|
|
|
|
const [k, ...v] = cookiePart.split('=');
|
|
|
|
|
if (k && v.length > 0) {
|
|
|
|
|
cookieMap.set(k.trim(), v.join('='));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return Array.from(cookieMap.entries())
|
|
|
|
|
.map(([k, v]) => `${k}=${v}`)
|
|
|
|
|
.join('; ');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private mergeCookieStrings(cookies1: string, cookies2: string): string {
|
|
|
|
|
if (!cookies1) return cookies2 || '';
|
|
|
|
|
if (!cookies2) return cookies1 || '';
|
|
|
|
|
const cookieMap = new Map<string, string>();
|
|
|
|
|
cookies1.split(';').forEach(c => {
|
|
|
|
|
const [k, ...v] = c.trim().split('=');
|
|
|
|
|
if (k) cookieMap.set(k.trim(), v.join('='));
|
|
|
|
|
});
|
|
|
|
|
cookies2.split(';').forEach(c => {
|
|
|
|
|
const [k, ...v] = c.trim().split('=');
|
|
|
|
|
if (k) cookieMap.set(k.trim(), v.join('='));
|
|
|
|
|
});
|
|
|
|
|
return Array.from(cookieMap.entries())
|
|
|
|
|
.map(([k, v]) => `${k}=${v}`)
|
|
|
|
|
.join('; ');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async saveAndOpenFile(base64Data: string, filename: string): Promise<void> {
|
|
|
|
|
try {
|
|
|
|
|
const savedFile = await Filesystem.writeFile({
|
|
|
|
|