1057 lines
30 KiB
JavaScript
1057 lines
30 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
/**
|
|
* Generador de Libro de Estudio Offline
|
|
* ======================================
|
|
*
|
|
* Extrae el contenido académico de las páginas HTML descargadas del campus
|
|
* virtual y genera dos formatos de estudio:
|
|
* - LIBRO_DE_ESTUDIO.html → Versión navegable con portada, índice y CSS
|
|
* - LIBRO_DE_ESTUDIO.md → Versión Markdown para leer en cualquier editor
|
|
*
|
|
* Modo de uso:
|
|
* node generar_dashboard.mjs
|
|
*
|
|
* Requisitos:
|
|
* - Haber ejecutado antes download_course.mjs para tener los HTML locales
|
|
* - Funciona 100% offline, solo usa fs.readFileSync
|
|
*/
|
|
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import { fileURLToPath } from "url";
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const DOWNLOADS_DIR = path.join(__dirname, "descargas");
|
|
const SECCIONES_DIR = path.join(DOWNLOADS_DIR, "secciones");
|
|
|
|
// ============================================================
|
|
// DATOS DEL CURSO — Estructura de módulos y secciones
|
|
// ============================================================
|
|
|
|
const MODULOS = [
|
|
{
|
|
titulo: "Módulo 1 — Planificación",
|
|
carpeta: "Modulo_1_Planificacion",
|
|
secciones: [
|
|
{ carpeta: "Planificacion", titulo: "Planificación" },
|
|
{ carpeta: "Preparacion_Atletica", titulo: "Preparación Atlética" },
|
|
{ carpeta: "Explicacion_TP", titulo: "Explicación del Trabajo Práctico" },
|
|
{ carpeta: "Seguimientos_Equipos", titulo: "Seguimientos de Equipos" },
|
|
{
|
|
carpeta: "Analisis_Equipos_1",
|
|
titulo: "Análisis de Equipos de Voleibol 1",
|
|
},
|
|
{
|
|
carpeta: "Analisis_Equipos_2",
|
|
titulo: "Análisis de Equipos de Voleibol 2",
|
|
},
|
|
{
|
|
carpeta: "TP_Final_Unidad",
|
|
titulo: "Trabajo Práctico Final de la Unidad",
|
|
},
|
|
],
|
|
},
|
|
{
|
|
titulo: "Módulo 2 — Entrenamiento",
|
|
carpeta: "Modulo_2_Entrenamiento",
|
|
secciones: [
|
|
{
|
|
carpeta: "Centrales_y_Oponentes",
|
|
titulo: "Entrenamiento de Centrales y Opuestos/as",
|
|
},
|
|
{ carpeta: "Puntas_y_Liberos", titulo: "Puntas y Liberos/as" },
|
|
{
|
|
carpeta: "Entrenamiento_Armadoras",
|
|
titulo: "Entrenamiento de Armadoras",
|
|
},
|
|
{ carpeta: "Explicacion_TP", titulo: "Explicación del Trabajo Práctico" },
|
|
],
|
|
},
|
|
];
|
|
|
|
// ============================================================
|
|
// EXTRACCIÓN DE CONTENIDO DESDE HTML
|
|
// ============================================================
|
|
|
|
/**
|
|
* Lee un archivo HTML y extrae los temas de estudio organizados.
|
|
*
|
|
* Cada fila <tr> dentro de las tablas study-resources representa un tema.
|
|
* Puede contener:
|
|
* - Contenido de estudio en <div class="redactor-usr-input">
|
|
* - Un video Vimeo en <div class="embed-video"> con <iframe>
|
|
* - Un recurso descargable con enlace "Abrir Archivo"
|
|
* - Un enlace externo con "Abrir Enlace"
|
|
*
|
|
* @param {string} filePath - Ruta al archivo pagina.html
|
|
* @returns {Array<{titulo: string, contenido: string, videos: string[], recursos: string[]}>}
|
|
*/
|
|
function extraerTemas(filePath) {
|
|
const temas = [];
|
|
|
|
try {
|
|
if (!fs.existsSync(filePath)) return temas;
|
|
const html = fs.readFileSync(filePath, "utf-8");
|
|
|
|
// Detectar páginas de error
|
|
if (
|
|
html.includes("An Error Occurred") ||
|
|
html.includes("500 Internal Server Error")
|
|
) {
|
|
return temas;
|
|
}
|
|
|
|
// Extraer título de la sección desde el <h1> de la página
|
|
const tituloSeccionMatch = html.match(
|
|
/<div class="pageheader">\s*<h1>([^<]+)<\/h1>/i,
|
|
);
|
|
const tituloSeccion = tituloSeccionMatch
|
|
? tituloSeccionMatch[1].trim()
|
|
: "Materiales de estudio";
|
|
|
|
// Buscar todas las tablas de estudio con un extractor que maneja anidamiento
|
|
const tablas = extraerTablasAnidadas(
|
|
html,
|
|
'table class="table table-bordered study-resources"',
|
|
);
|
|
if (tablas.length === 0) return temas;
|
|
|
|
for (const tabla of tablas) {
|
|
// Extraer tipo de material desde el <th>
|
|
const tipoMatch = tabla.match(/<th[^>]*>([^<]+)<\/th>/i);
|
|
const tipoMaterial = tipoMatch ? tipoMatch[1].trim() : "Material";
|
|
|
|
// Extraer cada fila <tr> manejando anidamiento (pueden tener tablas dentro)
|
|
const filas = extraerFilasAnidadas(tabla);
|
|
|
|
for (const fila of filas) {
|
|
// Saltar filas que solo contienen <th> en el tr directo (encabezados),
|
|
// pero NO filtrar filas cuyo contenido de estudio tenga tablas anidadas con <th>
|
|
const trimmed = fila.trim();
|
|
// Buscar <th> solo dentro del primer nivel del <tr> (antes de cualquier <table> anidada)
|
|
const primerParte = fila.split("<table")[0];
|
|
if (trimmed.startsWith("<tr") && primerParte.includes("<th")) continue;
|
|
// Saltar filas que no tienen <td>
|
|
if (!fila.includes("<td")) continue;
|
|
|
|
const tema = procesarFila(fila, tipoMaterial);
|
|
if (tema) temas.push(tema);
|
|
}
|
|
}
|
|
} catch {
|
|
// Si hay error de lectura, devolver array vacío
|
|
}
|
|
|
|
return temas;
|
|
}
|
|
|
|
/**
|
|
* Extrae bloques <table> del HTML manejando anidamiento correctamente.
|
|
* Busca la cadena de apertura y encuentra su </table> de cierre contando niveles.
|
|
*/
|
|
function extraerTablasAnidadas(html, matchStr) {
|
|
const tablas = [];
|
|
let pos = 0;
|
|
while (true) {
|
|
const start = html.indexOf("<" + matchStr, pos);
|
|
if (start === -1) break;
|
|
// Encontrar el > final de la etiqueta de apertura
|
|
const openEnd = html.indexOf(">", start);
|
|
if (openEnd === -1) break;
|
|
|
|
// Contar anidamiento desde openEnd + 1
|
|
let depth = 1;
|
|
let searchPos = openEnd + 1;
|
|
while (depth > 0 && searchPos < html.length) {
|
|
const nextOpen = html.indexOf("<table", searchPos);
|
|
const nextClose = html.indexOf("</table>", searchPos);
|
|
if (nextClose === -1) break;
|
|
if (nextOpen !== -1 && nextOpen < nextClose) {
|
|
depth++;
|
|
searchPos = nextOpen + 6;
|
|
} else {
|
|
depth--;
|
|
searchPos = nextClose + 8;
|
|
}
|
|
}
|
|
tablas.push(html.substring(start, searchPos));
|
|
pos = searchPos;
|
|
}
|
|
return tablas;
|
|
}
|
|
|
|
/**
|
|
* Extrae filas <tr> de una tabla manejando anidamiento de tablas internas.
|
|
*/
|
|
function extraerFilasAnidadas(tableHTML) {
|
|
const filas = [];
|
|
const tbodyStart = tableHTML.indexOf("<tbody>");
|
|
if (tbodyStart === -1) return filas;
|
|
const tbody = tableHTML.substring(tbodyStart);
|
|
|
|
let pos = 0;
|
|
while (true) {
|
|
const trStart = tbody.indexOf("<tr", pos);
|
|
if (trStart === -1) break;
|
|
|
|
// Encontrar </tr> de cierre contando anidamiento de <tr> y <table>
|
|
let trDepth = 1;
|
|
let tableDepth = 0;
|
|
let searchPos = trStart + 3;
|
|
|
|
while (trDepth > 0 && searchPos < tbody.length) {
|
|
const trOpen = tbody.indexOf("<tr", searchPos);
|
|
const trClose = tbody.indexOf("</tr>", searchPos);
|
|
const tableOpen = tbody.indexOf("<table", searchPos);
|
|
const tableClose = tbody.indexOf("</table>", searchPos);
|
|
|
|
if (trClose === -1) break;
|
|
|
|
// Encontrar el tag relevante más cercano
|
|
let earliestType = null;
|
|
let earliestPos = Infinity;
|
|
|
|
const candidates = [];
|
|
if (trOpen !== -1) candidates.push({ type: "trOpen", pos: trOpen });
|
|
if (trClose !== -1) candidates.push({ type: "trClose", pos: trClose });
|
|
if (tableOpen !== -1)
|
|
candidates.push({ type: "tableOpen", pos: tableOpen });
|
|
if (tableClose !== -1)
|
|
candidates.push({ type: "tableClose", pos: tableClose });
|
|
|
|
for (const c of candidates) {
|
|
if (c.pos < earliestPos) {
|
|
earliestPos = c.pos;
|
|
earliestType = c.type;
|
|
}
|
|
}
|
|
|
|
if (!earliestType) break;
|
|
|
|
switch (earliestType) {
|
|
case "tableOpen":
|
|
tableDepth++;
|
|
searchPos = earliestPos + 6;
|
|
break;
|
|
case "tableClose":
|
|
tableDepth = Math.max(0, tableDepth - 1);
|
|
searchPos = earliestPos + 7;
|
|
break;
|
|
case "trOpen":
|
|
if (tableDepth === 0) trDepth++;
|
|
searchPos = earliestPos + 3;
|
|
break;
|
|
case "trClose":
|
|
if (tableDepth === 0) trDepth--;
|
|
searchPos = earliestPos + 5;
|
|
break;
|
|
}
|
|
}
|
|
|
|
filas.push(tbody.substring(trStart, searchPos));
|
|
pos = searchPos;
|
|
}
|
|
return filas;
|
|
}
|
|
|
|
/**
|
|
* Procesa una fila <tr> individual y extrae título, contenido, videos y recursos.
|
|
*/
|
|
function procesarFila(filaHTML, tipoMaterial) {
|
|
// Extraer título del tema (está dentro de <em>)
|
|
const tituloMatch = filaHTML.match(/<em>([\s\S]*?)<\/em>/i);
|
|
const titulo = tituloMatch
|
|
? limpiarHTML(tituloMatch[1]).trim()
|
|
: "Sin título";
|
|
|
|
// Extraer tipo (Video / Archivo / Enlace)
|
|
const tipoMatch = filaHTML.match(/<strong>(Video|Archivo|Enlace)<\/strong>/i);
|
|
const tipo = tipoMatch ? tipoMatch[1] : "";
|
|
|
|
// Extraer autor
|
|
const autorMatch = filaHTML.match(/por\s+([^•<]+)/i);
|
|
const autor = autorMatch ? autorMatch[1].trim() : "";
|
|
|
|
// Extraer ID de video Vimeo
|
|
const vimeoMatch = filaHTML.match(/player\.vimeo\.com\/video\/(\d+)/i);
|
|
const vimeoID = vimeoMatch ? vimeoMatch[1] : null;
|
|
|
|
// Extraer enlace a recurso (Abrir Archivo o Abrir Enlace)
|
|
const recursoMatch = filaHTML.match(
|
|
/<a[^>]*href="([^"]*)"[^>]*class="btn[^"]*"[^>]*>(Abrir (?:Archivo|Enlace))<\/a>/i,
|
|
);
|
|
const recursoURL = recursoMatch ? recursoMatch[1] : null;
|
|
const recursoTexto = recursoMatch ? recursoMatch[2] : null;
|
|
|
|
// Extraer contenido de estudio real (dentro de redactor-usr-input)
|
|
const contenidoMatch = filaHTML.match(
|
|
/<div class="redactor-usr-input">([\s\S]*?)<\/div>/i,
|
|
);
|
|
let contenidoHTML = contenidoMatch ? contenidoMatch[1].trim() : "";
|
|
|
|
// Limpiar el contenido: eliminar <br> redundantes, normalizar
|
|
contenidoHTML = limpiarContenidoEstudio(contenidoHTML);
|
|
|
|
// Si no hay contenido de estudio ni video ni recurso, no generamos entrada
|
|
if (!contenidoHTML && !vimeoID && !recursoURL) return null;
|
|
|
|
// Id único para anclajes
|
|
const id = titulo
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9áéíóúüñ]+/gi, "-")
|
|
.replace(/-+/g, "-")
|
|
.replace(/^-|-$/g, "");
|
|
|
|
return {
|
|
id,
|
|
titulo,
|
|
tipo,
|
|
autor,
|
|
contenidoHTML,
|
|
vimeoID,
|
|
recursoURL,
|
|
recursoTexto,
|
|
tipoMaterial,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Limpia etiquetas HTML no deseadas del contenido de estudio.
|
|
* Preserva el formato educativo: títulos, párrafos, listas, tablas, citas.
|
|
*/
|
|
function limpiarContenidoEstudio(html) {
|
|
if (!html) return "";
|
|
|
|
let texto = html;
|
|
|
|
// Eliminar estilos inline que no aportan valor educativo
|
|
texto = texto.replace(/\s*style="[^"]*"/gi, "");
|
|
|
|
// Normalizar saltos de línea
|
|
texto = texto.replace(/<br\s*\/?>\s*<br\s*\/?>/gi, "<br>");
|
|
texto = texto.replace(/(<br\s*\/?>\s*){3,}/gi, "<br><br>");
|
|
|
|
// Eliminar nbsp excesivos
|
|
texto = texto.replace(/( \s*){3,}/g, " ");
|
|
|
|
// Eliminar divs vacíos o wrappers que no aportan contenido
|
|
texto = texto.replace(/<div>\s*<\/div>/gi, "");
|
|
|
|
return texto.trim();
|
|
}
|
|
|
|
/**
|
|
* Convierte HTML de estudio a Markdown limpio y legible.
|
|
*/
|
|
function htmlAMarkdown(html) {
|
|
if (!html) return "";
|
|
|
|
let md = html;
|
|
|
|
// ── Títulos ──
|
|
md = md.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, "# $1\n\n");
|
|
md = md.replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, "## $1\n\n");
|
|
md = md.replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, "### $1\n\n");
|
|
md = md.replace(/<h4[^>]*>([\s\S]*?)<\/h4>/gi, "#### $1\n\n");
|
|
md = md.replace(/<h5[^>]*>([\s\S]*?)<\/h5>/gi, "##### $1\n\n");
|
|
|
|
// ── Énfasis ──
|
|
md = md.replace(/<strong>([\s\S]*?)<\/strong>/gi, "**$1**");
|
|
md = md.replace(/<b>([\s\S]*?)<\/b>/gi, "**$1**");
|
|
md = md.replace(/<em>([\s\S]*?)<\/em>/gi, "*$1*");
|
|
md = md.replace(/<i>([\s\S]*?)<\/i>/gi, "*$1*");
|
|
|
|
// ── Párrafos ──
|
|
md = md.replace(/<p[^>]*>([\s\S]*?)<\/p>/gi, "$1\n\n");
|
|
|
|
// ── Listas ──
|
|
md = md.replace(/<ul[^>]*>([\s\S]*?)<\/ul>/gi, "$1\n");
|
|
md = md.replace(/<ol[^>]*>([\s\S]*?)<\/ol>/gi, "$1\n");
|
|
md = md.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, "- $1\n");
|
|
|
|
// ── Blockquote ──
|
|
md = md.replace(/<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi, "> $1\n\n");
|
|
// Limpiar <br> dentro de blockquote en markdown
|
|
md = md.replace(/(^>.*)\n>$/gm, "$1");
|
|
|
|
// ── Tablas ──
|
|
md = md.replace(/<table[^>]*>([\s\S]*?)<\/table>/gi, (_, tablaHTML) => {
|
|
return tablaHTMLAMarkdown(tablaHTML);
|
|
});
|
|
|
|
// ── Código inline ──
|
|
md = md.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi, "`$1`");
|
|
|
|
// ── Línea horizontal ──
|
|
md = md.replace(/<hr[^>]*>/gi, "\n---\n");
|
|
|
|
// ── Entity decoding ──
|
|
md = md.replace(/ /g, " ");
|
|
md = md.replace(/&/g, "&");
|
|
md = md.replace(/</g, "<");
|
|
md = md.replace(/>/g, ">");
|
|
md = md.replace(/"/g, '"');
|
|
md = md.replace(/'/g, "'");
|
|
md = md.replace(/á/g, "á");
|
|
md = md.replace(/é/g, "é");
|
|
md = md.replace(/í/g, "í");
|
|
md = md.replace(/ó/g, "ó");
|
|
md = md.replace(/ú/g, "ú");
|
|
md = md.replace(/ñ/g, "ñ");
|
|
md = md.replace(/Á/g, "Á");
|
|
md = md.replace(/É/g, "É");
|
|
md = md.replace(/Í/g, "Í");
|
|
md = md.replace(/Ó/g, "Ó");
|
|
md = md.replace(/Ú/g, "Ú");
|
|
md = md.replace(/Ñ/g, "Ñ");
|
|
md = md.replace(/ü/g, "ü");
|
|
md = md.replace(/Ü/g, "Ü");
|
|
|
|
// ── Eliminar etiquetas HTML residuales ──
|
|
md = md.replace(/<[^>]*>/g, "");
|
|
|
|
// ── Normalizar espacios y líneas ──
|
|
md = md.replace(/\n{4,}/g, "\n\n\n");
|
|
md = md.replace(/[ \t]+\n/g, "\n");
|
|
|
|
// Limpiar espacios al inicio/fin de cada línea
|
|
md = md
|
|
.split("\n")
|
|
.map((l) => l.trim())
|
|
.join("\n");
|
|
|
|
return md.trim();
|
|
}
|
|
|
|
/**
|
|
* Convierte el HTML interno de una tabla (<thead>/<tbody>/<tr>/<td>/<th>)
|
|
* a formato Markdown de tabla.
|
|
*/
|
|
function tablaHTMLAMarkdown(tablaHTML) {
|
|
const filas = [];
|
|
const rowRegex = /<tr[^>]*>([\s\S]*?)<\/tr>/gi;
|
|
let match;
|
|
let esEncabezado = true;
|
|
|
|
while ((match = rowRegex.exec(tablaHTML)) !== null) {
|
|
const celdas = [];
|
|
const cellRegex = /<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi;
|
|
let cellMatch;
|
|
|
|
while ((cellMatch = cellRegex.exec(match[1])) !== null) {
|
|
let contenido = cellMatch[1]
|
|
.replace(/<br\s*\/?>/gi, " ")
|
|
.replace(/<[^>]+>/g, "")
|
|
.replace(/ /g, " ")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
celdas.push(contenido);
|
|
}
|
|
|
|
if (celdas.length > 0) {
|
|
filas.push({ celdas, esEncabezado });
|
|
esEncabezado = false;
|
|
}
|
|
}
|
|
|
|
if (filas.length === 0) return "";
|
|
|
|
let md = "\n";
|
|
const numCols = Math.max(...filas.map((f) => f.celdas.length));
|
|
|
|
// Usar la primera fila como encabezado (o la marcada como th)
|
|
const header = filas[0];
|
|
// Rellenar si faltan columnas
|
|
while (header.celdas.length < numCols) header.celdas.push("");
|
|
md += "| " + header.celdas.join(" | ") + " |\n";
|
|
md += "| " + header.celdas.map(() => "---").join(" | ") + " |\n";
|
|
|
|
// Las filas restantes son datos
|
|
for (let i = 1; i < filas.length; i++) {
|
|
const fila = filas[i];
|
|
while (fila.celdas.length < numCols) fila.celdas.push("");
|
|
md += "| " + fila.celdas.join(" | ") + " |\n";
|
|
}
|
|
|
|
md += "\n";
|
|
return md;
|
|
}
|
|
|
|
/**
|
|
* Limpia texto HTML simple (sin estructura) para obtener solo el texto plano.
|
|
*/
|
|
function limpiarHTML(html) {
|
|
return html
|
|
.replace(/<[^>]*>/g, "")
|
|
.replace(/ /g, " ")
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, "'")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
// ============================================================
|
|
// GENERACIÓN DE CONTENIDO ESTRUCTURADO
|
|
// ============================================================
|
|
|
|
/**
|
|
* Recorre todos los módulos y secciones, extrae los temas y los organiza.
|
|
*/
|
|
function generarContenido() {
|
|
const libros = [];
|
|
|
|
for (const modulo of MODULOS) {
|
|
const seccionesConContenido = [];
|
|
|
|
for (const seccion of modulo.secciones) {
|
|
const htmlPath = path.join(
|
|
SECCIONES_DIR,
|
|
modulo.carpeta,
|
|
seccion.carpeta,
|
|
"pagina.html",
|
|
);
|
|
const temas = extraerTemas(htmlPath);
|
|
|
|
if (temas.length > 0) {
|
|
seccionesConContenido.push({
|
|
titulo: seccion.titulo,
|
|
temas,
|
|
});
|
|
}
|
|
}
|
|
|
|
if (seccionesConContenido.length > 0) {
|
|
libros.push({
|
|
titulo: modulo.titulo,
|
|
secciones: seccionesConContenido,
|
|
});
|
|
}
|
|
}
|
|
|
|
return libros;
|
|
}
|
|
|
|
// ============================================================
|
|
// GENERACIÓN DE MARKDOWN (.md)
|
|
// ============================================================
|
|
|
|
function generarMarkdown(datos) {
|
|
const ahora = new Date();
|
|
const fecha = ahora.toLocaleDateString("es-AR", {
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric",
|
|
});
|
|
|
|
let totalTemas = 0;
|
|
let md = `# Curso de Entrenador Nacional de Vóley
|
|
## Material de Estudio
|
|
|
|
*Generado el ${fecha}*
|
|
*Contenido extraído del curso online — Versión offline para estudio*
|
|
|
|
---
|
|
|
|
`;
|
|
|
|
for (const modulo of datos) {
|
|
md += `# ${modulo.titulo}\n\n`;
|
|
|
|
for (const seccion of modulo.secciones) {
|
|
md += `## ${seccion.titulo}\n\n`;
|
|
|
|
for (let t = 0; t < seccion.temas.length; t++) {
|
|
const tema = seccion.temas[t];
|
|
totalTemas++;
|
|
|
|
// Número de tema + título
|
|
md += `### ${t + 1}. ${tema.titulo}\n\n`;
|
|
|
|
// Nota de video
|
|
if (tema.vimeoID) {
|
|
md += `📹 *Video disponible — ID: ${tema.vimeoID}*\n\n`;
|
|
}
|
|
|
|
// Contenido de estudio
|
|
if (tema.contenidoHTML) {
|
|
md += htmlAMarkdown(tema.contenidoHTML);
|
|
md += "\n\n";
|
|
}
|
|
|
|
// Recurso descargable
|
|
if (tema.recursoURL) {
|
|
const tipoIcono = tema.recursoTexto === "Abrir Archivo" ? "📄" : "🔗";
|
|
md += `${tipoIcono} **${tema.recursoTexto}:** [${tema.titulo}](${tema.recursoURL})\n\n`;
|
|
}
|
|
|
|
// Separador entre temas
|
|
if (t < seccion.temas.length - 1) {
|
|
md += "---\n\n";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
md += `\n---\n*Fin del material de estudio. ${totalTemas} temas extraídos.*\n`;
|
|
|
|
return md;
|
|
}
|
|
|
|
// ============================================================
|
|
// GENERACIÓN DE HTML (.html)
|
|
// ============================================================
|
|
|
|
function generarHTML(datos) {
|
|
const ahora = new Date();
|
|
const fecha = ahora.toLocaleDateString("es-AR", {
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric",
|
|
});
|
|
|
|
let totalModulos = datos.length;
|
|
let totalSecciones = 0;
|
|
let totalTemas = 0;
|
|
for (const m of datos) {
|
|
totalSecciones += m.secciones.length;
|
|
for (const s of m.secciones) totalTemas += s.temas.length;
|
|
}
|
|
|
|
const css = `
|
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
body {
|
|
font-family: 'Segoe UI', 'Georgia', 'Times New Roman', serif;
|
|
background: #f5f3ef;
|
|
color: #2c2c2c;
|
|
line-height: 1.8;
|
|
font-size: 17px;
|
|
}
|
|
|
|
/* ── PORTADA ── */
|
|
.portada {
|
|
background: linear-gradient(135deg, #0d2b3e 0%, #1a5276 50%, #2980b9 100%);
|
|
color: white;
|
|
padding: 5rem 2rem;
|
|
text-align: center;
|
|
min-height: 70vh;
|
|
display: flex;
|
|
flex-direction: column;
|
|
justify-content: center;
|
|
align-items: center;
|
|
position: relative;
|
|
overflow: hidden;
|
|
}
|
|
.portada::before {
|
|
content: '';
|
|
position: absolute;
|
|
top: -50%;
|
|
left: -50%;
|
|
width: 200%;
|
|
height: 200%;
|
|
background: radial-gradient(circle at 30% 70%, rgba(255,255,255,0.05) 0%, transparent 50%);
|
|
pointer-events: none;
|
|
}
|
|
.portada h1 { font-size: 2.6rem; margin-bottom: 0.6rem; font-weight: 700; letter-spacing: -0.5px; }
|
|
.portada h2 { font-size: 1.3rem; font-weight: 300; opacity: 0.9; margin-bottom: 1.5rem; }
|
|
.portada p { opacity: 0.7; font-size: 0.95rem; }
|
|
.portada .stats {
|
|
margin-top: 2rem;
|
|
display: flex;
|
|
gap: 1.5rem;
|
|
flex-wrap: wrap;
|
|
justify-content: center;
|
|
}
|
|
.portada .stat {
|
|
background: rgba(255,255,255,0.12);
|
|
backdrop-filter: blur(4px);
|
|
padding: 0.6rem 1.4rem;
|
|
border-radius: 8px;
|
|
font-size: 0.9rem;
|
|
border: 1px solid rgba(255,255,255,0.08);
|
|
}
|
|
.portada .icono-grande {
|
|
font-size: 4rem;
|
|
margin-bottom: 1rem;
|
|
opacity: 0.3;
|
|
}
|
|
|
|
/* ── ÍNDICE ── */
|
|
.indice {
|
|
background: white;
|
|
padding: 2.5rem;
|
|
max-width: 820px;
|
|
margin: 0 auto;
|
|
border-bottom: 1px solid #e8e4df;
|
|
}
|
|
.indice h2 {
|
|
color: #0d2b3e;
|
|
margin-bottom: 1.5rem;
|
|
font-size: 1.3rem;
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 0.5rem;
|
|
}
|
|
.indice ul { list-style: none; }
|
|
.indice li { padding: 0.35rem 0; }
|
|
.indice a {
|
|
color: #1a5276;
|
|
text-decoration: none;
|
|
border-bottom: 1px solid transparent;
|
|
transition: border-color 0.2s;
|
|
}
|
|
.indice a:hover { border-bottom-color: #2980b9; }
|
|
.indice .modulo-titulo {
|
|
font-weight: 600;
|
|
font-size: 1.05rem;
|
|
margin-top: 1rem;
|
|
padding-top: 0.8rem;
|
|
border-top: 1px solid #eee;
|
|
color: #0d2b3e;
|
|
}
|
|
.indice .modulo-titulo:first-child { border-top: none; margin-top: 0; padding-top: 0; }
|
|
.indice .seccion-link { padding-left: 1.2rem; font-size: 0.93rem; }
|
|
|
|
/* ── CONTENIDO ── */
|
|
.contenido {
|
|
max-width: 820px;
|
|
margin: 0 auto;
|
|
padding: 2.5rem;
|
|
background: white;
|
|
}
|
|
.contenido h1.modulo-titulo {
|
|
color: #0d2b3e;
|
|
font-size: 2rem;
|
|
border-bottom: 3px solid #2980b9;
|
|
padding-bottom: 0.5rem;
|
|
margin: 3rem 0 1.5rem;
|
|
}
|
|
.contenido h2.seccion-titulo {
|
|
color: #1a5276;
|
|
font-size: 1.5rem;
|
|
margin: 2.5rem 0 1rem;
|
|
border-left: 4px solid #2980b9;
|
|
padding-left: 0.8rem;
|
|
}
|
|
.contenido h3.tema-titulo {
|
|
color: #2c3e50;
|
|
font-size: 1.15rem;
|
|
margin: 1.8rem 0 0.8rem;
|
|
font-weight: 600;
|
|
}
|
|
.contenido h4 {
|
|
color: #34495e;
|
|
font-size: 1.05rem;
|
|
margin: 1.3rem 0 0.6rem;
|
|
font-weight: 600;
|
|
}
|
|
.contenido p { margin: 0.8rem 0; text-align: justify; }
|
|
.contenido ul, .contenido ol { margin: 0.8rem 0; padding-left: 1.8rem; }
|
|
.contenido li { margin: 0.4rem 0; }
|
|
.contenido strong { color: #1a3a4a; font-weight: 600; }
|
|
.contenido hr {
|
|
border: none;
|
|
border-top: 1px solid #e8e4df;
|
|
margin: 1.8rem 0;
|
|
}
|
|
.contenido table {
|
|
width: 100%;
|
|
border-collapse: collapse;
|
|
margin: 1.2rem 0;
|
|
font-size: 0.9rem;
|
|
overflow-x: auto;
|
|
display: block;
|
|
}
|
|
.contenido th, .contenido td {
|
|
border: 1px solid #ddd;
|
|
padding: 0.6rem 0.8rem;
|
|
text-align: left;
|
|
vertical-align: top;
|
|
}
|
|
.contenido th {
|
|
background: #0d2b3e;
|
|
color: white;
|
|
font-weight: 600;
|
|
}
|
|
.contenido tr:nth-child(even) { background: #f8f6f3; }
|
|
.contenido tr:hover { background: #efece7; }
|
|
.contenido blockquote {
|
|
border-left: 4px solid #2980b9;
|
|
margin: 1rem 0;
|
|
padding: 0.8rem 1.2rem;
|
|
background: #f0f5fa;
|
|
color: #2c3e50;
|
|
border-radius: 0 4px 4px 0;
|
|
}
|
|
|
|
/* ── NOTAS ESPECIALES ── */
|
|
.nota-video {
|
|
background: #fef9e7;
|
|
border: 1px solid #f9e79f;
|
|
border-left: 4px solid #f1c40f;
|
|
padding: 0.6rem 1rem;
|
|
margin: 0.8rem 0;
|
|
border-radius: 0 4px 4px 0;
|
|
font-size: 0.9rem;
|
|
color: #7d6608;
|
|
}
|
|
.nota-recurso {
|
|
background: #eaf2f8;
|
|
border: 1px solid #aed6f1;
|
|
border-left: 4px solid #2980b9;
|
|
padding: 0.6rem 1rem;
|
|
margin: 0.8rem 0;
|
|
border-radius: 0 4px 4px 0;
|
|
font-size: 0.9rem;
|
|
}
|
|
.nota-recurso a {
|
|
color: #1a5276;
|
|
font-weight: 600;
|
|
}
|
|
.nota-vacio {
|
|
color: #999;
|
|
font-style: italic;
|
|
font-size: 0.9rem;
|
|
margin: 0.5rem 0;
|
|
}
|
|
.contenido .tema-separador {
|
|
margin: 2rem 0;
|
|
border-top: 1px dashed #ddd;
|
|
}
|
|
|
|
/* ── PIE DE PÁGINA ── */
|
|
.footer {
|
|
text-align: center;
|
|
padding: 3rem 2rem;
|
|
color: #999;
|
|
font-size: 0.85rem;
|
|
max-width: 820px;
|
|
margin: 0 auto;
|
|
border-top: 1px solid #e8e4df;
|
|
background: white;
|
|
}
|
|
|
|
/* ── RESPONSIVE ── */
|
|
@media (max-width: 600px) {
|
|
body { font-size: 15px; }
|
|
.portada { padding: 2rem 1rem; min-height: 50vh; }
|
|
.portada h1 { font-size: 1.6rem; }
|
|
.portada h2 { font-size: 1rem; }
|
|
.contenido { padding: 1rem; }
|
|
.indice { padding: 1.5rem; }
|
|
}
|
|
`;
|
|
|
|
// ─── ÍNDICE ───
|
|
let indiceHTML = '<div class="indice"><h2>📑 Índice de contenidos</h2><ul>';
|
|
for (const modulo of datos) {
|
|
indiceHTML += `<li class="modulo-titulo">${modulo.titulo}</li>`;
|
|
for (const seccion of modulo.secciones) {
|
|
indiceHTML += `<li class="seccion-link"><a href="#sec-${slugify(seccion.titulo)}">${seccion.titulo}</a> (${seccion.temas.length} temas)</li>`;
|
|
}
|
|
}
|
|
indiceHTML += "</ul></div>";
|
|
|
|
// ─── CONTENIDO ───
|
|
let bodyHTML = "";
|
|
for (const modulo of datos) {
|
|
bodyHTML += `<h1 class="modulo-titulo">${modulo.titulo}</h1>\n`;
|
|
|
|
for (const seccion of modulo.secciones) {
|
|
const secID = `sec-${slugify(seccion.titulo)}`;
|
|
bodyHTML += `<h2 class="seccion-titulo" id="${secID}">${seccion.titulo}</h2>\n`;
|
|
|
|
for (let t = 0; t < seccion.temas.length; t++) {
|
|
const tema = seccion.temas[t];
|
|
const temaID = `tema-${slugify(tema.titulo)}-${t}`;
|
|
|
|
bodyHTML += `<h3 class="tema-titulo" id="${temaID}">${t + 1}. ${tema.titulo}</h3>\n`;
|
|
|
|
// Video
|
|
if (tema.vimeoID) {
|
|
bodyHTML += `<div class="nota-video">📹 <strong>Video disponible</strong> — ID: ${tema.vimeoID}</div>\n`;
|
|
}
|
|
|
|
// Contenido de estudio
|
|
if (tema.contenidoHTML) {
|
|
bodyHTML += contenidoEstudioAHTML(tema.contenidoHTML);
|
|
} else if (!tema.vimeoID && !tema.recursoURL) {
|
|
bodyHTML += `<p class="nota-vacio">Sin contenido de estudio adicional.</p>\n`;
|
|
}
|
|
|
|
// Recurso descargable o enlace
|
|
if (tema.recursoURL) {
|
|
const icono = tema.recursoTexto === "Abrir Archivo" ? "📄" : "🔗";
|
|
const etiqueta =
|
|
tema.recursoTexto === "Abrir Archivo" ? "Archivo" : "Enlace";
|
|
bodyHTML += `<div class="nota-recurso">${icono} <strong>${etiqueta}:</strong> <a href="${tema.recursoURL}" target="_blank">${tema.titulo}</a></div>\n`;
|
|
}
|
|
|
|
// Separador entre temas
|
|
if (t < seccion.temas.length - 1) {
|
|
bodyHTML += `<div class="tema-separador"></div>\n`;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return `<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Curso de Vóley — Material de Estudio</title>
|
|
<style>${css}</style>
|
|
</head>
|
|
<body>
|
|
<div class="portada">
|
|
<div class="icono-grande">🏐</div>
|
|
<h1>Curso de Entrenador Nacional de Vóley</h1>
|
|
<h2>Material de Estudio — Versión Offline</h2>
|
|
<p>Contenido extraído del campus virtual</p>
|
|
<div class="stats">
|
|
<div class="stat">📚 ${totalModulos} módulos</div>
|
|
<div class="stat">📂 ${totalSecciones} secciones</div>
|
|
<div class="stat">📖 ${totalTemas} temas</div>
|
|
</div>
|
|
<p style="margin-top: 2rem; opacity: 0.5; font-size: 0.8rem;">Generado el ${fecha}</p>
|
|
</div>
|
|
|
|
${indiceHTML}
|
|
|
|
<div class="contenido">
|
|
${bodyHTML}
|
|
</div>
|
|
|
|
<div class="footer">
|
|
<p>Online Education Center — Material de estudio offline</p>
|
|
<p style="margin-top: 0.3rem; font-size: 0.8rem;">Generado el ${fecha}</p>
|
|
</div>
|
|
</body>
|
|
</html>`;
|
|
}
|
|
|
|
/**
|
|
* Convierte el HTML de contenido de estudio (redactor-usr-input) a HTML limpio
|
|
* manteniendo la estructura semántica (títulos, párrafos, listas, tablas, citas).
|
|
*/
|
|
function contenidoEstudioAHTML(html) {
|
|
if (!html) return "";
|
|
|
|
let out = html;
|
|
|
|
// Procesar títulos
|
|
out = out.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, "<h4>$1</h4>");
|
|
out = out.replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, "<h4>$1</h4>");
|
|
out = out.replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, "<h4>$1</h4>");
|
|
|
|
// Eliminar <br> que son solo espaciado estético (más de 2 seguidos)
|
|
out = out.replace(/(<br\s*\/?>\s*){3,}/gi, "<br><br>");
|
|
|
|
// Asegurar que las tablas tengan bordes visibles
|
|
out = out.replace(/<table/gi, '<table cellspacing="0"');
|
|
|
|
// Eliminar etiquetas vacías que no aportan contenido
|
|
out = out.replace(/<p>\s*<\/p>/gi, "");
|
|
out = out.replace(/<div>\s*<\/div>/gi, "");
|
|
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Convierte un texto en un slug apto para usar como ID HTML.
|
|
*/
|
|
function slugify(texto) {
|
|
return texto
|
|
.toLowerCase()
|
|
.normalize("NFD")
|
|
.replace(/[\u0300-\u036f]/g, "") // eliminar tildes
|
|
.replace(/[^a-z0-9]+/gi, "-")
|
|
.replace(/-+/g, "-")
|
|
.replace(/^-|-$/g, "");
|
|
}
|
|
|
|
// ============================================================
|
|
// EJECUCIÓN PRINCIPAL
|
|
// ============================================================
|
|
|
|
console.log("🏐 Generando libro de estudio...");
|
|
console.log("");
|
|
|
|
const datos = generarContenido();
|
|
|
|
if (datos.length === 0) {
|
|
console.log(
|
|
"⚠ No se encontró contenido de estudio en las páginas descargadas.",
|
|
);
|
|
console.log(
|
|
" Asegurate de haber ejecutado primero: node download_course.mjs",
|
|
);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Resumen de lo extraído
|
|
for (const modulo of datos) {
|
|
console.log(` 📚 ${modulo.titulo}`);
|
|
for (const seccion of modulo.secciones) {
|
|
console.log(` 📂 ${seccion.titulo} (${seccion.temas.length} temas)`);
|
|
for (const tema of seccion.temas) {
|
|
const tieneContenido = tema.contenidoHTML ? "📝" : " ";
|
|
const tieneVideo = tema.vimeoID ? "📹" : " ";
|
|
const tieneRecurso = tema.recursoURL ? "📎" : " ";
|
|
console.log(
|
|
` ${tieneContenido}${tieneVideo}${tieneRecurso} ${tema.titulo}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
console.log("");
|
|
|
|
// Generar Markdown
|
|
console.log("📝 Generando LIBRO_DE_ESTUDIO.md...");
|
|
const md = generarMarkdown(datos);
|
|
const mdPath = path.join(DOWNLOADS_DIR, "LIBRO_DE_ESTUDIO.md");
|
|
fs.writeFileSync(mdPath, md, "utf-8");
|
|
console.log(` ✓ ${mdPath} (${(md.length / 1024).toFixed(0)} KB)`);
|
|
|
|
// Generar HTML
|
|
console.log("🎨 Generando LIBRO_DE_ESTUDIO.html...");
|
|
const html = generarHTML(datos);
|
|
const htmlPath = path.join(DOWNLOADS_DIR, "LIBRO_DE_ESTUDIO.html");
|
|
fs.writeFileSync(htmlPath, html, "utf-8");
|
|
console.log(` ✓ ${htmlPath} (${(html.length / 1024).toFixed(0)} KB)`);
|
|
|
|
// Estadísticas
|
|
let totalPalabras = 0;
|
|
let totalTemas = 0;
|
|
for (const m of datos) {
|
|
for (const s of m.secciones) {
|
|
for (const t of s.temas) {
|
|
if (t.contenidoHTML) {
|
|
totalPalabras += t.contenidoHTML
|
|
.replace(/<[^>]*>/g, "")
|
|
.split(/\s+/).length;
|
|
}
|
|
totalTemas++;
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log("");
|
|
console.log("📊 Estadísticas:");
|
|
console.log(` ${datos.length} módulos`);
|
|
console.log(` ${datos.reduce((s, m) => s + m.secciones.length, 0)} secciones`);
|
|
console.log(` ${totalTemas} temas de estudio`);
|
|
console.log(` ~${(totalPalabras / 1000).toFixed(1)}k palabras de contenido`);
|
|
console.log("");
|
|
console.log("📂 Archivos generados:");
|
|
console.log(` LIBRO_DE_ESTUDIO.md → Para leer en cualquier editor de texto`);
|
|
console.log(
|
|
` LIBRO_DE_ESTUDIO.html → Para leer en el navegador (recomendado)`,
|
|
);
|
|
console.log("");
|
|
console.log("✅ Listo. ¡A estudiar!");
|