Skip to content

Commit

Permalink
Adjusted some more code to new name
Browse files Browse the repository at this point in the history
  • Loading branch information
rschili committed Dec 25, 2024
1 parent 87036cd commit b0223ac
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 65 deletions.
12 changes: 9 additions & 3 deletions src/Narrensicher.Matrix.Console/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Narrensicher.Matrix;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Narrensicher.Matrix.Models;

// load environment variables or a .env file
DotNetEnv.Env.TraversePath().Load();
Expand All @@ -27,10 +28,10 @@

try
{
var client = await MatrixClientCore.ConnectAsync(userid, password, device,
var client = await MatrixTextClient.ConnectAsync(userid, password, device,
services.GetRequiredService<IHttpClientFactory>(), cancellationTokenSource.Token,
services.GetRequiredService<ILogger<MatrixClientCore>>());
await client.SyncAsync();
services.GetRequiredService<ILogger<MatrixTextClient>>());
await client.SyncAsync(MessageReceived);
Console.WriteLine("Sync has ended.");
}
catch (OperationCanceledException)
Expand All @@ -44,4 +45,9 @@
finally
{
await services.DisposeAsync();
}

Task MessageReceived(MatrixTextMessage message)
{
return Task.CompletedTask;
}
68 changes: 34 additions & 34 deletions src/Narrensicher.Matrix/EventDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,31 @@ public EventDispatcher(ILogger logger)
Logger = logger ?? NullLogger<EventDispatcher>.Instance;
}

public async Task HandleSyncReceivedAsync(MatrixClientCore client, SyncResponse syncResponse)
public async Task HandleSyncReceivedAsync(SyncResponse syncResponse)
{
try
{
await HandleSyncReceivedInternalAsync(client, syncResponse).ConfigureAwait(false);
await HandleSyncReceivedInternalAsync(syncResponse).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error handling sync response");
}
}

private async Task HandleSyncReceivedInternalAsync(MatrixClientCore client, SyncResponse syncResponse)
private async Task HandleSyncReceivedInternalAsync(SyncResponse syncResponse)
{
if (syncResponse == null)
return;

if (syncResponse.AccountData != null)
{
await HandleAccountDataReceivedAsync(client, null, syncResponse.AccountData).ConfigureAwait(false);
await HandleAccountDataReceivedAsync(null, syncResponse.AccountData).ConfigureAwait(false);
}

if (syncResponse.Presence != null)
{
await HandlePresenceReceivedAsync(client, syncResponse.Presence).ConfigureAwait(false);
await HandlePresenceReceivedAsync(syncResponse.Presence).ConfigureAwait(false);
}

if (syncResponse.Rooms != null)
Expand All @@ -54,27 +54,27 @@ private async Task HandleSyncReceivedInternalAsync(MatrixClientCore client, Sync
continue;
}

await HandleRoomSummaryReceivedAsync(client, roomId, pair.Value.Summary).ConfigureAwait(false);
await HandleAccountDataReceivedAsync(client, roomId, pair.Value.AccountData).ConfigureAwait(false);
await HandleEphemeralReceivedAsync(client, roomId, pair.Value.Ephemeral).ConfigureAwait(false);
await HandleStateReceivedAsync(client, roomId, pair.Value.State).ConfigureAwait(false);
await HandleTimelineReceivedAsync(client, roomId, pair.Value.Timeline).ConfigureAwait(false);
await HandleRoomSummaryReceivedAsync(roomId, pair.Value.Summary).ConfigureAwait(false);
await HandleAccountDataReceivedAsync(roomId, pair.Value.AccountData).ConfigureAwait(false);
await HandleEphemeralReceivedAsync(roomId, pair.Value.Ephemeral).ConfigureAwait(false);
await HandleStateReceivedAsync(roomId, pair.Value.State).ConfigureAwait(false);
await HandleTimelineReceivedAsync(roomId, pair.Value.Timeline).ConfigureAwait(false);
} // foreach joined room
} // if joined
} // if rooms
}

private async Task HandleRoomSummaryReceivedAsync(MatrixClientCore client, MatrixId roomId, RoomSummary? summary)
private async Task HandleRoomSummaryReceivedAsync(MatrixId roomId, RoomSummary? summary)
{
if (summary == null || summary.Heroes == null || RoomSummaryReceived == null)
return;

var users = summary.Heroes.Select(s => UserId.TryParse(s, out MatrixId? userId) ? userId : null)
.Where(id => id != null).Select(id => id!).ToList();
await RoomSummaryReceived(client, roomId, users!).ConfigureAwait(false);
await RoomSummaryReceived(roomId, users!).ConfigureAwait(false);
}

private async Task HandleStateReceivedAsync(MatrixClientCore client, MatrixId roomId, ClientEventWithoutRoomIdResponse? state)
private async Task HandleStateReceivedAsync(MatrixId roomId, ClientEventWithoutRoomIdResponse? state)
{
if (state == null || state.Events == null)
return;
Expand Down Expand Up @@ -116,7 +116,7 @@ private async Task HandleStateReceivedAsync(MatrixClientCore client, MatrixId ro
continue;
}

await RoomMemberReceived(client, roomId, userId, displayName, membership).ConfigureAwait(false);
await RoomMemberReceived(roomId, userId, displayName, membership).ConfigureAwait(false);
}
else if (e.Type == "m.space.child")
{ } // ignore for now. Room hierarchy is not implemented
Expand All @@ -141,7 +141,7 @@ private async Task HandleStateReceivedAsync(MatrixClientCore client, MatrixId ro
continue;
}

await CanonicalAliasReceived(client, roomId, alias).ConfigureAwait(false);
await CanonicalAliasReceived(roomId, alias).ConfigureAwait(false);
}
else if (e.Type == "m.room.name")
{
Expand All @@ -160,7 +160,7 @@ private async Task HandleStateReceivedAsync(MatrixClientCore client, MatrixId ro
continue;
}

await RoomNameReceived(client, roomId, name).ConfigureAwait(false);
await RoomNameReceived(roomId, name).ConfigureAwait(false);
} // ignore for now.
else if (e.Type == "m.room.topic")
{ } // ignore for now.
Expand All @@ -177,7 +177,7 @@ private async Task HandleStateReceivedAsync(MatrixClientCore client, MatrixId ro
}
}

private async Task HandleTimelineReceivedAsync(MatrixClientCore client, MatrixId roomId, TimelineEventResponse? timeline)
private async Task HandleTimelineReceivedAsync(MatrixId roomId, TimelineEventResponse? timeline)
{
if (timeline == null || timeline.Events == null)
return;
Expand Down Expand Up @@ -248,7 +248,7 @@ private async Task HandleTimelineReceivedAsync(MatrixClientCore client, MatrixId
}
}

private async Task HandlePresenceReceivedAsync(MatrixClientCore client, EventResponse presenceEvents)
private async Task HandlePresenceReceivedAsync(EventResponse presenceEvents)
{
if (PresenceReceived == null || presenceEvents.Events == null)
return;
Expand All @@ -274,25 +274,25 @@ private async Task HandlePresenceReceivedAsync(MatrixClientCore client, EventRes
continue;
}
var content = JsonSerializer.Deserialize<Presence>((JsonElement)presence.Content);
await PresenceReceived(client, userId, content).ConfigureAwait(false);
await PresenceReceived(userId, content).ConfigureAwait(false);
}
}

private async Task HandleAccountDataReceivedAsync(MatrixClientCore client, MatrixId? roomId, EventResponse? accountData)
private async Task HandleAccountDataReceivedAsync(MatrixId? roomId, EventResponse? accountData)
{
if (accountData != null && accountData.Events != null)
{
foreach (var e in accountData.Events)
{
if (roomId != null && RoomAccountDataReceived != null)
await RoomAccountDataReceived(client, roomId, e.Type, e.Content).ConfigureAwait(false);
await RoomAccountDataReceived(roomId, e.Type, e.Content).ConfigureAwait(false);
else if (GlobalAccountDataReceived != null)
await GlobalAccountDataReceived(client, e.Type, e.Content).ConfigureAwait(false);
await GlobalAccountDataReceived(e.Type, e.Content).ConfigureAwait(false);
}
}
}

private async Task HandleEphemeralReceivedAsync(MatrixClientCore client, MatrixId roomId, EventResponse? eph)
private async Task HandleEphemeralReceivedAsync(MatrixId roomId, EventResponse? eph)
{
if (eph != null && eph.Events != null)
{
Expand All @@ -313,7 +313,7 @@ private async Task HandleEphemeralReceivedAsync(MatrixClientCore client, MatrixI
.Select(s => UserId.TryParse(s, out MatrixId? userId) ? userId : null)
.Where(id => id != null).Select(id => id!).ToList();

await TypingReceived(client, roomId, typingUsers).ConfigureAwait(false);
await TypingReceived(roomId, typingUsers).ConfigureAwait(false);
}
else
Logger.LogWarning("Received typing event with invalid user_ids structure");
Expand Down Expand Up @@ -353,7 +353,7 @@ private async Task HandleEphemeralReceivedAsync(MatrixClientCore client, MatrixI
threadId = tid.GetString();
}

await ReceiptReceived(client, roomId, eventId, userId, threadId).ConfigureAwait(false);
await ReceiptReceived(roomId, eventId, userId, threadId).ConfigureAwait(false);
}
}
} // else if receipt
Expand All @@ -363,32 +363,32 @@ private async Task HandleEphemeralReceivedAsync(MatrixClientCore client, MatrixI
} // if ephemeral
}

public delegate Task GlobalAccountDataHandler(MatrixClientCore client, string type, JsonElement? content);
public delegate Task GlobalAccountDataHandler(string type, JsonElement? content);
public GlobalAccountDataHandler? GlobalAccountDataReceived;

public delegate Task RoomAccountDataHandler(MatrixClientCore client, MatrixId room, string type, JsonElement? content);
public delegate Task RoomAccountDataHandler(MatrixId room, string type, JsonElement? content);
public RoomAccountDataHandler? RoomAccountDataReceived;

public delegate Task PresenceHandler(MatrixClientCore client, MatrixId sender, Presence presence);
public delegate Task PresenceHandler(MatrixId sender, Presence presence);
public PresenceHandler? PresenceReceived;

public delegate Task TypingHandler(MatrixClientCore client, MatrixId room, List<MatrixId> typingUsers);
public delegate Task TypingHandler(MatrixId room, List<MatrixId> typingUsers);
public TypingHandler? TypingReceived;

public delegate Task ReceiptHandler(MatrixClientCore client, MatrixId room, MatrixId eventId, MatrixId userId, string? threadId);
public delegate Task ReceiptHandler(MatrixId room, MatrixId eventId, MatrixId userId, string? threadId);

public ReceiptHandler? ReceiptReceived;

public delegate Task RoomSummaryHandler(MatrixClientCore client, MatrixId room, List<MatrixId> users);
public delegate Task RoomSummaryHandler(MatrixId room, List<MatrixId> users);
public RoomSummaryHandler? RoomSummaryReceived;

public delegate Task StateHandler(MatrixClientCore client, MatrixId room, MatrixId userId, string displayName, string membership);
public delegate Task StateHandler(MatrixId room, MatrixId userId, string displayName, string membership);
public StateHandler? RoomMemberReceived;

public delegate Task CanonicalAliasHandler(MatrixClientCore client, MatrixId room, string alias);
public delegate Task CanonicalAliasHandler(MatrixId room, string alias);
public CanonicalAliasHandler? CanonicalAliasReceived;

public delegate Task RoomNameHandler(MatrixClientCore client, MatrixId room, string name);
public delegate Task RoomNameHandler(MatrixId room, string name);
public RoomNameHandler? RoomNameReceived;

public delegate Task MessageHandler(MatrixId room, MatrixId sender, string eventId, string body, List<MatrixId>? mentions);
Expand Down
24 changes: 12 additions & 12 deletions src/Narrensicher.Matrix/MatrixClientCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@ namespace Narrensicher.Matrix;
/// <summary>
/// The low level class for interacting with the Matrix server.
/// </summary>
public sealed class MatrixClientCore
internal sealed class MatrixClientCore
{
public ILogger Logger => HttpClientParameters.Logger;
public MatrixId User { get; }
public IList<SpecVersion> SupportedSpecVersions { get; }
public static SpecVersion CurrentSpecVersion { get; } = new SpecVersion(1, 12, null, null);
internal ILogger Logger => HttpClientParameters.Logger;
internal MatrixId User { get; }
internal IList<SpecVersion> SupportedSpecVersions { get; }
internal static SpecVersion CurrentSpecVersion { get; } = new SpecVersion(1, 12, null, null);
internal HttpClientParameters HttpClientParameters { get; private set; }
public Capabilities ServerCapabilities { get; private set; }
internal Capabilities ServerCapabilities { get; private set; }

public delegate Task SyncReceivedHandler(SyncResponse matrixEvent);
internal delegate Task SyncReceivedHandler(SyncResponse matrixEvent);

/// <summary>
/// Gets the filter applied to the connection. At first it is null. Set it using SetFilterAsync method.
/// </summary>
public Filter? Filter { get; private set; }
internal Filter? Filter { get; private set; }

internal MatrixClientCore(HttpClientParameters parameters,
MatrixId userId,
Expand All @@ -37,7 +37,7 @@ internal MatrixClientCore(HttpClientParameters parameters,
ServerCapabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities));
}

public static async Task<MatrixClientCore> ConnectAsync(string userId, string password, string deviceId, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken, ILogger? logger = null)
internal static async Task<MatrixClientCore> ConnectAsync(string userId, string password, string deviceId, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken, ILogger? logger = null)
{
if (logger == null)
logger = NullLogger<MatrixClientCore>.Instance;
Expand Down Expand Up @@ -135,7 +135,7 @@ public static async Task<MatrixClientCore> ConnectAsync(string userId, string pa
return client;
}

public async Task<Filter> SetFilterAsync(Filter filter)
internal async Task<Filter> SetFilterAsync(Filter filter)
{
Logger.LogInformation("Setting filter new filter");
var filterResponse = await MatrixHelper.PostFilterAsync(HttpClientParameters, User, filter).ConfigureAwait(false);
Expand Down Expand Up @@ -165,7 +165,7 @@ public async Task<Filter> SetFilterAsync(Filter filter)
/// </summary>
/// <param name="handler">optional handler for incoming events, default writes events to logger</param>
/// <returns></returns>
public async Task SyncAsync(SyncReceivedHandler? handler = null)
internal async Task SyncAsync(SyncReceivedHandler? handler = null)
{
if (handler == null)
handler = DefaultSyncReceivedHandler;
Expand All @@ -188,7 +188,7 @@ public async Task SyncAsync(SyncReceivedHandler? handler = null)
}
}

public Task DefaultSyncReceivedHandler(SyncResponse response)
internal Task DefaultSyncReceivedHandler(SyncResponse response)
{
Logger.LogInformation("Received sync response but no handler is set.");
return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@ namespace Narrensicher.Matrix;
/// <summary>
/// The low level class for interacting with the Matrix server.
/// </summary>
public sealed class MatrixClient
public sealed class MatrixTextClient
{
public MatrixClientCore Core { get; private init; }
public ILogger Logger => Core.Logger;
public MatrixId User => Core.User;
internal MatrixClientCore Core { get; private init; }
private ILogger Logger => Core.Logger;
public MatrixId CurrentUser => Core.User;

public delegate Task MessageHandler(MatrixTextMessage message);

private MessageHandler _messageHandler;
private MessageHandler? _messageHandler = null; // We use this to track if the sync has been started

private MatrixClient(MatrixClientCore core)
private MatrixTextClient(MatrixClientCore core)
{
Core = core ?? throw new ArgumentNullException(nameof(core));
}

public static async Task<MatrixClient> ConnectAsync(string userId, string password, string deviceId, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken, ILogger? logger = null)
public static async Task<MatrixTextClient> ConnectAsync(string userId, string password, string deviceId, IHttpClientFactory httpClientFactory, CancellationToken cancellationToken, ILogger? logger = null)
{
var core = await MatrixClientCore.ConnectAsync(userId, password, deviceId, httpClientFactory, cancellationToken, logger).ConfigureAwait(false);
var client = new MatrixClient(core);
var client = new MatrixTextClient(core);
return client;
}

Expand All @@ -40,12 +40,12 @@ public async Task SyncAsync(MessageHandler handler)
await Core.SyncAsync(HandleSyncResponse).ConfigureAwait(false);
}

public async Task HandleSyncResponse(SyncResponse response)
private async Task HandleSyncResponse(SyncResponse response)
{
MatrixTextMessage message = new();
try
{
await _messageHandler(message).ConfigureAwait(false);
await _messageHandler!(message).ConfigureAwait(false);
}
catch(TaskCanceledException)
{
Expand Down
8 changes: 2 additions & 6 deletions src/Narrensicher.Matrix/Models/MatrixTextMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ namespace Narrensicher.Matrix.Models;

public class MatrixTextMessage
{
public string Content { get; set; }
public string Sender { get; set; }
public string RoomId { get; set; }
public string MessageId { get; set; }
public string Timestamp { get; set; }
public string MessageType { get; set; }
public string? Body { get; set; }

}

0 comments on commit b0223ac

Please sign in to comment.