utn-mcp 0.2.1 → 0.6.7

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/README.md CHANGED
@@ -6,6 +6,10 @@ Este es el Model Context Protocol server NO OFICIAL de la UTN. Con él podrás p
6
6
  - *"¿Qué avisó la profesora de Física esta semana?"*
7
7
  - *"Resumime la guía de la unidad 3 de Sistemas Operativos."*
8
8
  - *"Pasame el link para bajar el apunte de calorimetría."*
9
+ - *"¿Qué nota me pusieron en el TP1 y qué me corrigieron?"*
10
+ - *"Preguntá en el foro de consultas si el parcial incluye la unidad 4."*
11
+ - *"Anotame en el grupo 6."*
12
+ - *"Agendame el recuperatorio del 14 a las 18."*
9
13
 
10
14
  El agente recorre el aula como lo harías vos: entra al curso, mira los foros y abre los archivos que hagan falta.
11
15
 
@@ -16,6 +20,14 @@ El agente recorre el aula como lo harías vos: entra al curso, mira los foros y
16
20
  | `aula_open` | Entra a un curso, un módulo, un foro o una discusión. Cada respuesta trae las direcciones de lo que hay adentro y de un nivel más arriba, así el agente navega sin perderse. |
17
21
  | `aula_read_file` | Lee un archivo del aula, por partes cuando es largo. |
18
22
  | `aula_get_site_info` | Datos de tu usuario en el aula virtual. |
23
+ | `aula_forum_post` | Abre un hilo en un foro o responde en una discusión. |
24
+ | `aula_forum_edit_post` | Edita una publicación tuya. |
25
+ | `aula_forum_delete_post` | Borra una publicación tuya. |
26
+ | `aula_choice_answer` | Responde una elección o te anota en un grupo. |
27
+ | `aula_send_message` | Manda un mensaje privado a un docente o compañero. |
28
+ | `aula_calendar_add_event` | Agrega un recordatorio a tu calendario del aula. |
29
+
30
+ Al abrir una tarea, `aula_open` muestra si la entregaste, cuándo vence y la devolución con la nota. Las tools que escriben le piden al agente que te muestre lo que va a hacer y espere tu confirmación.
19
31
 
20
32
  ### Archivos que puede leer
21
33
  - **PDF**: el texto, página por página. Los **escaneados** se mandan como imagen de cada página, y el agente los lee igual.
@@ -1,4 +1,4 @@
1
- import { callWs } from "./moodle-api.js";
1
+ import { callWs, MoodleError } from "./moodle-api.js";
2
2
  export function getSiteInfo(session) {
3
3
  return callWs(session, "core_webservice_get_site_info");
4
4
  }
@@ -20,15 +20,147 @@ export function getCourseSections(session, courseId, cmid) {
20
20
  }
21
21
  // --- Foros ---
22
22
  /** Cuántas discusiones trae una página del índice de un foro. */
23
- export const POR_PAGINA = 50;
23
+ export const PAGE_SIZE = 50;
24
24
  /**
25
25
  * Discusiones de un foro, las más recientes primero. Moodle manda el mensaje completo de la
26
26
  * primera publicación de cada una; el que lee decide si lo recorta.
27
27
  */
28
28
  export function getForumDiscussions(session, forumid, page = 0) {
29
- return callWs(session, "mod_forum_get_forum_discussions", { forumid, page, perpage: POR_PAGINA });
29
+ return callWs(session, "mod_forum_get_forum_discussions", { forumid, page, perpage: PAGE_SIZE });
30
30
  }
31
31
  /** Publicaciones de una discusión, incluidas las respuestas. */
32
32
  export function getDiscussionPosts(session, discussionid) {
33
33
  return callWs(session, "mod_forum_get_discussion_posts", { discussionid });
34
34
  }
35
+ /** Si el usuario puede abrir un hilo en el foro, con el grupo que le toque. */
36
+ export async function canAddDiscussion(session, forumid) {
37
+ const { status } = await callWs(session, "mod_forum_can_add_discussion", { forumid });
38
+ return status;
39
+ }
40
+ /** Abre un hilo. Moodle elige solo el grupo del usuario si el foro es por grupos. */
41
+ export async function addDiscussion(session, forumid, subject, message) {
42
+ const { discussionid } = await callWs(session, "mod_forum_add_discussion", {
43
+ forumid,
44
+ subject,
45
+ message,
46
+ });
47
+ return discussionid;
48
+ }
49
+ /** Responde a una publicación, que puede ser la primera de la discusión. */
50
+ export async function addDiscussionPost(session, postid, subject, message) {
51
+ const { postid: newPostId } = await callWs(session, "mod_forum_add_discussion_post", {
52
+ postid,
53
+ subject,
54
+ message,
55
+ });
56
+ return newPostId;
57
+ }
58
+ /** Edita una publicación propia; con asunto vacío Moodle deja el que tenía. */
59
+ export async function updateDiscussionPost(session, postid, subject, message) {
60
+ await callWs(session, "mod_forum_update_discussion_post", { postid, subject, message });
61
+ }
62
+ /** Borra una publicación; si es la primera, se va la discusión entera. */
63
+ export async function deletePost(session, postid) {
64
+ await callWs(session, "mod_forum_delete_post", { postid });
65
+ }
66
+ // --- Tareas ---
67
+ /** Las tareas de un curso con su configuración: fechas y qué tipos de entrega aceptan. */
68
+ export async function getAssignments(session, courseId) {
69
+ const { courses } = await callWs(session, "mod_assign_get_assignments", { "courseids[0]": courseId });
70
+ return courses[0]?.assignments ?? [];
71
+ }
72
+ /** Estado de la entrega del usuario y, si ya la corrigieron, la devolución. */
73
+ export function getSubmissionStatus(session, assignid) {
74
+ return callWs(session, "mod_assign_get_submission_status", { assignid });
75
+ }
76
+ // --- Elecciones (choice) y selección de grupos (choicegroup) ---
77
+ export async function getChoices(session, courseId) {
78
+ const { choices } = await callWs(session, "mod_choice_get_choices_by_courses", {
79
+ "courseids[0]": courseId,
80
+ });
81
+ return choices;
82
+ }
83
+ export async function getChoiceOptions(session, choiceid) {
84
+ const { options } = await callWs(session, "mod_choice_get_choice_options", {
85
+ choiceid,
86
+ });
87
+ return options;
88
+ }
89
+ export async function submitChoiceResponse(session, choiceid, optionIds) {
90
+ const params = { choiceid };
91
+ optionIds.forEach((id, i) => (params[`responses[${i}]`] = id));
92
+ await callWs(session, "mod_choice_submit_choice_response", params);
93
+ }
94
+ export async function deleteChoiceResponses(session, choiceid) {
95
+ await callWs(session, "mod_choice_delete_choice_responses", { choiceid });
96
+ }
97
+ export async function getChoicegroupOptions(session, choicegroupid) {
98
+ const { userid } = await getSiteInfo(session);
99
+ const { options } = await callWs(session, "mod_choicegroup_get_choicegroup_options", {
100
+ choicegroupid,
101
+ userid,
102
+ });
103
+ return options;
104
+ }
105
+ /**
106
+ * El plugin lee `responses` si la actividad deja un solo grupo y `choicegroup_<id>: "true"` si deja
107
+ * varios, y la configuración no se puede consultar: mandamos las dos formas y él usa la que le sirve.
108
+ * Con varios grupos, los que no vienen marcados se quitan.
109
+ */
110
+ export async function submitChoicegroupResponse(session, choicegroupid, optionIds) {
111
+ const data = [
112
+ { name: "responses", value: String(optionIds[0]) },
113
+ ...optionIds.map((id) => ({ name: `choicegroup_${id}`, value: "true" })),
114
+ ];
115
+ const params = { choicegroupid };
116
+ data.forEach((d, i) => {
117
+ params[`data[${i}][name]`] = d.name;
118
+ params[`data[${i}][value]`] = d.value;
119
+ });
120
+ await callWs(session, "mod_choicegroup_submit_choicegroup_response", params);
121
+ }
122
+ export async function deleteChoicegroupResponses(session, choicegroupid) {
123
+ await callWs(session, "mod_choicegroup_delete_choicegroup_responses", { choicegroupid });
124
+ }
125
+ // --- Mensajes ---
126
+ /** Nombre de otro usuario, visto desde el usuario logueado, o null si no existe. */
127
+ export async function getMemberName(session, userId) {
128
+ const { userid } = await getSiteInfo(session);
129
+ let members;
130
+ try {
131
+ members = await callWs(session, "core_message_get_member_info", {
132
+ referenceuserid: userid,
133
+ "userids[0]": userId,
134
+ });
135
+ }
136
+ catch (e) {
137
+ // Con un id que no existe, Moodle 5.1 no devuelve vacío: revienta con un error de PHP.
138
+ if (e instanceof MoodleError)
139
+ return null;
140
+ throw e;
141
+ }
142
+ const m = members.find((x) => x.id === userId && !x.isdeleted);
143
+ return m?.fullname ?? null;
144
+ }
145
+ /** Manda un mensaje privado. Moodle no tira excepción si falla: devuelve `msgid: -1` y el motivo. */
146
+ export async function sendInstantMessage(session, touserid, html) {
147
+ const [res] = await callWs(session, "core_message_send_instant_messages", { "messages[0][touserid]": touserid, "messages[0][text]": html, "messages[0][textformat]": 1 });
148
+ if (!res || res.msgid === -1)
149
+ throw new MoodleError(res?.errormessage || "Moodle no aceptó el mensaje.");
150
+ return res.msgid;
151
+ }
152
+ // --- Calendario ---
153
+ /** Crea un evento personal: solo lo ve el usuario. */
154
+ export async function createUserEvent(session, event) {
155
+ const { events } = await callWs(session, "core_calendar_create_calendar_events", {
156
+ "events[0][name]": event.name,
157
+ "events[0][description]": event.description,
158
+ "events[0][format]": 1,
159
+ "events[0][eventtype]": "user",
160
+ "events[0][timestart]": event.timestart,
161
+ "events[0][timeduration]": event.timeduration,
162
+ });
163
+ if (!events[0])
164
+ throw new MoodleError("Moodle no creó el evento.");
165
+ return events[0].id;
166
+ }
@@ -37,11 +37,11 @@ export async function callWs(session, wsfunction, params = {}) {
37
37
  export async function fetchFile(session, url, maxBytes) {
38
38
  let token = await session.getToken();
39
39
  for (let attempt = 0;; attempt++) {
40
- const conToken = new URL(url);
41
- conToken.searchParams.set("token", token);
40
+ const withToken = new URL(url);
41
+ withToken.searchParams.set("token", token);
42
42
  let res;
43
43
  try {
44
- res = await fetch(conToken, { signal: AbortSignal.timeout(60_000) });
44
+ res = await fetch(withToken, { signal: AbortSignal.timeout(60_000) });
45
45
  }
46
46
  catch (e) {
47
47
  throw new MoodleError(`No se pudo bajar el archivo: ${e.message}`);
@@ -57,27 +57,27 @@ export async function fetchFile(session, url, maxBytes) {
57
57
  }
58
58
  if (!res.ok || !res.body)
59
59
  throw new MoodleError(`HTTP ${res.status} al bajar el archivo`);
60
- return { bytes: await leerConLimite(res, maxBytes), contentType };
60
+ return { bytes: await readWithLimit(res, maxBytes), contentType };
61
61
  }
62
62
  }
63
63
  /** Lee el cuerpo cortando apenas pasa el límite, sin esperar a bajarlo entero. */
64
- async function leerConLimite(res, maxBytes) {
65
- const limite = `El archivo pesa más de ${Math.round(maxBytes / 1024 / 1024)} MB; es demasiado para leerlo.`;
64
+ async function readWithLimit(res, maxBytes) {
65
+ const tooBig = `El archivo pesa más de ${Math.round(maxBytes / 1024 / 1024)} MB; es demasiado para leerlo.`;
66
66
  if (Number(res.headers.get("content-length")) > maxBytes) {
67
67
  await res.body?.cancel();
68
- throw new MoodleError(limite);
68
+ throw new MoodleError(tooBig);
69
69
  }
70
- const partes = [];
70
+ const chunks = [];
71
71
  let total = 0;
72
- for await (const parte of res.body) {
73
- total += parte.length;
72
+ for await (const chunk of res.body) {
73
+ total += chunk.length;
74
74
  if (total > maxBytes)
75
- throw new MoodleError(limite);
76
- partes.push(parte);
75
+ throw new MoodleError(tooBig);
76
+ chunks.push(chunk);
77
77
  }
78
78
  const bytes = new Uint8Array(total);
79
79
  let i = 0;
80
- for (const p of partes) {
80
+ for (const p of chunks) {
81
81
  bytes.set(p, i);
82
82
  i += p.length;
83
83
  }
@@ -0,0 +1,159 @@
1
+ import { textToHtml } from "../../shared/html.js";
2
+ import { addDiscussion, addDiscussionPost, createUserEvent, deleteChoiceResponses, deleteChoicegroupResponses, deletePost, getChoiceOptions, getChoicegroupOptions, getDiscussionPosts, getMemberName, sendInstantMessage, submitChoiceResponse, submitChoicegroupResponse, updateDiscussionPost, } from "../client/client.js";
3
+ import { AULA_BASE_URL } from "../client/constants.js";
4
+ import { toOption } from "./activities.js";
5
+ import { discussionAddr, formatAddress, parseAddress } from "./address.js";
6
+ import { isoDate } from "./fields.js";
7
+ import { findModule } from "./navigate.js";
8
+ // --- Foros ---
9
+ /**
10
+ * Con la dirección de un foro abre un hilo; con la de una discusión responde. Así el modelo no elige
11
+ * entre dos operaciones: la dirección que ya tiene dice cuál es.
12
+ */
13
+ export async function postToForum(session, rawAddress, message, subject, replyTo) {
14
+ const address = parseAddress(rawAddress);
15
+ if (address.level === "module") {
16
+ const { module } = await findModule(session, address.courseId, address.cmid);
17
+ if (module.modname !== "forum") {
18
+ throw new Error(`"${rawAddress}" no es un foro, es un módulo de tipo ${module.modname}.`);
19
+ }
20
+ if (!subject?.trim())
21
+ throw new Error("Para abrir un hilo hace falta un `asunto`.");
22
+ const discussionId = await addDiscussion(session, module.instance, subject.trim(), textToHtml(message));
23
+ return { publicado: "hilo nuevo", direccion: discussionAddr(address.courseId, address.cmid, discussionId) };
24
+ }
25
+ if (address.level === "discussion") {
26
+ const { posts } = await getDiscussionPosts(session, address.discussionId);
27
+ const parent = replyTo
28
+ ? findPost(posts, replyTo, rawAddress)
29
+ : posts.find((p) => p.parentid === null && !p.isdeleted);
30
+ if (!parent)
31
+ throw new Error(`La discusión ${rawAddress} no tiene publicaciones a las que responder.`);
32
+ if (!parent.capabilities.reply) {
33
+ throw new Error("No podés responder en esta discusión: está cerrada o el foro no deja responder.");
34
+ }
35
+ const postId = await addDiscussionPost(session, parent.id, subject?.trim() || parent.replysubject, textToHtml(message));
36
+ return { publicado: "respuesta", direccion: formatAddress(address), id: postId, respuestaA: parent.id };
37
+ }
38
+ throw new Error(`Para publicar hace falta la dirección de un foro (/curso/{id}/mod/{cmid}) o de una discusión ` +
39
+ `(/curso/{id}/mod/{cmid}/disc/{id}); "${rawAddress}" no es ninguna de las dos.`);
40
+ }
41
+ export async function editForumPost(session, rawAddress, postId, message, subject) {
42
+ const { address, post } = await findPostAt(session, rawAddress, postId);
43
+ if (!post.capabilities.edit) {
44
+ throw new Error("No podés editar esta publicación: no es tuya o ya pasó el tiempo para editarla.");
45
+ }
46
+ // Asunto vacío: Moodle deja el que tenía.
47
+ await updateDiscussionPost(session, postId, subject?.trim() ?? "", textToHtml(message));
48
+ return { editado: true, direccion: formatAddress(address), id: postId };
49
+ }
50
+ export async function deleteForumPost(session, rawAddress, postId) {
51
+ const { address, post } = await findPostAt(session, rawAddress, postId);
52
+ if (!post.capabilities.delete) {
53
+ throw new Error("No podés borrar esta publicación: no es tuya, tiene respuestas o ya pasó el tiempo.");
54
+ }
55
+ await deletePost(session, postId);
56
+ const isFirst = post.parentid === null;
57
+ return {
58
+ borrado: true,
59
+ id: postId,
60
+ // Borrar la primera publicación se lleva la discusión entera.
61
+ discusionBorrada: isFirst || undefined,
62
+ direccion: isFirst ? undefined : formatAddress(address),
63
+ };
64
+ }
65
+ async function findPostAt(session, rawAddress, postId) {
66
+ const address = parseAddress(rawAddress);
67
+ if (address.level !== "discussion") {
68
+ throw new Error(`Hace falta la dirección de la discusión donde está la publicación; "${rawAddress}" no lo es.`);
69
+ }
70
+ const { posts } = await getDiscussionPosts(session, address.discussionId);
71
+ return { address, post: findPost(posts, postId, rawAddress) };
72
+ }
73
+ function findPost(posts, postId, rawAddress) {
74
+ const post = posts.find((p) => p.id === postId && !p.isdeleted);
75
+ if (!post) {
76
+ throw new Error(`La publicación ${postId} no está en ${rawAddress}. Los ids salen de abrir la discusión con aula_open.`);
77
+ }
78
+ return post;
79
+ }
80
+ // --- Elecciones y selección de grupos ---
81
+ /** Deja elegidas exactamente `optionIds`; vacío borra la respuesta. Devuelve cómo quedó. */
82
+ export async function answerChoice(session, rawAddress, optionIds) {
83
+ const address = parseAddress(rawAddress);
84
+ if (address.level !== "module")
85
+ throw new Error(`"${rawAddress}" no es la dirección de un módulo.`);
86
+ const { module } = await findModule(session, address.courseId, address.cmid);
87
+ const api = CHOICE_APIS[module.modname];
88
+ if (!api) {
89
+ throw new Error(`"${rawAddress}" es un módulo de tipo ${module.modname}; solo se puede elegir en choice y choicegroup.`);
90
+ }
91
+ const current = await api.options(session, module.instance);
92
+ for (const id of optionIds) {
93
+ const option = current.find((o) => o.id === id);
94
+ if (!option) {
95
+ throw new Error(`No existe la opción ${id}. Las válidas son: ${current.map((o) => o.id).join(", ")}.`);
96
+ }
97
+ if (option.disabled && !option.checked) {
98
+ throw new Error(`La opción ${id} (${option.text ?? option.name}) está completa o deshabilitada.`);
99
+ }
100
+ }
101
+ if (optionIds.length)
102
+ await api.submit(session, module.instance, optionIds);
103
+ else
104
+ await api.clear(session, module.instance);
105
+ const after = await api.options(session, module.instance);
106
+ const chosen = after.filter((o) => o.checked).map((o) => o.id);
107
+ const matches = chosen.length === optionIds.length && optionIds.every((id) => chosen.includes(id));
108
+ return {
109
+ elegidas: chosen,
110
+ // Pasa cuando la actividad deja una sola opción y se pidieron varias.
111
+ aviso: matches ? undefined : "Moodle no dejó exactamente las opciones pedidas; `elegidas` es lo que quedó.",
112
+ opciones: after.map(toOption),
113
+ };
114
+ }
115
+ const CHOICE_APIS = {
116
+ choice: { options: getChoiceOptions, submit: submitChoiceResponse, clear: deleteChoiceResponses },
117
+ choicegroup: {
118
+ options: getChoicegroupOptions,
119
+ submit: submitChoicegroupResponse,
120
+ clear: deleteChoicegroupResponses,
121
+ },
122
+ };
123
+ // --- Mensajes ---
124
+ export async function sendMessage(session, userId, message) {
125
+ // Se busca antes el nombre: un id equivocado le mandaría el mensaje a otra persona sin que nadie lo note.
126
+ const name = await getMemberName(session, userId);
127
+ if (!name) {
128
+ throw new Error(`No existe el usuario ${userId}. El id sale del \`autorId\` de un foro abierto con aula_open.`);
129
+ }
130
+ await sendInstantMessage(session, userId, textToHtml(message));
131
+ return { enviado: true, para: name };
132
+ }
133
+ // --- Calendario ---
134
+ /** Exige la zona horaria: el servidor hosteado no está en la hora de Argentina y adivinarla corre el evento. */
135
+ const HAS_TIMEZONE = /(Z|[+-]\d{2}:?\d{2})$/i;
136
+ export async function addCalendarEvent(session, event) {
137
+ const start = new Date(event.start);
138
+ if (!HAS_TIMEZONE.test(event.start.trim()) || Number.isNaN(start.getTime())) {
139
+ throw new Error(`Fecha inválida: "${event.start}". Usá ISO 8601 con zona horaria, por ejemplo "2026-10-14T18:00:00-03:00".`);
140
+ }
141
+ const timestart = Math.floor(start.getTime() / 1000);
142
+ const timeduration = Math.round((event.durationMinutes ?? 0) * 60);
143
+ const name = event.name.trim();
144
+ const id = await createUserEvent(session, {
145
+ name,
146
+ description: event.description ? textToHtml(event.description) : "",
147
+ timestart,
148
+ timeduration,
149
+ });
150
+ return {
151
+ creado: true,
152
+ id,
153
+ nombre: name,
154
+ inicio: isoDate(timestart),
155
+ fin: timeduration ? isoDate(timestart + timeduration) : undefined,
156
+ // Para que el usuario lo vea en el calendario del aula.
157
+ url: `${AULA_BASE_URL}/calendar/view.php?view=day&time=${timestart}`,
158
+ };
159
+ }
@@ -0,0 +1,101 @@
1
+ import { htmlToText } from "../../shared/html.js";
2
+ import { getAssignments, getChoiceOptions, getChoicegroupOptions, getChoices, getSubmissionStatus, } from "../client/client.js";
3
+ import { isoDate, toFile } from "./fields.js";
4
+ const SUBMISSION_STATUS_LABELS = {
5
+ new: "sin entregar",
6
+ draft: "borrador",
7
+ submitted: "enviada",
8
+ reopened: "reabierta",
9
+ };
10
+ /** La entrega del usuario (o la de su grupo): qué acepta la tarea, qué subió y la devolución si la hay. */
11
+ export async function viewSubmission(session, courseId, module) {
12
+ const [assignments, status] = await Promise.all([
13
+ getAssignments(session, courseId),
14
+ getSubmissionStatus(session, module.instance),
15
+ ]);
16
+ const assignment = assignments.find((a) => a.cmid === module.id);
17
+ const attempt = status.lastattempt;
18
+ // En las entregas grupales la individual queda vacía; la que cuenta es la del grupo.
19
+ const submission = attempt?.teamsubmission ?? attempt?.submission;
20
+ const config = (plugin, name) => assignment?.configs.find((c) => c.subtype === "assignsubmission" && c.plugin === plugin && c.name === name)
21
+ ?.value;
22
+ const accepts = [];
23
+ if (config("file", "enabled") === "1") {
24
+ accepts.push({
25
+ tipo: "archivos",
26
+ maximo: Number(config("file", "maxfilesubmissions")) || undefined,
27
+ tamanioMaximo: Number(config("file", "maxsubmissionsizebytes")) || undefined,
28
+ extensiones: config("file", "filetypeslist") || undefined,
29
+ });
30
+ }
31
+ if (config("onlinetext", "enabled") === "1") {
32
+ accepts.push({ tipo: "texto en línea", limitePalabras: Number(config("onlinetext", "wordlimit")) || undefined });
33
+ }
34
+ const feedback = status.feedback;
35
+ return {
36
+ estado: submission ? (SUBMISSION_STATUS_LABELS[submission.status] ?? submission.status) : "sin entregar",
37
+ grupal: assignment?.teamsubmission === 1 || undefined,
38
+ // Moodle crea la entrega vacía al abrir la tarea: su fecha no dice nada hasta que hay algo subido.
39
+ modificada: (submission?.status !== "new" && isoDate(submission?.timemodified)) || undefined,
40
+ abre: isoDate(assignment?.allowsubmissionsfromdate) || undefined,
41
+ vence: isoDate(assignment?.duedate) || undefined,
42
+ prorroga: isoDate(attempt?.extensionduedate) || undefined,
43
+ cierreDefinitivo: isoDate(assignment?.cutoffdate) || undefined,
44
+ acepta: accepts.length ? accepts : undefined,
45
+ // Con borradores, lo subido no cuenta hasta confirmar el envío.
46
+ requiereConfirmarEnvio: assignment?.submissiondrafts === 1 || undefined,
47
+ requiereDeclaracion: assignment?.requiresubmissionstatement === 1 || undefined,
48
+ puedeEditar: attempt?.canedit ?? false,
49
+ puedeEnviar: attempt?.cansubmit || undefined,
50
+ bloqueada: attempt?.locked || undefined,
51
+ ...pluginContent(submission?.plugins),
52
+ devolucion: feedback
53
+ ? {
54
+ calificacion: feedback.gradefordisplay || undefined,
55
+ fecha: isoDate(feedback.gradeddate),
56
+ ...pluginContent(feedback.plugins),
57
+ }
58
+ : undefined,
59
+ };
60
+ }
61
+ /** Los archivos y textos de una entrega o devolución, sin los plugins vacíos. */
62
+ function pluginContent(plugins = []) {
63
+ const files = plugins.flatMap((p) => p.fileareas?.flatMap((a) => a.files ?? []) ?? []);
64
+ const texts = plugins
65
+ .flatMap((p) => p.editorfields ?? [])
66
+ .map((e) => htmlToText(e.text))
67
+ .filter(Boolean);
68
+ return {
69
+ archivos: files.length ? files.map(toFile) : undefined,
70
+ texto: texts.length ? texts.join("\n\n") : undefined,
71
+ };
72
+ }
73
+ export async function viewChoice(session, courseId, module) {
74
+ const [choices, options] = await Promise.all([
75
+ getChoices(session, courseId),
76
+ getChoiceOptions(session, module.instance),
77
+ ]);
78
+ const choice = choices.find((c) => c.coursemodule === module.id);
79
+ return {
80
+ multiple: choice?.allowmultiple || undefined,
81
+ puedeCambiar: choice?.allowupdate,
82
+ abre: isoDate(choice?.timeopen) || undefined,
83
+ cierra: isoDate(choice?.timeclose) || undefined,
84
+ opciones: options.map(toOption),
85
+ };
86
+ }
87
+ /** El plugin no expone si deja cambiar o elegir varios grupos: eso lo dice la descripción o el error al elegir. */
88
+ export async function viewChoicegroup(session, module) {
89
+ const options = await getChoicegroupOptions(session, module.instance);
90
+ return { opciones: options.map(toOption) };
91
+ }
92
+ export function toOption(o) {
93
+ return {
94
+ id: o.id,
95
+ texto: o.text ?? o.name,
96
+ elegida: o.checked || undefined,
97
+ deshabilitada: o.disabled || undefined,
98
+ cupo: o.maxanswers || undefined,
99
+ anotados: o.countanswers,
100
+ };
101
+ }
@@ -0,0 +1,52 @@
1
+ export const ROOT = "/";
2
+ export const courseAddr = (courseId) => `/curso/${courseId}`;
3
+ export const moduleAddr = (courseId, cmid) => `/curso/${courseId}/mod/${cmid}`;
4
+ export const discussionAddr = (courseId, cmid, discussionId) => `/curso/${courseId}/mod/${cmid}/disc/${discussionId}`;
5
+ const FORMATS = [
6
+ "/",
7
+ "/curso/{courseId}",
8
+ "/curso/{courseId}/mod/{cmid}",
9
+ "/curso/{courseId}/mod/{cmid}/disc/{discussionId}",
10
+ ].join(", ");
11
+ const PATTERN = /^\/curso\/(\d+)(?:\/mod\/(\d+)(?:\/disc\/(\d+))?)?$/;
12
+ export function parseAddress(raw) {
13
+ const path = raw.trim().replace(/\/+$/, "") || "/";
14
+ if (path === "/")
15
+ return { level: "root" };
16
+ const m = PATTERN.exec(path);
17
+ if (!m)
18
+ throw new Error(`Dirección inválida: "${raw}". Formatos válidos: ${FORMATS}`);
19
+ const [, course, cmid, disc] = m;
20
+ const courseId = Number(course);
21
+ if (!cmid)
22
+ return { level: "course", courseId };
23
+ if (!disc)
24
+ return { level: "module", courseId, cmid: Number(cmid) };
25
+ return { level: "discussion", courseId, cmid: Number(cmid), discussionId: Number(disc) };
26
+ }
27
+ /** La dirección en texto, tal como la ve el modelo. */
28
+ export function formatAddress(address) {
29
+ switch (address.level) {
30
+ case "root":
31
+ return ROOT;
32
+ case "course":
33
+ return courseAddr(address.courseId);
34
+ case "module":
35
+ return moduleAddr(address.courseId, address.cmid);
36
+ case "discussion":
37
+ return discussionAddr(address.courseId, address.cmid, address.discussionId);
38
+ }
39
+ }
40
+ /** La dirección de un nivel más arriba, o null si ya estamos en la raíz. */
41
+ export function parentOf(address) {
42
+ switch (address.level) {
43
+ case "root":
44
+ return null;
45
+ case "course":
46
+ return ROOT;
47
+ case "module":
48
+ return courseAddr(address.courseId);
49
+ case "discussion":
50
+ return moduleAddr(address.courseId, address.cmid);
51
+ }
52
+ }
@@ -0,0 +1,14 @@
1
+ import { userFacingUrl } from "./files.js";
2
+ /** Los timestamps de Moodle (segundos) en ISO; 0 o vacío es "sin fecha". */
3
+ export const isoDate = (seconds) => seconds ? new Date(seconds * 1000).toISOString() : null;
4
+ export function toFile(f) {
5
+ return {
6
+ nombre: f.filename,
7
+ ruta: f.filepath || undefined,
8
+ tamanio: f.filesize,
9
+ mimetype: f.mimetype,
10
+ modificado: isoDate(f.timemodified),
11
+ // Sirve para pasársela al usuario y también para leerlo con aula_read_file.
12
+ url: userFacingUrl(f.fileurl),
13
+ };
14
+ }
@@ -0,0 +1,89 @@
1
+ import { openDocument, UnsupportedFormat } from "../../shared/documents/index.js";
2
+ import { AULA_BASE_URL } from "../client/constants.js";
3
+ import { fetchFile } from "../client/moodle-api.js";
4
+ const ORIGIN = new URL(AULA_BASE_URL).origin;
5
+ const WS_PATH = "/webservice/pluginfile.php/";
6
+ const WEB_PATH = "/pluginfile.php/";
7
+ /** Cuánto se devuelve por llamada, en caracteres de texto. */
8
+ const BUDGET_CHARS = 30_000;
9
+ /** Lo que cuesta una página como imagen (~1.600 tokens), medido en caracteres de texto. */
10
+ const IMAGE_COST_CHARS = 6_000;
11
+ /** El más grande que hay hoy en los cursos pesa 12 MB. */
12
+ const MAX_BYTES = 30 * 1024 * 1024;
13
+ /**
14
+ * Moodle devuelve las URLs del web service, que piden token. Al usuario le sirve la misma ruta sin
15
+ * `/webservice`, que se abre con la sesión de su navegador. Es la única que mostramos: el token no
16
+ * sale nunca del servidor.
17
+ */
18
+ export function userFacingUrl(fileurl) {
19
+ return fileurl.replace(`${ORIGIN}${WS_PATH}`, `${ORIGIN}${WEB_PATH}`);
20
+ }
21
+ /**
22
+ * Acepta cualquiera de las dos formas y devuelve la del web service. Solo archivos del aula: con
23
+ * cualquier otra URL estaríamos mandando el token del usuario a donde diga el modelo.
24
+ */
25
+ function downloadUrl(url) {
26
+ let u;
27
+ try {
28
+ u = new URL(url);
29
+ }
30
+ catch {
31
+ throw new Error(`URL inválida: "${url}". Usá la \`url\` de un archivo tal como la devuelve aula_open.`);
32
+ }
33
+ const path = u.pathname.startsWith(WS_PATH) ? u.pathname : u.pathname.startsWith(WEB_PATH) ? WS_PATH + u.pathname.slice(WEB_PATH.length) : null;
34
+ if (u.origin !== ORIGIN || !path) {
35
+ throw new Error(`Solo se pueden leer archivos del aula virtual (${ORIGIN}${WEB_PATH}...).`);
36
+ }
37
+ u.pathname = path;
38
+ u.searchParams.delete("token");
39
+ u.searchParams.delete("wstoken");
40
+ return u;
41
+ }
42
+ /** Baja un archivo del aula y devuelve desde la parte `from` tantas como entren en el presupuesto. */
43
+ export async function readAulaFile(session, url, from = 1) {
44
+ const download = downloadUrl(url);
45
+ const fileName = decodeURIComponent(download.pathname.split("/").pop() ?? "");
46
+ const forUser = userFacingUrl(download.href);
47
+ const { bytes } = await fetchFile(session, download, MAX_BYTES);
48
+ let doc;
49
+ try {
50
+ doc = await openDocument(bytes, fileName);
51
+ }
52
+ catch (e) {
53
+ if (e instanceof UnsupportedFormat) {
54
+ throw new Error(`${e.message} El usuario lo puede bajar desde ${forUser}`);
55
+ }
56
+ throw e;
57
+ }
58
+ try {
59
+ if (from > doc.total) {
60
+ throw new Error(`"${fileName}" termina en ${doc.unit} ${doc.total}; se pidió desde ${from}.`);
61
+ }
62
+ const parts = [];
63
+ let spent = 0;
64
+ let n = from;
65
+ for (; n <= doc.total; n++) {
66
+ const part = await doc.part(n);
67
+ const cost = "text" in part ? part.text.length : IMAGE_COST_CHARS;
68
+ // Siempre al menos una parte, aunque sola se pase del presupuesto.
69
+ if (parts.length > 0 && spent + cost > BUDGET_CHARS)
70
+ break;
71
+ parts.push({ ...part, number: n });
72
+ spent += cost;
73
+ }
74
+ return {
75
+ archivo: fileName,
76
+ formato: doc.format,
77
+ unidad: doc.unit,
78
+ total: doc.total,
79
+ desde: from,
80
+ hasta: n - 1,
81
+ siguiente: n <= doc.total ? n : undefined,
82
+ urlParaUsuario: forUser,
83
+ parts,
84
+ };
85
+ }
86
+ finally {
87
+ await doc.close();
88
+ }
89
+ }