diff --git a/README.md b/README.md index 7acf7e1..210b1c8 100644 --- a/README.md +++ b/README.md @@ -285,7 +285,9 @@ Kubernetes 或密钥管理系统仍可覆盖文件中的值。 管理员可在“教学任务”列表中为有管理权限的教学班选择“关联 Moodle”,粘贴已有 Moodle 课程的 HTTPS 地址;清空并保存可解除关联。多个教学班可以关联同一课程。教师在“选课名单”中选择本人已发布或已归档的教学班后,可点击“进入 Moodle 课程”。 -该功能只保存链接,不检查课程是否存在,也不创建 Moodle 账号、同步名单或自动登录。教师须在 Moodle 中已有对应课程的访问权限;如需单点登录,需要分别配置两边的身份认证。部署升级时需应用数据库迁移。 +手动关联只保存链接,不检查课程是否存在,也不创建 Moodle 账号、同步名单或自动登录。教师须在 Moodle 中已有对应课程的访问权限;如需单点登录,需要分别配置两边的身份认证。部署升级时需应用数据库迁移。 + +管理员还可为已发布且尚未关联的教学任务创建 Moodle 空课程。服务端配置 `Moodle__BaseUrl`(HTTPS Moodle 根地址,可含子路径)、`Moodle__CategoryId`(目标分类数字 ID)和 `Moodle__Token`(Moodle Web 服务令牌)后显示创建按钮。请通过环境变量或密钥管理器提供令牌,不要提交到仓库。Moodle 需要启用 REST Web 服务并为服务账户提供 `core_course_get_courses_by_field`、`core_course_create_courses` 及相应分类创建、隐藏课程查看权限。系统使用教学任务 ID 生成课程短名称和 ID 号码,以便请求超时后重试恢复;创建的课程默认隐藏,需要 Moodle 管理员配置教师、内容和可见性。此步骤尚不自动同步用户和名单;教师可以在 Moodle 中从旧课程导入资源。 ### Keycloak 单点登录(可选) diff --git a/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs new file mode 100644 index 0000000..ab55340 --- /dev/null +++ b/src/Jiaowu.Api/Controllers/MoodleCoursesController.cs @@ -0,0 +1,44 @@ +using Jiaowu.Api.Domain.Academic; +using Jiaowu.Api.Domain.Identity; +using Jiaowu.Api.Infrastructure.Auth; +using Jiaowu.Api.Infrastructure.Persistence; +using Jiaowu.Api.Infrastructure.Teaching; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Jiaowu.Api.Controllers; + +[ApiController] +[Authorize(Roles = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin)] +[Route("api/moodle-courses")] +public sealed class MoodleCoursesController(AppDbContext db, ICurrentUserDataScope scope, MoodleCourseClient moodle) : ControllerBase +{ + [HttpGet("availability")] + public ActionResult Availability() => Ok(new { available = moodle.IsConfigured }); + + [HttpPost("teaching-tasks/{id:guid}")] + public async Task Create(Guid id, CancellationToken ct) + { + var query = db.TeachingTasks.AsNoTracking().Include(x => x.Course).AsQueryable(); + if (scope.Current.RestrictedCollegeId is Guid collegeId) + query = query.Where(x => x.Course!.CollegeId == collegeId); + var task = await query.SingleOrDefaultAsync(x => x.Id == id, ct); + if (task is null) return NotFound(); + if (!TeachingTaskMaintenancePolicy.CanManage(scope.Current, task.Course!.CollegeId, task.Course.Nature)) return Forbid(); + if (task.Status != TeachingTaskStatus.Published) return Conflict(new ProblemDetails { Detail = "仅已发布的教学任务可以创建 Moodle 课程。", Status = 409 }); + if (task.MoodleCourseUrl is not null) return Conflict(new ProblemDetails { Detail = "该教学任务已有 Moodle 课程关联。", Status = 409 }); + try + { + var url = await moodle.CreateOrRecoverAsync(task.Id, task.Name, ct); + var updated = await db.TeachingTasks.Where(x => x.Id == id && x.MoodleCourseUrl == null && x.Status == TeachingTaskStatus.Published) + .ExecuteUpdateAsync(setters => setters.SetProperty(x => x.MoodleCourseUrl, url), ct); + if (updated == 0) return Conflict(new ProblemDetails { Detail = "教学任务状态或课程关联已更改;请检查 Moodle 课程后重新操作。", Status = 409 }); + return Ok(new { url }); + } + catch (MoodleIntegrationException ex) + { + return StatusCode(StatusCodes.Status502BadGateway, new ProblemDetails { Title = "Moodle 课程创建失败", Detail = ex.Message, Status = StatusCodes.Status502BadGateway }); + } + } +} diff --git a/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs new file mode 100644 index 0000000..f2d1827 --- /dev/null +++ b/src/Jiaowu.Api/Infrastructure/Teaching/MoodleCourseClient.cs @@ -0,0 +1,87 @@ +using System.Text.Json; + +namespace Jiaowu.Api.Infrastructure.Teaching; + +public sealed class MoodleCourseClient(IHttpClientFactory clients, IConfiguration configuration) +{ + public bool IsConfigured => TryGetSettings(out _, out _, out _); + + private bool TryGetSettings(out Uri baseUri, out string token, out int categoryId) + { + var address = configuration["Moodle:BaseUrl"]?.Trim().TrimEnd('/') + "/"; + token = configuration["Moodle:Token"]?.Trim() ?? ""; + var validCategory = int.TryParse(configuration["Moodle:CategoryId"], out categoryId) && categoryId > 0; + var validUri = Uri.TryCreate(address, UriKind.Absolute, out var parsed) && + parsed.Scheme == Uri.UriSchemeHttps && string.IsNullOrEmpty(parsed.UserInfo) && + string.IsNullOrEmpty(parsed.Query) && string.IsNullOrEmpty(parsed.Fragment); + baseUri = validUri ? parsed! : null!; + return validUri && token.Length > 0 && validCategory; + } + + public async Task CreateOrRecoverAsync(Guid taskId, string name, CancellationToken ct) + { + if (!TryGetSettings(out var baseUri, out var token, out var categoryId)) + throw new MoodleIntegrationException("Moodle 未配置或配置无效。"); + var key = "jiaowu-" + taskId.ToString("N"); + var found = await FindAsync(baseUri, token, key, ct); + if (found is null) + { + using var created = await CallAsync(baseUri, token, "core_course_create_courses", new() + { + ["courses[0][fullname]"] = name, + ["courses[0][shortname]"] = key, + ["courses[0][idnumber]"] = key, + ["courses[0][categoryid]"] = categoryId.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["courses[0][visible]"] = "0" + }, ct); + if (created.RootElement.ValueKind != JsonValueKind.Array || created.RootElement.GetArrayLength() != 1 || + !created.RootElement[0].TryGetProperty("id", out var idValue) || !idValue.TryGetInt64(out var newId) || newId <= 0) + throw new MoodleIntegrationException("Moodle 返回的课程信息无效;请重试以恢复关联。"); + found = newId; + } + return new Uri(baseUri, "course/view.php?id=" + found.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToString(); + } + + private async Task FindAsync(Uri baseUri, string token, string key, CancellationToken ct) + { + using var result = await CallAsync(baseUri, token, "core_course_get_courses_by_field", new() + { + ["field"] = "shortname", ["value"] = key + }, ct); + if (result.RootElement.ValueKind != JsonValueKind.Object || + !result.RootElement.TryGetProperty("courses", out var courses) || courses.ValueKind != JsonValueKind.Array) + throw new MoodleIntegrationException("Moodle 返回的查询结果无效。"); + if (courses.GetArrayLength() == 0) return null; + if (courses.GetArrayLength() != 1 || courses[0].ValueKind != JsonValueKind.Object || + !courses[0].TryGetProperty("idnumber", out var idnumber) || idnumber.ValueKind != JsonValueKind.String || + idnumber.GetString() != key || !courses[0].TryGetProperty("id", out var id) || !id.TryGetInt64(out var value) || value <= 0) + throw new MoodleIntegrationException("Moodle 中存在标识冲突,请管理员检查后再试。"); + return value; + } + + private async Task CallAsync(Uri baseUri, string token, string function, Dictionary parameters, CancellationToken ct) + { + parameters["wstoken"] = token; + parameters["wsfunction"] = function; + parameters["moodlewsrestformat"] = "json"; + try + { + using var content = new FormUrlEncodedContent(parameters); + using var response = await clients.CreateClient("Moodle").PostAsync(new Uri(baseUri, "webservice/rest/server.php"), content, ct); + response.EnsureSuccessStatusCode(); + var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct), cancellationToken: ct); + if (json.RootElement.ValueKind == JsonValueKind.Object && json.RootElement.TryGetProperty("exception", out _)) + { + json.Dispose(); + throw new MoodleIntegrationException("Moodle 拒绝了请求,请检查服务权限和课程分类。"); + } + return json; + } + catch (Exception ex) when (ex is HttpRequestException or JsonException or TaskCanceledException && !ct.IsCancellationRequested) + { + throw new MoodleIntegrationException("无法确认 Moodle 操作结果,请检查连接后重试。", ex); + } + } +} + +public sealed class MoodleIntegrationException(string message, Exception? inner = null) : Exception(message, inner); diff --git a/src/Jiaowu.Api/Program.cs b/src/Jiaowu.Api/Program.cs index 4bcc66d..6189804 100644 --- a/src/Jiaowu.Api/Program.cs +++ b/src/Jiaowu.Api/Program.cs @@ -27,6 +27,7 @@ using Jiaowu.Api.Infrastructure.Persistence; using Jiaowu.Api.Infrastructure.Plugins; using Jiaowu.Api.Infrastructure.Scheduling; using Jiaowu.Api.Infrastructure.Timetables; +using Jiaowu.Api.Infrastructure.Teaching; using Jiaowu.Plugin.Abstractions; using CaptchaKit.AspNetCore; using Fido2NetLib; @@ -363,6 +364,9 @@ builder.Services.AddSingleton(rabbitMqOptions); builder.Services.AddSingleton(); builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpClient("LicenseIssuance", client => client.Timeout = TimeSpan.FromSeconds(20)); +builder.Services.AddHttpClient("Moodle", client => client.Timeout = TimeSpan.FromSeconds(45)) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); +builder.Services.AddScoped(); builder.Services.AddMemoryCache(); builder.Services.AddHttpClient((services, client) => { diff --git a/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs b/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs new file mode 100644 index 0000000..d3e79dc --- /dev/null +++ b/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs @@ -0,0 +1,80 @@ +using System.Net; +using Jiaowu.Api.Infrastructure.Teaching; +using Microsoft.Extensions.Configuration; + +namespace Jiaowu.Api.Tests; + +public sealed class MoodleCourseClientTests +{ + [Fact] + public async Task CreatesHiddenCourseAndRecoversUsingStableIdentifiers() + { + var taskId = Guid.NewGuid(); + var key = "jiaowu-" + taskId.ToString("N"); + var handler = new StubHandler(); + var client = Client(handler); + var first = await client.CreateOrRecoverAsync(taskId, "测试课程", CancellationToken.None); + Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", first); + Assert.Contains("courses%5B0%5D%5Bvisible%5D=0", handler.Requests[1]); + Assert.Contains(key, handler.Requests[1]); + handler.ExistingKey = key; + var second = await client.CreateOrRecoverAsync(taskId, "测试课程", CancellationToken.None); + Assert.Equal(first, second); + Assert.Equal(3, handler.Requests.Count); + } + + [Fact] + public async Task RetryRecoversCourseAfterCreateResponseIsLost() + { + var taskId = Guid.NewGuid(); + var handler = new StubHandler { FailCreateOnce = true, RecoveryKey = "jiaowu-" + taskId.ToString("N") }; + var client = Client(handler); + await Assert.ThrowsAsync(() => client.CreateOrRecoverAsync(taskId, "课程", CancellationToken.None)); + Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", await client.CreateOrRecoverAsync(taskId, "课程", CancellationToken.None)); + Assert.Equal(3, handler.Requests.Count); + } + + [Fact] + public async Task RejectsExistingCourseWithUnexpectedIdNumber() + { + var handler = new StubHandler { ExistingKey = "different" }; + await Assert.ThrowsAsync(() => Client(handler).CreateOrRecoverAsync(Guid.NewGuid(), "课程", CancellationToken.None)); + Assert.Single(handler.Requests); + } + + private static MoodleCourseClient Client(StubHandler handler) + { + var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "test-token", ["Moodle:CategoryId"] = "4" + }).Build(); + return new MoodleCourseClient(new Factory(new HttpClient(handler)), config); + } + + private sealed class Factory(HttpClient client) : IHttpClientFactory + { + public HttpClient CreateClient(string name) => client; + } + + private sealed class StubHandler : HttpMessageHandler + { + public List Requests { get; } = []; + public string? ExistingKey { get; set; } + public string? RecoveryKey { get; set; } + public bool FailCreateOnce { get; set; } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = await request.Content!.ReadAsStringAsync(cancellationToken); + Requests.Add(body); + if (FailCreateOnce && body.Contains("core_course_create_courses")) + { + FailCreateOnce = false; + ExistingKey = RecoveryKey; + throw new HttpRequestException("response lost"); + } + var response = body.Contains("core_course_create_courses") ? "[{\"id\":42,\"shortname\":\"x\"}]" : + ExistingKey is null ? "{\"courses\":[]}" : $"{{\"courses\":[{{\"id\":42,\"idnumber\":\"{ExistingKey}\"}}]}}"; + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(response) }; + } + } +} diff --git a/web/src/i18n/messages/en-US/core.ts b/web/src/i18n/messages/en-US/core.ts index ee1354a..0672daf 100644 --- a/web/src/i18n/messages/en-US/core.ts +++ b/web/src/i18n/messages/en-US/core.ts @@ -2,6 +2,7 @@ export default { moodle: { manage: "Link Moodle", hint: "Paste the HTTPS address of an existing Moodle course. Clear it to unlink. Teachers need access to the course in Moodle.", placeholder: "https://moodle.example.edu/course/view.php?id=123", save: "Save", cancel: "Cancel", saved: "Moodle course link saved", open: "Open Moodle course", linked: "Moodle linked", + create: "Create empty course", createConfirm: "Create a hidden, empty Moodle course for this teaching task? Teachers and students will not be enrolled automatically.", created: "Moodle course created and linked", }, selectionTemplate: { courseSelection: "Course selection", diff --git a/web/src/i18n/messages/zh-CN/core.ts b/web/src/i18n/messages/zh-CN/core.ts index b712de9..6196527 100644 --- a/web/src/i18n/messages/zh-CN/core.ts +++ b/web/src/i18n/messages/zh-CN/core.ts @@ -2,6 +2,7 @@ export default { moodle: { manage: "关联 Moodle", hint: "粘贴已有 Moodle 课程的 HTTPS 地址;留空可解除关联。教师需要具备 Moodle 课程访问权限。", placeholder: "https://moodle.example.edu/course/view.php?id=123", save: "保存", cancel: "取消", saved: "Moodle 课程关联已保存", open: "进入 Moodle 课程", linked: "已关联 Moodle", + create: "创建空课程", createConfirm: "将在 Moodle 创建隐藏的空课程并关联当前教学任务。教师和学生尚不会自动加入,确认继续?", created: "Moodle 课程已创建并关联", }, selectionTemplate: { courseSelection: "学生选课", diff --git a/web/src/views/TeachingTasksView.vue b/web/src/views/TeachingTasksView.vue index 02c0eee..cb8ffd4 100644 --- a/web/src/views/TeachingTasksView.vue +++ b/web/src/views/TeachingTasksView.vue @@ -33,6 +33,7 @@ const hasMore = ref(false); const dialogVisible = ref(false); const moodleDialog = ref(false); const moodleSaving = ref(false); +const moodleAvailable = ref(false); const moodleTask = ref(null); const moodleUrl = ref(""); const generationDialog = ref(false); @@ -267,10 +268,29 @@ function canManageRow(row: any) { ); } -function editMoodle(row: any) { +async function editMoodle(row: any) { moodleTask.value = row; moodleUrl.value = row.moodleCourseUrl ?? ""; moodleDialog.value = true; + moodleAvailable.value = false; + try { + moodleAvailable.value = (await http.get('/moodle-courses/availability')).data.available; + } catch { /* Manual linking remains available. */ } +} + +async function createMoodle() { + try { + await ElMessageBox.confirm(t('moodle.createConfirm'), t('moodle.create'), { type: 'warning' }); + moodleSaving.value = true; + await http.post(`/moodle-courses/teaching-tasks/${moodleTask.value.id}`); + moodleDialog.value = false; + ElMessage.success(t('moodle.created')); + await load(); + } catch (error) { + if (error !== 'cancel' && error !== 'close') ElMessage.error(apiErrorMessage(error)); + } finally { + moodleSaving.value = false; + } } async function saveMoodle() { @@ -810,6 +830,7 @@ onMounted(async () => {

{{ t('moodle.hint') }}