moodle-student-bridge 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.es.md +4 -0
- package/README.md +4 -0
- package/docs/CASOS_DE_USO.md +19 -0
- package/docs/ROADMAP.md +1 -1
- package/manifest.json +17 -1
- package/package.json +1 -1
- package/src/index.js +7 -1
- package/src/organizacion.js +273 -0
- package/src/seguridad.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.0 — 2026-11-20
|
|
4
|
+
|
|
5
|
+
Organización. / Organization tools.
|
|
6
|
+
|
|
7
|
+
- `calendario`: día por día con entregas, apertura/cierre de cuestionarios, **clases con asistencia** y
|
|
8
|
+
eventos del curso, de grupo o institucionales; filtros por tipo; exporta `.ics` (avisos 1 día y 3 h
|
|
9
|
+
antes) o da el enlace de **suscripción oficial** de Moodle, que se actualiza solo.
|
|
10
|
+
- `resumen_notas`: la nota total de todas las materias en una llamada, de menor a mayor, con puesto
|
|
11
|
+
si Moodle lo muestra.
|
|
12
|
+
- `trabajos_atrasados`: tareas vencidas que aún se pueden entregar tarde, borradores sin enviar, las
|
|
13
|
+
que ya no se pueden entregar y cuestionarios cerrados sin intento.
|
|
14
|
+
- `ver_conversacion`: conversación completa por id, nombre o "yo", sin marcarla como leída.
|
|
15
|
+
|
|
3
16
|
## 1.2.0 — 2026-11-20
|
|
4
17
|
|
|
5
18
|
Estudiar mejor. / Study tools.
|
package/README.es.md
CHANGED
|
@@ -19,6 +19,8 @@ con su propia cuenta. Funciona con cualquier Moodle que tenga la app móvil habi
|
|
|
19
19
|
|---|---|
|
|
20
20
|
| `resumen_semanal` | Todo lo pendiente y lo nuevo en una sola llamada |
|
|
21
21
|
| `proximos_vencimientos` | Línea de tiempo: lo que vence en los próximos N días (y lo vencido) |
|
|
22
|
+
| `calendario` | Calendario completo día por día: entregas, apertura/cierre de cuestionarios, clases (asistencia) y eventos; exporta .ics o da el enlace de suscripción oficial |
|
|
23
|
+
| `trabajos_atrasados` | Lo vencido: lo que aún puedes entregar tarde, borradores sin enviar y lo que ya se perdió |
|
|
22
24
|
| `listar_cursos` | Cursos en los que estás matriculado |
|
|
23
25
|
| `listar_tareas` | Tareas por curso con fechas |
|
|
24
26
|
| `ver_tarea` | Enunciado, rúbricas, adjuntos, estado de tu entrega y retroalimentación |
|
|
@@ -28,7 +30,9 @@ con su propia cuenta. Funciona con cualquier Moodle que tenga la app móvil habi
|
|
|
28
30
|
| `anuncios` / `ver_discusion` | Avisos de profesores y foros |
|
|
29
31
|
| `notificaciones` | La campana: notas publicadas, retroalimentación, cambios (no las marca como leídas) |
|
|
30
32
|
| `mensajes` | Conversaciones de mensajería |
|
|
33
|
+
| `ver_conversacion` | Lee una conversación completa (nunca la marca como leída) |
|
|
31
34
|
| `calificaciones` | Tu libro de calificaciones por curso |
|
|
35
|
+
| `resumen_notas` | La nota total de todas tus materias en una llamada, de menor a mayor |
|
|
32
36
|
| `revisar_intento` | Revisa un intento **terminado** de un cuestionario: tus respuestas, puntaje y la retroalimentación que el profe permita |
|
|
33
37
|
| `ver_actividad` | Lee una actividad: páginas, libros (por capítulo), carpetas, enlaces, etiquetas y archivos |
|
|
34
38
|
| `novedades` | Qué cambió en las últimas N horas: materiales nuevos o actualizados, tareas, notas, foros |
|
package/README.md
CHANGED
|
@@ -37,6 +37,8 @@ The tool names are in Spanish, but Claude understands requests in any language.
|
|
|
37
37
|
|---|---|
|
|
38
38
|
| `resumen_semanal` | Everything pending and new in one call |
|
|
39
39
|
| `proximos_vencimientos` | Timeline of upcoming (and overdue) deadlines |
|
|
40
|
+
| `calendario` | Full calendar day by day: deadlines, quiz open/close, classes (attendance) and course/site events; .ics export or official subscription link |
|
|
41
|
+
| `trabajos_atrasados` | Overdue work: what you can still submit late, drafts not sent, and what's lost |
|
|
40
42
|
| `listar_cursos` | Courses you're enrolled in |
|
|
41
43
|
| `listar_tareas` | Assignments per course with due dates |
|
|
42
44
|
| `ver_tarea` | Brief, rubrics, attachments, submission status, rules and feedback |
|
|
@@ -46,7 +48,9 @@ The tool names are in Spanish, but Claude understands requests in any language.
|
|
|
46
48
|
| `anuncios` / `ver_discusion` | Teacher announcements and forum discussions |
|
|
47
49
|
| `notificaciones` | The notification bell: new grades, feedback, changes (never marks them as read) |
|
|
48
50
|
| `mensajes` | Messaging conversations |
|
|
51
|
+
| `ver_conversacion` | Read a full messaging conversation (never marks as read) |
|
|
49
52
|
| `calificaciones` | Your gradebook for a course |
|
|
53
|
+
| `resumen_notas` | Total grade of every course in one call, lowest first |
|
|
50
54
|
| `revisar_intento` | Review a finished quiz attempt: your answers, marks and the feedback the teacher allows |
|
|
51
55
|
| `ver_actividad` | Read an activity: pages, books (by chapter), folders, links, labels, files |
|
|
52
56
|
| `novedades` | What changed since N hours ago: new/updated materials, assignments, grades, forums |
|
package/docs/CASOS_DE_USO.md
CHANGED
|
@@ -57,6 +57,23 @@ y tus horas libres, y te arma un horario bloque por bloque.
|
|
|
57
57
|
`novedades` lista los materiales nuevos o actualizados, las tareas modificadas, las notas publicadas
|
|
58
58
|
y los foros con mensajes nuevos, agrupados por curso.
|
|
59
59
|
|
|
60
|
+
### Tu semana en el calendario
|
|
61
|
+
|
|
62
|
+
> **Tú:** Muéstrame mi calendario de la próxima semana, con clases y entregas.
|
|
63
|
+
|
|
64
|
+
> **Tú:** Exporta mis entregas y exámenes a Google Calendar.
|
|
65
|
+
|
|
66
|
+
`calendario` incluye las **clases** (sesiones de asistencia), entregas y cuestionarios. Puede guardar
|
|
67
|
+
un `.ics` con avisos 1 día y 3 h antes, o darte el **enlace de suscripción oficial de Moodle**, que se
|
|
68
|
+
mantiene actualizado solo.
|
|
69
|
+
|
|
70
|
+
### ¿Se me pasó algo?
|
|
71
|
+
|
|
72
|
+
> **Tú:** ¿Qué tengo atrasado? ¿Qué todavía puedo entregar aunque sea tarde?
|
|
73
|
+
|
|
74
|
+
`trabajos_atrasados` separa lo que **aún puedes entregar**, lo que dejaste **en borrador sin enviar**
|
|
75
|
+
y lo que **ya se perdió**.
|
|
76
|
+
|
|
60
77
|
### Lo urgente de hoy
|
|
61
78
|
|
|
62
79
|
> **Tú:** ¿Hay algo que venza en las próximas 24 horas?
|
|
@@ -255,6 +272,8 @@ También puedes **agregar** archivos a los que ya subiste (`modo: agregar`), sie
|
|
|
255
272
|
|
|
256
273
|
> **Tú:** Compara mis notas en todas las materias y dime dónde estoy más flojo.
|
|
257
274
|
|
|
275
|
+
`resumen_notas` trae el total de todas tus materias en una sola llamada, de menor a mayor.
|
|
276
|
+
|
|
258
277
|
> **Tú:** ¿Ya calificaron mi proyecto? ¿Qué retroalimentación me dejó el profe?
|
|
259
278
|
|
|
260
279
|
---
|
package/docs/ROADMAP.md
CHANGED
|
@@ -23,7 +23,7 @@ Las fases van en orden de prioridad.
|
|
|
23
23
|
- Lectura de Excel (`.xlsx`).
|
|
24
24
|
- `buscar`: un tema en los materiales y foros de un curso.
|
|
25
25
|
|
|
26
|
-
## Fase 3 — Organización
|
|
26
|
+
## ✅ Fase 3 — Organización (v1.3)
|
|
27
27
|
|
|
28
28
|
- `calendario`: todos los eventos (también exámenes y clases), con exportación `.ics`.
|
|
29
29
|
- `resumen_notas`: el total de todas las materias en una llamada.
|
package/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"manifest_version": "0.2",
|
|
3
3
|
"name": "moodle-student-bridge",
|
|
4
4
|
"display_name": "Moodle Student Bridge",
|
|
5
|
-
"version": "1.
|
|
5
|
+
"version": "1.3.0",
|
|
6
6
|
"description": "Connect Claude to your Moodle as a student: deadlines, assignments, quizzes, files, announcements and grades.",
|
|
7
7
|
"long_description": "Uses your own Moodle mobile-app token (service moodle_mobile_app), so it works without an admin-issued API token. Read-only by default. Optional write mode (submit/edit/delete assignment submissions, messages, forum posts) always works in two steps: a preview with every check and warning, then an explicit confirmation code.",
|
|
8
8
|
"author": {
|
|
@@ -70,6 +70,22 @@
|
|
|
70
70
|
"name": "proximos_vencimientos",
|
|
71
71
|
"description": "Upcoming and overdue deadlines"
|
|
72
72
|
},
|
|
73
|
+
{
|
|
74
|
+
"name": "calendario",
|
|
75
|
+
"description": "Full calendar day by day: deadlines, quiz open/close, classes (attendance) and course/site events; .ics export or official subscription link"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"name": "resumen_notas",
|
|
79
|
+
"description": "Total grade of every course in one call, lowest first"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"name": "trabajos_atrasados",
|
|
83
|
+
"description": "Overdue work: what you can still submit late, drafts not sent, and what's lost"
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
"name": "ver_conversacion",
|
|
87
|
+
"description": "Read a full messaging conversation (never marks as read)"
|
|
88
|
+
},
|
|
73
89
|
{
|
|
74
90
|
"name": "listar_cursos",
|
|
75
91
|
"description": "Enrolled courses"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "moodle-student-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "MCP bridge for students: connect Claude to your Moodle courses, assignments, quizzes, files and grades using your own mobile-app token — no admin-issued API token needed.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"moodle",
|
package/src/index.js
CHANGED
|
@@ -11,6 +11,7 @@ import { formatearEvento, resumen } from "./resumen.js";
|
|
|
11
11
|
import { analizarTarea, describirEntrega, registrarEscritura } from "./escritura.js";
|
|
12
12
|
import { FUNCIONES_ESCRITURA, FUNCIONES_LECTURA, limpiarSecretos } from "./seguridad.js";
|
|
13
13
|
import { registrarEstudio } from "./estudio.js";
|
|
14
|
+
import { registrarOrganizacion } from "./organizacion.js";
|
|
14
15
|
|
|
15
16
|
cargarEnv();
|
|
16
17
|
|
|
@@ -40,7 +41,7 @@ export function ayudaError(e) {
|
|
|
40
41
|
const limpiar = (t) => limpiarSecretos(t, [process.env.MOODLE_TOKEN]);
|
|
41
42
|
|
|
42
43
|
const server = new McpServer(
|
|
43
|
-
{ name: "moodle-student-bridge", version: "1.
|
|
44
|
+
{ name: "moodle-student-bridge", version: "1.3.0" },
|
|
44
45
|
{
|
|
45
46
|
instructions:
|
|
46
47
|
"Herramientas para el Moodle del estudiante. Las de lectura se pueden usar libremente. " +
|
|
@@ -499,6 +500,9 @@ const FUNCIONALIDADES = [
|
|
|
499
500
|
["Calificaciones", ["gradereport_user_get_grade_items"]],
|
|
500
501
|
["Revisión de cuestionarios", ["mod_quiz_get_attempt_review", "mod_quiz_get_combined_review_options"]],
|
|
501
502
|
["Novedades", ["core_course_get_updates_since"]],
|
|
503
|
+
["Calendario y suscripción", ["core_calendar_get_calendar_events", "core_calendar_get_calendar_export_token"]],
|
|
504
|
+
["Resumen de notas", ["gradereport_overview_get_course_grades"]],
|
|
505
|
+
["Conversaciones completas", ["core_message_get_conversation_messages"]],
|
|
502
506
|
["Foros y anuncios", ["mod_forum_get_forums_by_courses", "mod_forum_get_forum_discussions", "mod_forum_get_discussion_posts"]],
|
|
503
507
|
["Notificaciones y mensajes", ["message_popup_get_popup_notifications", "core_message_get_conversations"]],
|
|
504
508
|
["Participantes y grupos", ["core_enrol_get_enrolled_users", "core_group_get_course_user_groups", "core_group_get_groups_for_selector"]],
|
|
@@ -547,6 +551,8 @@ herramienta(
|
|
|
547
551
|
|
|
548
552
|
// Fase 2: estudiar (solo lectura).
|
|
549
553
|
registrarEstudio({ herramienta, moodle, resolverCurso });
|
|
554
|
+
// Fase 3: organización (solo lectura).
|
|
555
|
+
registrarOrganizacion({ herramienta, moodle, resolverCurso });
|
|
550
556
|
|
|
551
557
|
// Herramientas que modifican Moodle: solo si el usuario las activa explícitamente.
|
|
552
558
|
if (MODO_ESCRITURA) registrarEscritura({ herramienta, moodle, resolverTarea, resolverCurso });
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// Fase 3: organización (solo lectura en Moodle).
|
|
2
|
+
// calendario (+ .ics y suscripción) · resumen_notas · trabajos_atrasados · ver_conversacion
|
|
3
|
+
|
|
4
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { MoodleError, faltan, fecha, hace, htmlATexto, normalizar } from "./moodle.js";
|
|
9
|
+
import { analizarTarea } from "./escritura.js";
|
|
10
|
+
import { nombreEvento } from "./resumen.js";
|
|
11
|
+
|
|
12
|
+
/** "(SOF) FISICA - A" → "FISICA" */
|
|
13
|
+
export const nombreMateria = (c) => (c?.fullname ?? "").replace(/^\([^)]*\)\s*/, "").replace(/\s+-\s+[A-Z0-9]{1,3}$/, "").trim() || c?.shortname || "";
|
|
14
|
+
|
|
15
|
+
const TZ = () => process.env.MOODLE_TZ || undefined;
|
|
16
|
+
|
|
17
|
+
/** Ejecuta fn sobre items con un máximo de `n` en paralelo (para no saturar Moodle). */
|
|
18
|
+
export async function enParalelo(items, n, fn) {
|
|
19
|
+
const salida = new Array(items.length);
|
|
20
|
+
let i = 0;
|
|
21
|
+
await Promise.all(
|
|
22
|
+
Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
23
|
+
while (i < items.length) {
|
|
24
|
+
const k = i++;
|
|
25
|
+
salida[k] = await fn(items[k], k);
|
|
26
|
+
}
|
|
27
|
+
}),
|
|
28
|
+
);
|
|
29
|
+
return salida;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ------------------------------------------------------------------ calendario
|
|
33
|
+
|
|
34
|
+
const TIPO_EVENTO = {
|
|
35
|
+
due: "📝 Entrega",
|
|
36
|
+
gradingdue: "Calificación pendiente",
|
|
37
|
+
open: "🟢 Abre",
|
|
38
|
+
close: "🔴 Cierra",
|
|
39
|
+
attendance: "🏫 Clase (asistencia)",
|
|
40
|
+
course: "📌 Evento del curso",
|
|
41
|
+
site: "🏛 Evento institucional",
|
|
42
|
+
user: "👤 Personal",
|
|
43
|
+
group: "👥 Grupo",
|
|
44
|
+
category: "📌 Evento de la categoría",
|
|
45
|
+
expectcompletionon: "Completar",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export function categoriaEvento(e) {
|
|
49
|
+
if (e.eventtype === "attendance" || e.modulename === "attendance") return "clases";
|
|
50
|
+
if (e.modulename === "quiz") return "examenes";
|
|
51
|
+
if (["due", "gradingdue"].includes(e.eventtype) || e.modulename === "assign") return "entregas";
|
|
52
|
+
return "otros";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const dosDigitos = (n) => String(n).padStart(2, "0");
|
|
56
|
+
const fechaIcs = (ts) => {
|
|
57
|
+
const d = new Date(ts * 1000);
|
|
58
|
+
return `${d.getUTCFullYear()}${dosDigitos(d.getUTCMonth() + 1)}${dosDigitos(d.getUTCDate())}T${dosDigitos(d.getUTCHours())}${dosDigitos(d.getUTCMinutes())}${dosDigitos(d.getUTCSeconds())}Z`;
|
|
59
|
+
};
|
|
60
|
+
const escaparIcs = (s = "") => String(s).replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r?\n/g, "\\n");
|
|
61
|
+
/** Pliega líneas a 75 octetos como pide RFC 5545 (sin partir caracteres UTF-8). */
|
|
62
|
+
function plegar(linea) {
|
|
63
|
+
const partes = [];
|
|
64
|
+
let actual = "";
|
|
65
|
+
for (const ch of linea) {
|
|
66
|
+
if (Buffer.byteLength(actual + ch) > (partes.length ? 74 : 75)) {
|
|
67
|
+
partes.push(actual);
|
|
68
|
+
actual = "";
|
|
69
|
+
}
|
|
70
|
+
actual += ch;
|
|
71
|
+
}
|
|
72
|
+
partes.push(actual);
|
|
73
|
+
return partes.join("\r\n ");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Genera un calendario iCalendar (.ics) con avisos 1 día y 3 h antes de cada entrega/cierre. */
|
|
77
|
+
export function generarIcs(eventos, { host = "moodle", cursos = new Map(), ahora = Date.now() / 1000 } = {}) {
|
|
78
|
+
const l = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//moodle-student-bridge//ES", "CALSCALE:GREGORIAN", "METHOD:PUBLISH", "X-WR-CALNAME:Moodle"];
|
|
79
|
+
for (const e of eventos) {
|
|
80
|
+
const curso = cursos.get(e.courseid);
|
|
81
|
+
const fin = e.timestart + Math.max(e.timeduration || 0, e.timeduration ? 0 : 15 * 60);
|
|
82
|
+
l.push(
|
|
83
|
+
"BEGIN:VEVENT",
|
|
84
|
+
`UID:moodle-${e.id}@${host}`,
|
|
85
|
+
`DTSTAMP:${fechaIcs(ahora)}`,
|
|
86
|
+
`DTSTART:${fechaIcs(e.timestart)}`,
|
|
87
|
+
`DTEND:${fechaIcs(fin)}`,
|
|
88
|
+
plegar(`SUMMARY:${escaparIcs(`${curso ? `[${nombreMateria(curso)}] ` : ""}${nombreEvento(e)}`)}`),
|
|
89
|
+
plegar(`DESCRIPTION:${escaparIcs(htmlATexto(e.description ?? "").slice(0, 1000))}`),
|
|
90
|
+
...(e.url ? [plegar(`URL:${e.url}`)] : []),
|
|
91
|
+
...(e.location ? [plegar(`LOCATION:${escaparIcs(e.location)}`)] : []),
|
|
92
|
+
);
|
|
93
|
+
if (["entregas", "examenes"].includes(categoriaEvento(e)) && e.eventtype !== "open")
|
|
94
|
+
for (const antes of ["-P1D", "-PT3H"]) l.push("BEGIN:VALARM", "ACTION:DISPLAY", `DESCRIPTION:${escaparIcs(nombreEvento(e))}`, `TRIGGER:${antes}`, "END:VALARM");
|
|
95
|
+
l.push("END:VEVENT");
|
|
96
|
+
}
|
|
97
|
+
l.push("END:VCALENDAR");
|
|
98
|
+
return l.join("\r\n") + "\r\n";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ------------------------------------------------------------------ registro
|
|
102
|
+
|
|
103
|
+
export function registrarOrganizacion({ herramienta, moodle, resolverCurso }) {
|
|
104
|
+
herramienta(
|
|
105
|
+
"calendario",
|
|
106
|
+
"Calendario completo: entregas, apertura y cierre de cuestionarios, clases con asistencia y eventos del curso o de la institución, día por día. Puede exportarlo a .ics o darte el enlace de suscripción oficial de Moodle para Google Calendar/Outlook.",
|
|
107
|
+
{
|
|
108
|
+
dias: z.number().int().min(1).max(120).default(14).describe("Días hacia adelante"),
|
|
109
|
+
curso: z.string().optional(),
|
|
110
|
+
tipo: z.enum(["todo", "entregas", "examenes", "clases"]).default("todo"),
|
|
111
|
+
exportar_ics: z.boolean().default(false).describe("Guardar un archivo .ics con estos eventos (con avisos 1 día y 3 h antes)"),
|
|
112
|
+
suscripcion: z.boolean().default(false).describe("Dar el enlace oficial de Moodle para suscribirse (se actualiza solo)"),
|
|
113
|
+
},
|
|
114
|
+
async ({ dias = 14, curso, tipo = "todo", exportar_ics = false, suscripcion = false }) => {
|
|
115
|
+
const m = moodle();
|
|
116
|
+
const c = await resolverCurso(curso);
|
|
117
|
+
const cursos = c ? [c] : await m.cursos();
|
|
118
|
+
const porId = new Map(cursos.map((x) => [x.id, x]));
|
|
119
|
+
const ahora = Math.floor(Date.now() / 1000);
|
|
120
|
+
const r = await m.llamar("core_calendar_get_calendar_events", {
|
|
121
|
+
events: { courseids: cursos.map((x) => x.id) },
|
|
122
|
+
options: { userevents: 1, siteevents: c ? 0 : 1, timestart: ahora - 3600, timeend: ahora + dias * 86400 },
|
|
123
|
+
});
|
|
124
|
+
const eventos = (r.events ?? [])
|
|
125
|
+
.filter((e) => e.visible !== 0 && (!c || e.courseid === c.id || !e.courseid))
|
|
126
|
+
.filter((e) => tipo === "todo" || categoriaEvento(e) === tipo)
|
|
127
|
+
.sort((a, b) => a.timestart - b.timestart);
|
|
128
|
+
|
|
129
|
+
const partes = [`# Calendario · próximos ${dias} días${c ? ` · ${c.fullname}` : ""}${tipo !== "todo" ? ` · ${tipo}` : ""}`];
|
|
130
|
+
if (!eventos.length) partes.push("No hay eventos en ese período.");
|
|
131
|
+
let dia = "";
|
|
132
|
+
for (const e of eventos) {
|
|
133
|
+
const d = new Date(e.timestart * 1000).toLocaleDateString("es", { timeZone: TZ(), weekday: "long", day: "numeric", month: "long" });
|
|
134
|
+
if (d !== dia) partes.push("", `## ${d}`);
|
|
135
|
+
dia = d;
|
|
136
|
+
const hora = new Date(e.timestart * 1000).toLocaleTimeString("es", { timeZone: TZ(), hour: "2-digit", minute: "2-digit" });
|
|
137
|
+
const dur = e.timeduration ? ` (${Math.round(e.timeduration / 60)} min)` : "";
|
|
138
|
+
const tipoTxt = TIPO_EVENTO[e.eventtype] ?? e.eventtype;
|
|
139
|
+
partes.push(`- ${hora}${dur} · ${tipoTxt} · ${nombreEvento(e)}${porId.get(e.courseid) ? ` — ${nombreMateria(porId.get(e.courseid))}` : ""}${e.location ? ` · 📍 ${e.location}` : ""}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (exportar_ics && eventos.length) {
|
|
143
|
+
const base = resolve(process.env.MOODLE_DESCARGAS || join(homedir(), "Downloads", "moodle-student-bridge"));
|
|
144
|
+
await mkdir(base, { recursive: true });
|
|
145
|
+
const ruta = join(base, `calendario-moodle${c ? `-${c.id}` : ""}.ics`);
|
|
146
|
+
await writeFile(ruta, generarIcs(eventos, { host: new URL(m.url).host, cursos: porId }));
|
|
147
|
+
partes.push("", `📅 Exportado: ${ruta}`, "Ábrelo o impórtalo en Google Calendar (Configuración → Importar) u Outlook. Es una copia: no se actualiza sola.");
|
|
148
|
+
}
|
|
149
|
+
if (suscripcion) {
|
|
150
|
+
const { userid } = await m.sitio();
|
|
151
|
+
const t = await m.llamar("core_calendar_get_calendar_export_token", {});
|
|
152
|
+
const url = `${m.url}/calendar/export_execute.php?userid=${userid}&authtoken=${t.token}&preset_what=all&preset_time=recentupcoming`;
|
|
153
|
+
partes.push(
|
|
154
|
+
"",
|
|
155
|
+
"🔗 Enlace de suscripción (oficial de Moodle, se actualiza solo):",
|
|
156
|
+
url,
|
|
157
|
+
"Google Calendar → Otros calendarios → + → Desde URL. ⚠ Este enlace permite ver tu calendario: no lo compartas.",
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
return partes.join("\n");
|
|
161
|
+
},
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
herramienta(
|
|
165
|
+
"resumen_notas",
|
|
166
|
+
"Nota total de TODAS tus materias en una sola llamada, ordenadas de menor a mayor para ver dónde vas más flojo. Para el detalle de una materia usa calificaciones.",
|
|
167
|
+
{},
|
|
168
|
+
async () => {
|
|
169
|
+
const m = moodle();
|
|
170
|
+
const [r, cursos] = await Promise.all([m.llamar("gradereport_overview_get_course_grades", {}), m.cursos()]);
|
|
171
|
+
const porId = new Map(cursos.map((x) => [x.id, x]));
|
|
172
|
+
const filas = (r.grades ?? [])
|
|
173
|
+
.filter((g) => porId.has(g.courseid))
|
|
174
|
+
.map((g) => ({ ...g, curso: porId.get(g.courseid), num: g.rawgrade == null || g.rawgrade === "" ? null : Number(g.rawgrade) }))
|
|
175
|
+
.sort((a, b) => (a.num ?? Infinity) - (b.num ?? Infinity));
|
|
176
|
+
if (!filas.length) return "No hay calificaciones visibles todavía.";
|
|
177
|
+
const conNota = filas.filter((f) => f.num != null);
|
|
178
|
+
const promedio = conNota.length ? conNota.reduce((s, f) => s + f.num, 0) / conNota.length : null;
|
|
179
|
+
return [
|
|
180
|
+
"# Resumen de notas",
|
|
181
|
+
...filas.map((f) => `- ${nombreMateria(f.curso)}: ${f.grade && f.grade !== "-" ? f.grade : "sin nota"}${f.rank ? ` · puesto ${f.rank}` : ""}`),
|
|
182
|
+
"",
|
|
183
|
+
promedio != null ? `Promedio simple de las materias con nota: ${promedio.toFixed(2)}` : "",
|
|
184
|
+
conNota.length ? `Más baja: ${nombreMateria(conNota[0].curso)} (${conNota[0].grade}). Pide "calificaciones" de esa materia para ver el detalle.` : "",
|
|
185
|
+
"Nota: es el total que muestra Moodle en este momento; puede no incluir actividades aún sin calificar.",
|
|
186
|
+
]
|
|
187
|
+
.filter(Boolean)
|
|
188
|
+
.join("\n");
|
|
189
|
+
},
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
herramienta(
|
|
193
|
+
"trabajos_atrasados",
|
|
194
|
+
"Lo vencido sin entregar del período: tareas que AÚN puedes entregar (tarde) y las que ya no (fecha de corte pasada), borradores sin enviar y cuestionarios cerrados sin intento.",
|
|
195
|
+
{
|
|
196
|
+
dias: z.number().int().min(1).max(365).default(120).describe("Mirar hacia atrás N días"),
|
|
197
|
+
curso: z.string().optional(),
|
|
198
|
+
},
|
|
199
|
+
async ({ dias = 120, curso }) => {
|
|
200
|
+
const m = moodle();
|
|
201
|
+
const c = await resolverCurso(curso);
|
|
202
|
+
const ahora = Math.floor(Date.now() / 1000);
|
|
203
|
+
const desde = ahora - dias * 86400;
|
|
204
|
+
const tareas = (await m.tareas(c ? [c.id] : undefined)).filter((t) => t.duedate && t.duedate < ahora && t.duedate >= desde);
|
|
205
|
+
const analisis = await enParalelo(tareas, 6, (t) => analizarTarea(m, t, ahora).catch(() => null));
|
|
206
|
+
const recuperables = [];
|
|
207
|
+
const perdidas = [];
|
|
208
|
+
const borradores = [];
|
|
209
|
+
tareas.forEach((t, i) => {
|
|
210
|
+
const a = analisis[i];
|
|
211
|
+
if (!a || (!a.archivosOn && !a.textoOn)) return; // sin entrega en línea
|
|
212
|
+
if (a.status === "submitted" || a.la.graded || a.la.gradingstatus === "graded") return;
|
|
213
|
+
const linea = `- [${t.id}] ${t.name} — ${nombreMateria({ fullname: t.curso })} · venció ${fecha(t.duedate)} (${hace(t.duedate)})`;
|
|
214
|
+
if (a.status === "draft") borradores.push(`${linea}\n Está en BORRADOR: falta "Enviar para calificar".${a.bloqueos.length ? " ⛔ Ya no se puede enviar." : ""}`);
|
|
215
|
+
else if (!a.bloqueos.length) recuperables.push(`${linea}\n ${t.cutoffdate ? `Puedes entregar hasta el ${fecha(t.cutoffdate)} (${faltan(t.cutoffdate)})` : "Moodle todavía acepta la entrega"} · quedará como tardía`);
|
|
216
|
+
else perdidas.push(`${linea}\n ${a.bloqueos[0]}`);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
const qs = (await m.cuestionarios(c ? [c.id] : undefined)).filter((q) => q.timeclose && q.timeclose < ahora && q.timeclose >= desde);
|
|
220
|
+
const estados = await enParalelo(qs, 6, (q) => m.estadoCuestionario(q.id));
|
|
221
|
+
const sinIntento = qs.filter((q, i) => estados[i].intentos && !estados[i].intentos.some((x) => x.state === "finished"));
|
|
222
|
+
|
|
223
|
+
const total = recuperables.length + perdidas.length + borradores.length + sinIntento.length;
|
|
224
|
+
if (!total) return `🎉 No tienes trabajos atrasados en los últimos ${dias} días (revisé ${tareas.length} tareas y ${qs.length} cuestionarios).`;
|
|
225
|
+
return [
|
|
226
|
+
`# Trabajos atrasados · últimos ${dias} días`,
|
|
227
|
+
...(recuperables.length ? ["", `## ✅ Aún puedes entregarlos (${recuperables.length})`, ...recuperables] : []),
|
|
228
|
+
...(borradores.length ? ["", `## ⚠ En borrador sin enviar (${borradores.length})`, ...borradores] : []),
|
|
229
|
+
...(perdidas.length ? ["", `## ⛔ Ya no se pueden entregar (${perdidas.length})`, ...perdidas] : []),
|
|
230
|
+
...(sinIntento.length ? ["", `## ⛔ Cuestionarios cerrados sin intento (${sinIntento.length})`, ...sinIntento.map((q) => `- ${q.name} — ${nombreMateria({ fullname: q.curso })} · cerró ${fecha(q.timeclose)}`)] : []),
|
|
231
|
+
"",
|
|
232
|
+
`Revisé ${tareas.length} tareas y ${qs.length} cuestionarios. Las tareas sin entrega en línea no se cuentan.`,
|
|
233
|
+
].join("\n");
|
|
234
|
+
},
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
herramienta(
|
|
238
|
+
"ver_conversacion",
|
|
239
|
+
"Lee una conversación de mensajería completa (no solo el último mensaje). Por id de conversación, nombre de la persona o 'yo' para tus notas personales. No marca los mensajes como leídos.",
|
|
240
|
+
{
|
|
241
|
+
conversacion: z.string().describe("Id de conversación, parte del nombre de la persona o 'yo'"),
|
|
242
|
+
limite: z.number().int().min(1).max(100).default(30),
|
|
243
|
+
},
|
|
244
|
+
async ({ conversacion, limite = 30 }) => {
|
|
245
|
+
const m = moodle();
|
|
246
|
+
const { userid } = await m.sitio();
|
|
247
|
+
const q = String(conversacion).trim();
|
|
248
|
+
let id;
|
|
249
|
+
let titulo;
|
|
250
|
+
if (/^(yo|mi|mí|notas|self)$/i.test(q)) {
|
|
251
|
+
id = (await m.llamar("core_message_get_self_conversation", { userid })).id;
|
|
252
|
+
titulo = "Tus notas personales";
|
|
253
|
+
} else {
|
|
254
|
+
const convs = await m.conversaciones(50);
|
|
255
|
+
const nombreDe = (cv) => cv.name || cv.members.filter((x) => x.id !== userid).map((x) => x.fullname).join(", ");
|
|
256
|
+
let hallados = /^\d+$/.test(q) ? convs.filter((cv) => cv.id === Number(q)) : [];
|
|
257
|
+
if (!hallados.length) hallados = convs.filter((cv) => normalizar(nombreDe(cv)).includes(normalizar(q)));
|
|
258
|
+
if (!hallados.length) throw new MoodleError(`No encontré una conversación con "${q}". Usa mensajes para ver la lista.`);
|
|
259
|
+
if (hallados.length > 1) throw new MoodleError(`"${q}" coincide con varias:\n${hallados.map((cv) => `- [${cv.id}] ${nombreDe(cv)}`).join("\n")}`);
|
|
260
|
+
id = hallados[0].id;
|
|
261
|
+
titulo = nombreDe(hallados[0]) || `Conversación ${id}`;
|
|
262
|
+
}
|
|
263
|
+
const r = await m.llamar("core_message_get_conversation_messages", { currentuserid: userid, convid: id, newest: 1, limitnum: limite });
|
|
264
|
+
const nombres = new Map((r.members ?? []).map((x) => [x.id, x.fullname]));
|
|
265
|
+
const msgs = [...(r.messages ?? [])].reverse();
|
|
266
|
+
if (!msgs.length) return `# ${titulo}\n(sin mensajes)`;
|
|
267
|
+
return [
|
|
268
|
+
`# ${titulo} · últimos ${msgs.length} mensajes`,
|
|
269
|
+
...msgs.map((x) => `\n**${x.useridfrom === userid ? "Tú" : nombres.get(x.useridfrom) ?? `usuario ${x.useridfrom}`}** · ${fecha(x.timecreated)}\n${htmlATexto(x.text)}`),
|
|
270
|
+
].join("\n");
|
|
271
|
+
},
|
|
272
|
+
);
|
|
273
|
+
}
|
package/src/seguridad.js
CHANGED
|
@@ -37,6 +37,11 @@ export const FUNCIONES_LECTURA = new Set([
|
|
|
37
37
|
"mod_quiz_get_attempt_review", // solo intentos ya terminados (se comprueba antes)
|
|
38
38
|
"mod_quiz_get_combined_review_options",
|
|
39
39
|
"core_course_get_updates_since",
|
|
40
|
+
// Fase 3
|
|
41
|
+
"core_calendar_get_calendar_events",
|
|
42
|
+
"core_calendar_get_calendar_export_token",
|
|
43
|
+
"gradereport_overview_get_course_grades",
|
|
44
|
+
"core_message_get_conversation_messages", // no marca como leído
|
|
40
45
|
]);
|
|
41
46
|
|
|
42
47
|
/** Funciones que modifican Moodle: solo con el modo escritura activado. */
|