Create Moodle courses from teaching tasks

This commit is contained in:
biss committed 2026-11-21 15:52:35 +08:00
1 parent c7786f7c16
commit d010af26b5
8 files changed
+242 -2

No files matched your search

+3 -1
View File
@@ -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 单点登录(可选)
@@ -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<ActionResult> 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 });
}
}
}
@@ -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<string> 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<long?> 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<JsonDocument> CallAsync(Uri baseUri, string token, string function, Dictionary<string, string> 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);
Loaded 3 of 8 files, more files were not shown because too many files have changed in this diff. Show more