This commit is contained in:
1 parent
cdb4637c65
commit
f0c0479bcb
22 files changed
+1099
-76
No files matched your search
@@ -2,6 +2,7 @@ using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Globalization;
|
||||
|
||||
namespace LehrerApp.WebUntis;
|
||||
|
||||
@@ -30,6 +31,8 @@ public sealed partial class WebUntisClient : IAsyncDisposable
|
||||
// (siehe _sessionId), deshalb hier ausgeklammert.
|
||||
private string? _serverCookies;
|
||||
private string? _tenantId;
|
||||
private string? _restBearerToken;
|
||||
private DateTimeOffset _restBearerExpiresAt;
|
||||
private DateTimeOffset _sessionExpiresAt;
|
||||
private int _activeRequests;
|
||||
private bool _disposed;
|
||||
@@ -270,6 +273,59 @@ public sealed partial class WebUntisClient : IAsyncDisposable
|
||||
Entities(entry, "ro"), entry.Clone())).ToList();
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Ruft den neuen, von der WebUntis-Weboberfläche verwendeten Stundenplan ab. Der
|
||||
/// kurzlebige Bearer wird aus der vorhandenen JSON-RPC-Sitzung erzeugt und nie persistiert.</summary>
|
||||
public Task<IReadOnlyList<UntisTimetableGridEntry>> GetTimetableGridAsync(int teacherId, int schoolYearId,
|
||||
DateOnly start, DateOnly end, CancellationToken cancellationToken) => WithSessionAsync(sessionId =>
|
||||
GetTimetableGridCoreAsync(sessionId, teacherId, schoolYearId, start, end, cancellationToken),
|
||||
cancellationToken);
|
||||
|
||||
public Task<IReadOnlyList<UntisTimetableGridEntry>> GetOwnTimetableGridAsync(int schoolYearId,
|
||||
DateOnly start, DateOnly end, CancellationToken cancellationToken) => WithSessionAsync(sessionId =>
|
||||
{
|
||||
var teacherId = _myTeacherUntisId
|
||||
?? throw new WebUntisException("WebUntis hat keine Lehrer-Kennung (personId) für diese Sitzung geliefert.");
|
||||
return GetTimetableGridCoreAsync(sessionId, teacherId, schoolYearId, start, end, cancellationToken);
|
||||
}, cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<UntisTimetableGridEntry>> GetTimetableGridCoreAsync(string sessionId,
|
||||
int teacherId, int schoolYearId, DateOnly start, DateOnly end, CancellationToken cancellationToken)
|
||||
{
|
||||
var bearer = await GetRestBearerTokenAsync(sessionId, cancellationToken);
|
||||
var configuration = GetConfiguration();
|
||||
var uri = $"https://{configuration.Host}/WebUntis/api/rest/view/v1/timetable/entries" +
|
||||
$"?start={start:yyyy-MM-dd}&end={end:yyyy-MM-dd}&format=1" +
|
||||
$"&resourceType=TEACHER&resources={teacherId}&periodTypes=" +
|
||||
"&timetableType=MY_TIMETABLE&layout=START_TIME";
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, uri);
|
||||
ApplyBrowserHeaders(request, configuration.Host);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
|
||||
request.Headers.Add("Cookie", SessionCookie(sessionId));
|
||||
if (_tenantId is not null) request.Headers.Add("tenant-id", _tenantId);
|
||||
request.Headers.Add("x-webuntis-api-school-year-id", schoolYearId.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
using var response = await SendAsync(request, TimeSpan.FromSeconds(20), cancellationToken);
|
||||
var payload = await ReadJsonAsync(response, cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new WebUntisException($"WebUntis-REST-Stundenplan fehlgeschlagen: {ErrorMessage(payload, response)}");
|
||||
if (!TryProperty(payload, "days", out var days) || days.ValueKind != JsonValueKind.Array)
|
||||
throw new WebUntisException("WebUntis hat keinen gültigen REST-Stundenplan geliefert.");
|
||||
if (TryProperty(payload, "errors", out var errors) && errors.ValueKind == JsonValueKind.Array &&
|
||||
errors.GetArrayLength() > 0)
|
||||
throw new WebUntisException("WebUntis hat Fehler im REST-Stundenplan gemeldet.");
|
||||
|
||||
var entries = new List<UntisTimetableGridEntry>();
|
||||
foreach (var day in days.EnumerateArray())
|
||||
{
|
||||
if (!TryProperty(day, "gridEntries", out var gridEntries) || gridEntries.ValueKind != JsonValueKind.Array)
|
||||
continue;
|
||||
foreach (var entry in gridEntries.EnumerateArray())
|
||||
entries.Add(ParseGridEntry(entry));
|
||||
}
|
||||
return (IReadOnlyList<UntisTimetableGridEntry>)entries;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<UntisClassRegisterEntry>> GetClassRegisterEntriesAsync(int studentId,
|
||||
int startDate, int endDate, CancellationToken cancellationToken) => WithSessionAsync(async sessionId =>
|
||||
{
|
||||
@@ -351,6 +407,8 @@ public sealed partial class WebUntisClient : IAsyncDisposable
|
||||
$"„{configuration.School}“ keine Sitzung geliefert. Bitte insbesondere Server und " +
|
||||
"Schulkennung mit der WebUntis-Anmeldeseite vergleichen.");
|
||||
_myTeacherUntisId = OptionalInt(result, "personId");
|
||||
_restBearerToken = null;
|
||||
_restBearerExpiresAt = default;
|
||||
await Task.Delay(PostLoginDelay, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -397,6 +455,8 @@ public sealed partial class WebUntisClient : IAsyncDisposable
|
||||
|
||||
sessionId = _sessionId;
|
||||
_sessionId = null;
|
||||
_restBearerToken = null;
|
||||
_restBearerExpiresAt = default;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -438,6 +498,124 @@ public sealed partial class WebUntisClient : IAsyncDisposable
|
||||
private TimeSpan SessionIdleTimeout =>
|
||||
TimeSpan.FromMinutes(Math.Clamp(_options.SessionIdleTimeoutMinutes, 1, 30));
|
||||
|
||||
private async Task<string> GetRestBearerTokenAsync(string sessionId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_restBearerToken is not null && _restBearerExpiresAt > DateTimeOffset.UtcNow.AddMinutes(1))
|
||||
return _restBearerToken;
|
||||
|
||||
var configuration = GetConfiguration();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
$"https://{configuration.Host}/WebUntis/api/token/new");
|
||||
ApplyBrowserHeaders(request, configuration.Host);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
request.Headers.Add("Cookie", SessionCookie(sessionId));
|
||||
if (_tenantId is not null) request.Headers.Add("tenant-id", _tenantId);
|
||||
using var response = await SendAsync(request, TimeSpan.FromSeconds(20), cancellationToken);
|
||||
var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
var payload = ParseJson(bytes);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new WebUntisException($"WebUntis-REST-Token fehlgeschlagen: {ErrorMessage(payload, response)}");
|
||||
|
||||
var token = payload.ValueKind == JsonValueKind.String ? payload.GetString()
|
||||
: OptionalString(payload, "token") ?? OptionalString(payload, "accessToken") ??
|
||||
OptionalString(payload, "access_token") ?? FindJwt(payload);
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
try { token = StrictUtf8.GetString(bytes).Trim().Trim('"'); }
|
||||
catch (DecoderFallbackException) { token = null; }
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(token) || token.Count(character => character == '.') != 2)
|
||||
throw new WebUntisException($"WebUntis hat keinen gültigen REST-Token geliefert ({TokenShape(payload)})." );
|
||||
_restBearerToken = token;
|
||||
_restBearerExpiresAt = ReadJwtExpiry(token) ?? DateTimeOffset.UtcNow.AddMinutes(10);
|
||||
return token;
|
||||
}
|
||||
|
||||
private static string? FindJwt(JsonElement value)
|
||||
{
|
||||
if (value.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var candidate = value.GetString();
|
||||
return candidate is not null && candidate.Count(character => character == '.') == 2
|
||||
? candidate
|
||||
: null;
|
||||
}
|
||||
if (value.ValueKind == JsonValueKind.Object)
|
||||
foreach (var property in value.EnumerateObject())
|
||||
if (FindJwt(property.Value) is { } token) return token;
|
||||
if (value.ValueKind == JsonValueKind.Array)
|
||||
foreach (var item in value.EnumerateArray())
|
||||
if (FindJwt(item) is { } token) return token;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string TokenShape(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Object => "Objekt: " + string.Join(", ", value.EnumerateObject()
|
||||
.Select(property => $"{property.Name}={TokenShape(property.Value)}")),
|
||||
JsonValueKind.Array => $"Array[{value.GetArrayLength()}]",
|
||||
JsonValueKind.String => $"Text[{value.GetString()?.Length ?? 0}]",
|
||||
_ => value.ValueKind.ToString(),
|
||||
};
|
||||
|
||||
private static DateTimeOffset? ReadJwtExpiry(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var parts = token.Split('.');
|
||||
if (parts.Length < 2) return null;
|
||||
var payload = parts[1].Replace('-', '+').Replace('_', '/');
|
||||
payload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
|
||||
using var json = JsonDocument.Parse(Convert.FromBase64String(payload));
|
||||
return json.RootElement.TryGetProperty("exp", out var exp) && exp.TryGetInt64(out var seconds)
|
||||
? DateTimeOffset.FromUnixTimeSeconds(seconds)
|
||||
: null;
|
||||
}
|
||||
catch (Exception exception) when (exception is FormatException or JsonException or ArgumentOutOfRangeException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static UntisTimetableGridEntry ParseGridEntry(JsonElement entry)
|
||||
{
|
||||
if (!TryProperty(entry, "duration", out var duration) || duration.ValueKind != JsonValueKind.Object ||
|
||||
!TryGridDateTime(duration, "start", out var start) || !TryGridDateTime(duration, "end", out var end))
|
||||
throw new WebUntisException("WebUntis-REST-GridEntry hat keine gültige Zeitspanne.");
|
||||
var type = OptionalString(entry, "type")
|
||||
?? throw new WebUntisException("WebUntis-REST-GridEntry hat keinen Typ.");
|
||||
var resources = new List<UntisGridResourceChange>();
|
||||
for (var position = 1; position <= 7; position++)
|
||||
{
|
||||
if (!TryProperty(entry, $"position{position}", out var values) || values.ValueKind != JsonValueKind.Array)
|
||||
continue;
|
||||
foreach (var value in values.EnumerateArray())
|
||||
resources.Add(new UntisGridResourceChange(ParseGridResource(value, "current"),
|
||||
ParseGridResource(value, "removed")));
|
||||
}
|
||||
return new UntisTimetableGridEntry(IntArray(entry, "ids"), start, end, type,
|
||||
OptionalString(entry, "status"), OptionalString(entry, "statusDetail"), OptionalString(entry, "name"),
|
||||
OptionalString(entry, "lessonText"), OptionalString(entry, "lessonInfo"),
|
||||
OptionalString(entry, "substitutionText"), resources, entry.Clone());
|
||||
}
|
||||
|
||||
private static UntisGridResource? ParseGridResource(JsonElement parent, string property)
|
||||
{
|
||||
if (!TryProperty(parent, property, out var value) || value.ValueKind != JsonValueKind.Object) return null;
|
||||
var type = OptionalString(value, "type");
|
||||
return type is null ? null : new UntisGridResource(type, OptionalString(value, "status"),
|
||||
OptionalString(value, "shortName"), OptionalString(value, "longName"),
|
||||
OptionalString(value, "displayName"));
|
||||
}
|
||||
|
||||
private static bool TryGridDateTime(JsonElement parent, string property, out DateTime value)
|
||||
{
|
||||
value = default;
|
||||
return OptionalString(parent, property) is { } text && DateTime.TryParseExact(text,
|
||||
["yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd'T'HH:mm:ss"], CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None, out value);
|
||||
}
|
||||
|
||||
private async Task<JsonElement> RpcAsync(string method, object parameters, string? sessionId,
|
||||
CancellationToken cancellationToken, Action<HttpResponseMessage>? onResponse = null)
|
||||
{
|
||||
|
||||
@@ -135,6 +135,43 @@ public sealed record UntisTimetablePeriod(
|
||||
IReadOnlyList<UntisEntity> Rooms,
|
||||
JsonElement Raw);
|
||||
|
||||
/// <summary>Eine Ressource innerhalb eines Eintrags des neuen WebUntis-Stundenplans. Bei
|
||||
/// Vertretungen kann <see cref="UntisGridResourceChange.Removed"/> die ursprüngliche und
|
||||
/// <see cref="UntisGridResourceChange.Current"/> die tatsächliche Belegung enthalten.</summary>
|
||||
public sealed record UntisGridResource(
|
||||
string Type,
|
||||
string? Status,
|
||||
string? ShortName,
|
||||
string? LongName,
|
||||
string? DisplayName);
|
||||
|
||||
public sealed record UntisGridResourceChange(
|
||||
UntisGridResource? Current,
|
||||
UntisGridResource? Removed);
|
||||
|
||||
/// <summary>Typisierter GridEntry aus der REST-Schnittstelle, mit der auch die WebUntis-Webseite
|
||||
/// ihren Stundenplan aufbaut. Anders als der iCal-Export enthält sie explizite Typen wie
|
||||
/// NORMAL_TEACHING_PERIOD, ADDITIONAL_PERIOD, BREAK_SUPERVISION und EXAM.</summary>
|
||||
public sealed record UntisTimetableGridEntry(
|
||||
IReadOnlyList<int> Ids,
|
||||
DateTime Start,
|
||||
DateTime End,
|
||||
string Type,
|
||||
string? Status,
|
||||
string? StatusDetail,
|
||||
string? Name,
|
||||
string? LessonText,
|
||||
string? LessonInfo,
|
||||
string? SubstitutionText,
|
||||
IReadOnlyList<UntisGridResourceChange> Resources,
|
||||
JsonElement Raw)
|
||||
{
|
||||
public IReadOnlyList<UntisGridResource> CurrentResources => Resources
|
||||
.Where(change => change.Current is not null).Select(change => change.Current!).ToList();
|
||||
public IReadOnlyList<UntisGridResource> RemovedResources => Resources
|
||||
.Where(change => change.Removed is not null).Select(change => change.Removed!).ToList();
|
||||
}
|
||||
|
||||
public sealed record UntisLessonAbsence(
|
||||
string StudentName,
|
||||
int Date,
|
||||
|
||||
Reference in new issue
Block a user