diff --git a/docs/auriondocs/Agent/README.md b/docs/auriondocs/Agent/README.md new file mode 100644 index 0000000..8fa04b5 --- /dev/null +++ b/docs/auriondocs/Agent/README.md @@ -0,0 +1,18 @@ +# Agent Context Pack — HueByte/EchoHub + +Machine-oriented context for AI coding agents, generated deterministically from +the repository's symbol graph (no LLM involved). Reading this pack instead of +scanning the source tree saves tokens: one map read plus targeted doc lookups +replaces repeated file reads and greps. + +| File | What it is | When to read it | +|---|---|---| +| [repo-map](repo-map.md) | Subsystem map + most-connected symbols | First — orientation | +| [symbol-graph.json](symbol-graph.json) | Full queryable symbol graph (kind, file, subsystem, complexity, dependencies, doc path) | To trace exact dependencies or find a symbol | +| `../Code/**` | Per-file generated documentation | For the behaviour of a specific file | +| `../Synthesis/Architecture.md` | Cross-cutting architecture narrative + diagram | For the big picture | + +Suggested workflow: read `repo-map.md`; locate the symbols relevant to your task in +`symbol-graph.json` (each carries a `doc` path and `dependsOn` edges); open only +those docs/sources. The pack is regenerated on every full documentation run, so it +matches the commit recorded in the graph's `commit` field. diff --git a/docs/auriondocs/Agent/repo-map.md b/docs/auriondocs/Agent/repo-map.md new file mode 100644 index 0000000..04dc773 --- /dev/null +++ b/docs/auriondocs/Agent/repo-map.md @@ -0,0 +1,188 @@ +# Repo Map — HueByte/EchoHub + +> Deterministic structural map generated for AI agents. Read this file for +> orientation, query [`symbol-graph.json`](symbol-graph.json) for exact +> dependencies, and open the linked per-file docs for behaviour — instead of +> scanning the source tree. + +Commit `4dcb480d1d43e4efaaa9b2e190c7275fcab94d23` · 201 symbols · 128 files · 648 dependency edges + +## Subsystems + +*Structural clusters detected from the dependency graph — groups of symbols more densely wired to each other than to the rest of the codebase.* + +### src/EchoHub.Core/DTOs · ChatService + +23 symbols across 14 files. Key symbols (by connectivity): + +- [`ChatService`](../Code/src/EchoHub.Server/Services/ChatService.cs.md) (class) — `src/EchoHub.Server/Services/ChatService.cs` +- [`MessageDto`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`UserStatus`](../Code/src/EchoHub.Core/Models/UserStatus.cs.md) (enum) — `src/EchoHub.Core/Models/UserStatus.cs` +- [`EchoHubConnection`](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) (class) — `src/EchoHub.Client/Services/EchoHubConnection.cs` +- [`ChannelDto`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`UserPresenceDto`](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ProfileDtos.cs` +- [`ChatHub`](../Code/src/EchoHub.Server/Hubs/ChatHub.cs.md) (class) — `src/EchoHub.Server/Hubs/ChatHub.cs` +- [`IChatService`](../Code/src/EchoHub.Core/Contracts/IChatService.cs.md) (interface) — `src/EchoHub.Core/Contracts/IChatService.cs` +- *…and 15 more (see symbol-graph.json)* + +### src/EchoHub.Client/Services · AppOrchestrator + +21 symbols across 16 files. Key symbols (by connectivity): + +- [`AppOrchestrator`](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) (class) — `src/EchoHub.Client/AppOrchestrator.cs` +- [`ConnectionManager`](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) (class) — `src/EchoHub.Client/Services/ConnectionManager.cs` +- [`RefreshToken`](../Code/src/EchoHub.Core/Models/RefreshToken.cs.md) (class) — `src/EchoHub.Core/Models/RefreshToken.cs` +- [`ConnectResult`](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) (record) — `src/EchoHub.Client/Services/ConnectionManager.cs` +- [`CommandHandler`](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) (class) — `src/EchoHub.Client/Commands/CommandHandler.cs` +- [`LoginResponse`](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/AuthDtos.cs` +- [`JoinOutcome`](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) (record) — `src/EchoHub.Client/Services/EchoHubConnection.cs` +- [`ChannelPasswordRequiredException`](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) (class) — `src/EchoHub.Client/Services/EchoHubConnection.cs` +- *…and 13 more (see symbol-graph.json)* + +### src/EchoHub.Client/UI · MainWindow + +21 symbols across 18 files. Key symbols (by connectivity): + +- [`MainWindow`](../Code/src/EchoHub.Client/UI/MainWindow.cs.md) (class) — `src/EchoHub.Client/UI/MainWindow.cs` +- [`ChatMessageManager`](../Code/src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md) (class) — `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +- [`ChatLine`](../Code/src/EchoHub.Client/UI/Chat/ChatLine.cs.md) (class) — `src/EchoHub.Client/UI/Chat/ChatLine.cs` +- [`ProfileViewDialog`](../Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md) (class) — `src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs` +- [`AttachmentKind`](../Code/src/EchoHub.Core/Models/AttachmentKind.cs.md) (enum) — `src/EchoHub.Core/Models/AttachmentKind.cs` +- [`ChatColors`](../Code/src/EchoHub.Client/UI/Chat/ChatColors.cs.md) (class) — `src/EchoHub.Client/UI/Chat/ChatColors.cs` +- [`ChatSegment`](../Code/src/EchoHub.Client/UI/Chat/ChatSegment.cs.md) (record) — `src/EchoHub.Client/UI/Chat/ChatSegment.cs` +- [`ChatListSource`](../Code/src/EchoHub.Client/UI/Chat/ChatListSource.cs.md) (class) — `src/EchoHub.Client/UI/Chat/ChatListSource.cs` +- *…and 13 more (see symbol-graph.json)* + +### src/EchoHub.Core/DTOs · ApiClient + +19 symbols across 11 files. Key symbols (by connectivity): + +- [`ApiClient`](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) (class) — `src/EchoHub.Client/Services/ApiClient.cs` +- [`ModerationController`](../Code/src/EchoHub.Server/Controllers/ModerationController.cs.md) (class) — `src/EchoHub.Server/Controllers/ModerationController.cs` +- [`ServerStatsCollector`](../Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md) (class) — `src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs` +- [`RefreshRequest`](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/AuthDtos.cs` +- [`AssignRoleRequest`](../Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ModerationDtos.cs` +- [`UpdateProfileRequest`](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ProfileDtos.cs` +- [`AvatarHelper`](../Code/src/EchoHub.Client/Services/AvatarHelper.cs.md) (class) — `src/EchoHub.Client/Services/AvatarHelper.cs` +- [`OutgoingAttachment`](../Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md) (record) — `src/EchoHub.Client/Services/OutgoingAttachment.cs` +- *…and 11 more (see symbol-graph.json)* + +### src/EchoHub.Server · User + +17 symbols across 15 files. Key symbols (by connectivity): + +- [`User`](../Code/src/EchoHub.Core/Models/User.cs.md) (class) — `src/EchoHub.Core/Models/User.cs` +- [`UsersController`](../Code/src/EchoHub.Server/Controllers/UsersController.cs.md) (class) — `src/EchoHub.Server/Controllers/UsersController.cs` +- [`EchoHubDbContext`](../Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md) (class) — `src/EchoHub.Server/Data/EchoHubDbContext.cs` +- [`ServerRole`](../Code/src/EchoHub.Core/Models/ServerRole.cs.md) (enum) — `src/EchoHub.Core/Models/ServerRole.cs` +- [`AuthController`](../Code/src/EchoHub.Server/Controllers/AuthController.cs.md) (class) — `src/EchoHub.Server/Controllers/AuthController.cs` +- [`UserProfileDto`](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ProfileDtos.cs` +- [`UserService`](../Code/src/EchoHub.Server/Services/UserService.cs.md) (class) — `src/EchoHub.Server/Services/UserService.cs` +- [`IUserService`](../Code/src/EchoHub.Core/Contracts/IUserService.cs.md) (interface) — `src/EchoHub.Core/Contracts/IUserService.cs` +- *…and 9 more (see symbol-graph.json)* + +### src/EchoHub.Core/DTOs · ChannelService + +13 symbols across 9 files. Key symbols (by connectivity): + +- [`ChannelService`](../Code/src/EchoHub.Server/Services/ChannelService.cs.md) (class) — `src/EchoHub.Server/Services/ChannelService.cs` +- [`IrcCommandHandler`](../Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md) (class) — `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +- [`IChannelService`](../Code/src/EchoHub.Core/Contracts/IChannelService.cs.md) (interface) — `src/EchoHub.Core/Contracts/IChannelService.cs` +- [`ChannelOperationResult`](../Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/CommonDtos.cs` +- [`FakeChannelService`](../Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md) (class) — `src/EchoHub.Tests/Irc/TestHelpers.cs` +- [`ValidationConstants`](../Code/src/EchoHub.Core/Constants/ValidationConstants.cs.md) (class) — `src/EchoHub.Core/Constants/ValidationConstants.cs` +- [`ChannelCryptoDto`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`ChannelError`](../Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md) (enum) — `src/EchoHub.Core/DTOs/CommonDtos.cs` +- *…and 5 more (see symbol-graph.json)* + +### src/EchoHub.Server · Program + +13 symbols across 12 files. Key symbols (by connectivity): + +- [`Program`](../Code/src/EchoHub.Server/Program.cs.md) (file) — `src/EchoHub.Server/Program.cs` +- [`HubConstants`](../Code/src/EchoHub.Core/Constants/HubConstants.cs.md) (class) — `src/EchoHub.Core/Constants/HubConstants.cs` +- [`PresenceTracker`](../Code/src/EchoHub.Server/Services/PresenceTracker.cs.md) (class) — `src/EchoHub.Server/Services/PresenceTracker.cs` +- [`ImageToAsciiService`](../Code/src/EchoHub.Core/Services/ImageToAsciiService.cs.md) (class) — `src/EchoHub.Core/Services/ImageToAsciiService.cs` +- [`UploadLimits`](../Code/src/EchoHub.Server/Config/UploadLimits.cs.md) (class) — `src/EchoHub.Server/Config/UploadLimits.cs` +- [`DatabaseSetup`](../Code/src/EchoHub.Server/Setup/DatabaseSetup.cs.md) (class) — `src/EchoHub.Server/Setup/DatabaseSetup.cs` +- [`DirectoryClaimStore`](../Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md) (class) — `src/EchoHub.Server/Services/DirectoryClaimStore.cs` +- [`LinkEmbedService`](../Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md) (class) — `src/EchoHub.Server/Services/LinkEmbedService.cs` +- *…and 5 more (see symbol-graph.json)* + +### src/EchoHub.Client/Config + +7 symbols across 5 files. Key symbols (by connectivity): + +- [`RoomKeyStore`](../Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md) (class) — `src/EchoHub.Client/Services/RoomKeyStore.cs` +- [`ClientConfig`](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) (class) — `src/EchoHub.Client/Config/ClientConfig.cs` +- [`SavedServer`](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) (class) — `src/EchoHub.Client/Config/ClientConfig.cs` +- [`RoomCrypto`](../Code/src/EchoHub.Core/Security/RoomCrypto.cs.md) (class) — `src/EchoHub.Core/Security/RoomCrypto.cs` +- [`ConfigManager`](../Code/src/EchoHub.Client/Config/ConfigManager.cs.md) (class) — `src/EchoHub.Client/Config/ConfigManager.cs` +- [`RoomKeyProtector`](../Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md) (class) — `src/EchoHub.Client/Services/RoomKeyProtector.cs` +- [`AccountPreset`](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) (class) — `src/EchoHub.Client/Config/ClientConfig.cs` + +### src/EchoHub.Server · ServerDirectoryService + +7 symbols across 1 files. Key symbols (by connectivity): + +- [`ServerDirectoryService`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (class) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`ErrorDetail`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (record) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`Response`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (record) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`DirectoryProtocol`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (class) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`DirectoryRegistrationErrors`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (class) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`RegisterServerDto`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (record) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` +- [`RegisterServerResult`](../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) (record) — `src/EchoHub.Server/Services/ServerDirectoryService.cs` + +### src/EchoHub.Client/UI · Channel + +6 symbols across 4 files. Key symbols (by connectivity): + +- [`Channel`](../Code/src/EchoHub.Core/Models/Channel.cs.md) (class) — `src/EchoHub.Core/Models/Channel.cs` +- [`SearchDialog`](../Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md) (class) — `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +- [`SearchResultType`](../Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md) (enum) — `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +- [`SearchListSource`](../Code/src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md) (class) — `src/EchoHub.Client/UI/ListSources/SearchListSource.cs` +- [`SearchResult`](../Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md) (record) — `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +- [`IrcNumericReply`](../Code/src/EchoHub.Server.Irc/IrcNumericReply.cs.md) (class) — `src/EchoHub.Server.Irc/IrcNumericReply.cs` + +### src/EchoHub.Core/DTOs · ChannelsController + +6 symbols across 3 files. Key symbols (by connectivity): + +- [`ChannelsController`](../Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md) (class) — `src/EchoHub.Server/Controllers/ChannelsController.cs` +- [`RekeyChannelRequest`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`FileValidationHelper`](../Code/src/EchoHub.Core/Services/FileValidationHelper.cs.md) (class) — `src/EchoHub.Core/Services/FileValidationHelper.cs` +- [`CreateChannelRequest`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`SendUrlRequest`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` +- [`UpdateTopicRequest`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/ChatDtos.cs` + +### src/EchoHub.Core/Models + +6 symbols across 6 files. Key symbols (by connectivity): + +- [`Message`](../Code/src/EchoHub.Core/Models/Message.cs.md) (class) — `src/EchoHub.Core/Models/Message.cs` +- [`DataMigrationService`](../Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md) (class) — `src/EchoHub.Server/Setup/DataMigrationService.cs` +- [`Attachment`](../Code/src/EchoHub.Core/Models/Attachment.cs.md) (class) — `src/EchoHub.Core/Models/Attachment.cs` +- [`AsyncRunner`](../Code/src/EchoHub.Client/Services/AsyncRunner.cs.md) (class) — `src/EchoHub.Client/Services/AsyncRunner.cs` +- [`MessageType`](../Code/src/EchoHub.Core/Models/MessageType.cs.md) (enum) — `src/EchoHub.Core/Models/MessageType.cs` +- [`ApiResponse`](../Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md) (record) — `src/EchoHub.Core/DTOs/CommonDtos.cs` + +*…and 12 smaller subsystems (see symbol-graph.json).* + +## Most connected symbols + +The load-bearing symbols — changes here have the widest blast radius. + +| Symbol | Kind | Used by | Uses | File | +|---|---|---|---|---| +| [`AppOrchestrator`](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) | class | 3 | 47 | `src/EchoHub.Client/AppOrchestrator.cs` | +| [`Program`](../Code/src/EchoHub.Server/Program.cs.md) | file | 0 | 34 | `src/EchoHub.Server/Program.cs` | +| [`ApiClient`](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) | class | 3 | 29 | `src/EchoHub.Client/Services/ApiClient.cs` | +| [`ChatService`](../Code/src/EchoHub.Server/Services/ChatService.cs.md) | class | 2 | 29 | `src/EchoHub.Server/Services/ChatService.cs` | +| [`Channel`](../Code/src/EchoHub.Core/Models/Channel.cs.md) | class | 29 | 1 | `src/EchoHub.Core/Models/Channel.cs` | +| [`MainWindow`](../Code/src/EchoHub.Client/UI/MainWindow.cs.md) | class | 2 | 25 | `src/EchoHub.Client/UI/MainWindow.cs` | +| [`Message`](../Code/src/EchoHub.Core/Models/Message.cs.md) | class | 21 | 4 | `src/EchoHub.Core/Models/Message.cs` | +| [`ChannelsController`](../Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md) | class | 0 | 25 | `src/EchoHub.Server/Controllers/ChannelsController.cs` | +| [`ConnectionManager`](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) | class | 1 | 22 | `src/EchoHub.Client/Services/ConnectionManager.cs` | +| [`MessageDto`](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) | record | 20 | 3 | `src/EchoHub.Core/DTOs/ChatDtos.cs` | + +*Regenerated on every full documentation run; see [README](README.md) for how to use this pack.* \ No newline at end of file diff --git a/docs/auriondocs/Agent/symbol-graph.json b/docs/auriondocs/Agent/symbol-graph.json new file mode 100644 index 0000000..6831c4c --- /dev/null +++ b/docs/auriondocs/Agent/symbol-graph.json @@ -0,0 +1,3295 @@ +{ + "schema": "auriondocs.agent-graph/v1", + "repository": "HueByte/EchoHub", + "commit": "4dcb480d1d43e4efaaa9b2e190c7275fcab94d23", + "grouping": "communities", + "stats": { + "symbols": 201, + "files": 128, + "edges": 648, + "subsystems": 24 + }, + "subsystems": [ + { + "label": "src/EchoHub.Core/DTOs · ChatService", + "symbols": 23 + }, + { + "label": "src/EchoHub.Client/Services · AppOrchestrator", + "symbols": 21 + }, + { + "label": "src/EchoHub.Client/UI · MainWindow", + "symbols": 21 + }, + { + "label": "src/EchoHub.Core/DTOs · ApiClient", + "symbols": 19 + }, + { + "label": "src/EchoHub.Server · User", + "symbols": 17 + }, + { + "label": "src/EchoHub.Core/DTOs · ChannelService", + "symbols": 13 + }, + { + "label": "src/EchoHub.Server · Program", + "symbols": 13 + }, + { + "label": "src/EchoHub.Client/Config", + "symbols": 7 + }, + { + "label": "src/EchoHub.Server · ServerDirectoryService", + "symbols": 7 + }, + { + "label": "src/EchoHub.Client/UI · Channel", + "symbols": 6 + }, + { + "label": "src/EchoHub.Core/DTOs · ChannelsController", + "symbols": 6 + }, + { + "label": "src/EchoHub.Core/Models", + "symbols": 6 + }, + { + "label": "src/EchoHub.Client/Services · UpdateBackupService", + "symbols": 5 + }, + { + "label": "src/EchoHub.Client/Themes", + "symbols": 5 + }, + { + "label": "src/EchoHub.Server · ServerLogsStreamService", + "symbols": 5 + }, + { + "label": "src/EchoHub.Client/Services · IMessageEncryptionService", + "symbols": 4 + }, + { + "label": "src/EchoHub.Client/UI · InviteCode", + "symbols": 4 + }, + { + "label": "src/EchoHub.Client/Services · FolderPickResult", + "symbols": 3 + }, + { + "label": "src/EchoHub.Core/DTOs · UserDataExportDto", + "symbols": 3 + }, + { + "label": "src/EchoHub.Server · ServerStatsReportService", + "symbols": 3 + }, + { + "label": "src/EchoHub.Server · SpamGuard", + "symbols": 3 + }, + { + "label": "src/EchoHub.Server.Irc", + "symbols": 3 + }, + { + "label": "src/EchoHub.Tests/Irc", + "symbols": 3 + }, + { + "label": "src/EchoHub.Core/DTOs", + "symbols": 1 + } + ], + "symbols": [ + { + "id": "src/EchoHub.Client/AppOrchestrator.cs::AppOrchestrator", + "name": "AppOrchestrator", + "kind": "class", + "file": "src/EchoHub.Client/AppOrchestrator.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.093, + "inDegree": 3, + "outDegree": 47, + "doc": "Code/src/EchoHub.Client/AppOrchestrator.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Commands/CommandHandler.cs::CommandHandler", + "src/EchoHub.Client/Config/ClientConfig.cs::AccountPreset", + "src/EchoHub.Client/Config/ClientConfig.cs::ClientConfig", + "src/EchoHub.Client/Config/ConfigManager.cs::ConfigManager", + "src/EchoHub.Client/Services/AsyncRunner.cs::AsyncRunner", + "src/EchoHub.Client/Services/AudioPlaybackService.cs::AudioPlaybackService", + "src/EchoHub.Client/Services/AvatarHelper.cs::AvatarHelper", + "src/EchoHub.Client/Services/ConnectionManager.cs::ConnectResult", + "src/EchoHub.Client/Services/ConnectionManager.cs::ConnectionManager", + "src/EchoHub.Client/Services/EchoHubConnection.cs::ChannelPasswordRequiredException", + "src/EchoHub.Client/Services/EchoHubConnection.cs::JoinOutcome", + "src/EchoHub.Client/Services/NotificationSoundService.cs::NotificationSoundService", + "src/EchoHub.Client/Services/OutgoingAttachment.cs::OutgoingAttachment", + "src/EchoHub.Client/Services/UpdateChecker.cs::UpdateChecker", + "src/EchoHub.Client/Services/UserSession.cs::UserSession", + "src/EchoHub.Client/Themes/Theme.cs::Theme", + "src/EchoHub.Client/Themes/ThemeManager.cs::ThemeManager", + "src/EchoHub.Client/UI/Chat/ChatMessageManager.cs::ChatMessageManager", + "src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs::ChannelPasswordDialog", + "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs::ConnectDialog", + "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs::CreateChannelDialog", + "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs::ProfileEditDialog", + "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs::ProfileAction", + "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs::ProfileViewDialog", + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchDialog", + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResultType", + "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs::StatusDialog", + "src/EchoHub.Client/UI/MainWindow.cs::MainWindow", + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Constants/MessageConventions.cs::MessageConventions", + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::RekeyChannelRequest", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UpdateProfileRequest", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto", + "src/EchoHub.Core/Services/AsciiBannerService.cs::AsciiBannerService", + "src/EchoHub.Core/Services/FileValidationHelper.cs::FileValidationHelper", + "src/EchoHub.Core/Services/ImageToAsciiService.cs::ImageToAsciiService" + ] + }, + { + "id": "src/EchoHub.Client/Commands/CommandHandler.cs::CommandHandler", + "name": "CommandHandler", + "kind": "class", + "file": "src/EchoHub.Client/Commands/CommandHandler.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": null, + "inDegree": 1, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/Commands/CommandHandler.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Commands/CommandHandler.cs::CommandResult", + "src/EchoHub.Client/Themes/Theme.cs::Theme", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/Commands/CommandHandler.cs::CommandResult", + "name": "CommandResult", + "kind": "record", + "file": "src/EchoHub.Client/Commands/CommandHandler.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.101, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Commands/CommandHandler.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Client/Config/ClientConfig.cs::AccountPreset", + "name": "AccountPreset", + "kind": "class", + "file": "src/EchoHub.Client/Config/ClientConfig.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.231, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Config/ClientConfig.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Config/ClientConfig.cs::ClientConfig", + "name": "ClientConfig", + "kind": "class", + "file": "src/EchoHub.Client/Config/ClientConfig.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.331, + "inDegree": 4, + "outDegree": 3, + "doc": "Code/src/EchoHub.Client/Config/ClientConfig.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Config/ClientConfig.cs::AccountPreset", + "src/EchoHub.Client/Config/ClientConfig.cs::NotificationConfig", + "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer" + ] + }, + { + "id": "src/EchoHub.Client/Config/ClientConfig.cs::NotificationConfig", + "name": "NotificationConfig", + "kind": "class", + "file": "src/EchoHub.Client/Config/ClientConfig.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.231, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Config/ClientConfig.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer", + "name": "SavedServer", + "kind": "class", + "file": "src/EchoHub.Client/Config/ClientConfig.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.384, + "inDegree": 5, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/Config/ClientConfig.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/RoomKeyProtector.cs::RoomKeyProtector", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken" + ] + }, + { + "id": "src/EchoHub.Client/Config/ConfigManager.cs::ConfigManager", + "name": "ConfigManager", + "kind": "class", + "file": "src/EchoHub.Client/Config/ConfigManager.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.477, + "inDegree": 4, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/Config/ConfigManager.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Config/ClientConfig.cs::ClientConfig", + "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer" + ] + }, + { + "id": "src/EchoHub.Client/Program.cs::Program", + "name": "Program", + "kind": "file", + "file": "src/EchoHub.Client/Program.cs", + "subsystem": "src/EchoHub.Client/Themes", + "complexity": 0.245, + "inDegree": 0, + "outDegree": 8, + "doc": "Code/src/EchoHub.Client/Program.cs.md", + "dependsOn": [ + "src/EchoHub.Client/AppOrchestrator.cs::AppOrchestrator", + "src/EchoHub.Client/Config/ConfigManager.cs::ConfigManager", + "src/EchoHub.Client/Services/PathSetup.cs::PathSetup", + "src/EchoHub.Client/Services/UpdateBackupService.cs::UpdateBackupService", + "src/EchoHub.Client/Themes/Theme.cs::Theme", + "src/EchoHub.Client/Themes/ThemeManager.cs::ThemeManager", + "src/EchoHub.Client/UI/MainWindow.cs::MainWindow", + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Client/Services/ApiClient.cs::ApiClient", + "name": "ApiClient", + "kind": "class", + "file": "src/EchoHub.Client/Services/ApiClient.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 3, + "outDegree": 29, + "doc": "Code/src/EchoHub.Client/Services/ApiClient.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/EchoHubConnection.cs::EchoHubConnection", + "src/EchoHub.Client/Services/OutgoingAttachment.cs::OutgoingAttachment", + "src/EchoHub.Core/DTOs/AccountDtos.cs::DeleteAccountRequest", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginRequest", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginResponse", + "src/EchoHub.Core/DTOs/AuthDtos.cs::RefreshRequest", + "src/EchoHub.Core/DTOs/AuthDtos.cs::RegisterRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelMetaDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::CreateChannelRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::RekeyChannelRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::SendUrlRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::UpdateTopicRequest", + "src/EchoHub.Core/DTOs/CommonDtos.cs::PaginatedResponse", + "src/EchoHub.Core/DTOs/InviteDtos.cs::CreateInviteRequest", + "src/EchoHub.Core/DTOs/InviteDtos.cs::InviteDto", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::AssignRoleRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::BanRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::KickRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::MuteRequest", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::AvatarUploadResponse", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UpdateProfileRequest", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/DTOs/ServerDtos.cs::EncryptionKeyResponse", + "src/EchoHub.Core/DTOs/ServerDtos.cs::ServerStatusDto", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole" + ] + }, + { + "id": "src/EchoHub.Client/Services/AsyncRunner.cs::AsyncRunner", + "name": "AsyncRunner", + "kind": "class", + "file": "src/EchoHub.Client/Services/AsyncRunner.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.299, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/AsyncRunner.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Client/Services/AudioPlaybackService.cs::AudioPlaybackService", + "name": "AudioPlaybackService", + "kind": "class", + "file": "src/EchoHub.Client/Services/AudioPlaybackService.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.519, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/AvatarHelper.cs::AvatarHelper", + "name": "AvatarHelper", + "kind": "class", + "file": "src/EchoHub.Client/Services/AvatarHelper.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.294, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/AvatarHelper.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/ApiClient.cs::ApiClient" + ] + }, + { + "id": "src/EchoHub.Client/Services/ClientEncryptionService.cs::ClientEncryptionService", + "name": "ClientEncryptionService", + "kind": "class", + "file": "src/EchoHub.Client/Services/ClientEncryptionService.cs", + "subsystem": "src/EchoHub.Client/Services · IMessageEncryptionService", + "complexity": 0.542, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService" + ] + }, + { + "id": "src/EchoHub.Client/Services/ClipboardFiles.cs::ClipboardFiles", + "name": "ClipboardFiles", + "kind": "class", + "file": "src/EchoHub.Client/Services/ClipboardFiles.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.493, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/ClipboardImage.cs::ClipboardImage", + "name": "ClipboardImage", + "kind": "class", + "file": "src/EchoHub.Client/Services/ClipboardImage.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.62, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/ClipboardImage.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/ConnectionManager.cs::ConnectResult", + "name": "ConnectResult", + "kind": "record", + "file": "src/EchoHub.Client/Services/ConnectionManager.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.167, + "inDegree": 2, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/Services/ConnectionManager.cs.md", + "dependsOn": [ + "src/EchoHub.Client/AppOrchestrator.cs::AppOrchestrator", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginResponse", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto" + ] + }, + { + "id": "src/EchoHub.Client/Services/ConnectionManager.cs::ConnectionManager", + "name": "ConnectionManager", + "kind": "class", + "file": "src/EchoHub.Client/Services/ConnectionManager.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.77, + "inDegree": 1, + "outDegree": 22, + "doc": "Code/src/EchoHub.Client/Services/ConnectionManager.cs.md", + "dependsOn": [ + "src/EchoHub.Client/AppOrchestrator.cs::AppOrchestrator", + "src/EchoHub.Client/Config/ClientConfig.cs::ClientConfig", + "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer", + "src/EchoHub.Client/Config/ConfigManager.cs::ConfigManager", + "src/EchoHub.Client/Services/ApiClient.cs::ApiClient", + "src/EchoHub.Client/Services/ClientEncryptionService.cs::ClientEncryptionService", + "src/EchoHub.Client/Services/ConnectionManager.cs::ConnectResult", + "src/EchoHub.Client/Services/EchoHubConnection.cs::ChannelPasswordRequiredException", + "src/EchoHub.Client/Services/EchoHubConnection.cs::EchoHubConnection", + "src/EchoHub.Client/Services/EchoHubConnection.cs::JoinOutcome", + "src/EchoHub.Client/Services/RoomKeyStore.cs::RoomKeyStore", + "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs::ConnectDialogResult", + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginResponse", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/Services/EchoHubConnection.cs::ChannelPasswordRequiredException", + "name": "ChannelPasswordRequiredException", + "kind": "class", + "file": "src/EchoHub.Client/Services/EchoHubConnection.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.275, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/EchoHubConnection.cs::EchoHubConnection", + "name": "EchoHubConnection", + "kind": "class", + "file": "src/EchoHub.Client/Services/EchoHubConnection.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.652, + "inDegree": 2, + "outDegree": 16, + "doc": "Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/ApiClient.cs::ApiClient", + "src/EchoHub.Client/Services/ClientEncryptionService.cs::ClientEncryptionService", + "src/EchoHub.Client/Services/EchoHubConnection.cs::ChannelPasswordRequiredException", + "src/EchoHub.Client/Services/EchoHubConnection.cs::JoinOutcome", + "src/EchoHub.Client/Services/EchoHubConnection.cs::RoomLockedException", + "src/EchoHub.Client/Services/RoomKeyStore.cs::RoomKeyStore", + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Contracts/IEchoHubClient.cs::IEchoHubClient", + "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::JoinChannelResult", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto" + ] + }, + { + "id": "src/EchoHub.Client/Services/EchoHubConnection.cs::JoinOutcome", + "name": "JoinOutcome", + "kind": "record", + "file": "src/EchoHub.Client/Services/EchoHubConnection.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.234, + "inDegree": 3, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto" + ] + }, + { + "id": "src/EchoHub.Client/Services/EchoHubConnection.cs::RoomLockedException", + "name": "RoomLockedException", + "kind": "class", + "file": "src/EchoHub.Client/Services/EchoHubConnection.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.264, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/NativeFolderPicker.cs::FolderPickResult", + "name": "FolderPickResult", + "kind": "record", + "file": "src/EchoHub.Client/Services/NativeFolderPicker.cs", + "subsystem": "src/EchoHub.Client/Services · FolderPickResult", + "complexity": 0.093, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/NativeFolderPicker.cs::PickerOutcome" + ] + }, + { + "id": "src/EchoHub.Client/Services/NativeFolderPicker.cs::NativeFolderPicker", + "name": "NativeFolderPicker", + "kind": "class", + "file": "src/EchoHub.Client/Services/NativeFolderPicker.cs", + "subsystem": "src/EchoHub.Client/Services · FolderPickResult", + "complexity": 0.408, + "inDegree": 0, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/NativeFolderPicker.cs::FolderPickResult", + "src/EchoHub.Client/Services/NativeFolderPicker.cs::PickerOutcome" + ] + }, + { + "id": "src/EchoHub.Client/Services/NativeFolderPicker.cs::PickerOutcome", + "name": "PickerOutcome", + "kind": "enum", + "file": "src/EchoHub.Client/Services/NativeFolderPicker.cs", + "subsystem": "src/EchoHub.Client/Services · FolderPickResult", + "complexity": 0.026, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/NativeFolderPicker.cs::FolderPickResult" + ] + }, + { + "id": "src/EchoHub.Client/Services/NotificationSoundService.cs::NotificationSoundService", + "name": "NotificationSoundService", + "kind": "class", + "file": "src/EchoHub.Client/Services/NotificationSoundService.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.501, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/NotificationSoundService.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Config/ClientConfig.cs::NotificationConfig" + ] + }, + { + "id": "src/EchoHub.Client/Services/OutgoingAttachment.cs::OutgoingAttachment", + "name": "OutgoingAttachment", + "kind": "record", + "file": "src/EchoHub.Client/Services/OutgoingAttachment.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.169, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/PathSetup.cs::PathSetup", + "name": "PathSetup", + "kind": "class", + "file": "src/EchoHub.Client/Services/PathSetup.cs", + "subsystem": "src/EchoHub.Client/Themes", + "complexity": 0.345, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/PathSetup.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/User.cs::User" + ] + }, + { + "id": "src/EchoHub.Client/Services/RoomKeyProtector.cs::RoomKeyProtector", + "name": "RoomKeyProtector", + "kind": "class", + "file": "src/EchoHub.Client/Services/RoomKeyProtector.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.472, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto" + ] + }, + { + "id": "src/EchoHub.Client/Services/RoomKeyStore.cs::RoomKeyStore", + "name": "RoomKeyStore", + "kind": "class", + "file": "src/EchoHub.Client/Services/RoomKeyStore.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.62, + "inDegree": 2, + "outDegree": 6, + "doc": "Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Config/ClientConfig.cs::ClientConfig", + "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer", + "src/EchoHub.Client/Config/ConfigManager.cs::ConfigManager", + "src/EchoHub.Client/Services/RoomKeyProtector.cs::RoomKeyProtector", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto" + ] + }, + { + "id": "src/EchoHub.Client/Services/UpdateBackupService.cs::BackupInfo", + "name": "BackupInfo", + "kind": "record", + "file": "src/EchoHub.Client/Services/UpdateBackupService.cs", + "subsystem": "src/EchoHub.Client/Services · UpdateBackupService", + "complexity": 0.101, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Services/UpdateBackupService.cs::BackupJsonContext", + "name": "BackupJsonContext", + "kind": "class", + "file": "src/EchoHub.Client/Services/UpdateBackupService.cs", + "subsystem": "src/EchoHub.Client/Services · UpdateBackupService", + "complexity": 0.158, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/UpdateBackupService.cs::BackupInfo" + ] + }, + { + "id": "src/EchoHub.Client/Services/UpdateBackupService.cs::UpdateBackupService", + "name": "UpdateBackupService", + "kind": "class", + "file": "src/EchoHub.Client/Services/UpdateBackupService.cs", + "subsystem": "src/EchoHub.Client/Services · UpdateBackupService", + "complexity": 0.535, + "inDegree": 3, + "outDegree": 3, + "doc": "Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/UpdateBackupService.cs::BackupInfo", + "src/EchoHub.Client/Services/UpdateBackupService.cs::BackupJsonContext", + "src/EchoHub.Client/Services/UpdateChecker.cs::UpdateChecker" + ] + }, + { + "id": "src/EchoHub.Client/Services/UpdateChecker.cs::UpdateChecker", + "name": "UpdateChecker", + "kind": "class", + "file": "src/EchoHub.Client/Services/UpdateChecker.cs", + "subsystem": "src/EchoHub.Client/Services · UpdateBackupService", + "complexity": 0.554, + "inDegree": 2, + "outDegree": 3, + "doc": "Code/src/EchoHub.Client/Services/UpdateChecker.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/UpdateBackupService.cs::UpdateBackupService", + "src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs::UpdateConfirmDialog", + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Client/Services/UserSession.cs::UserSession", + "name": "UserSession", + "kind": "class", + "file": "src/EchoHub.Client/Services/UserSession.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.244, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Services/UserSession.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/Themes/Theme.cs::Theme", + "name": "Theme", + "kind": "class", + "file": "src/EchoHub.Client/Themes/Theme.cs", + "subsystem": "src/EchoHub.Client/Themes", + "complexity": 0.379, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/Themes/Theme.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Themes/Theme.cs::ThemeColors" + ] + }, + { + "id": "src/EchoHub.Client/Themes/Theme.cs::ThemeColors", + "name": "ThemeColors", + "kind": "class", + "file": "src/EchoHub.Client/Themes/Theme.cs", + "subsystem": "src/EchoHub.Client/Themes", + "complexity": 0.252, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/Themes/Theme.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/Themes/ThemeManager.cs::ThemeManager", + "name": "ThemeManager", + "kind": "class", + "file": "src/EchoHub.Client/Themes/ThemeManager.cs", + "subsystem": "src/EchoHub.Client/Themes", + "complexity": null, + "inDegree": 3, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/Themes/ThemeManager.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Themes/Theme.cs::Theme", + "src/EchoHub.Client/Themes/Theme.cs::ThemeColors" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatColors.cs::ChatColors", + "name": "ChatColors", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/ChatColors.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.582, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatColors.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentAction", + "name": "AttachmentAction", + "kind": "enum", + "file": "src/EchoHub.Client/UI/Chat/ChatLine.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.026, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatLine.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentActionSpan", + "name": "AttachmentActionSpan", + "kind": "record", + "file": "src/EchoHub.Client/UI/Chat/ChatLine.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.301, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatLine.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentAction" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine", + "name": "ChatLine", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/ChatLine.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.635, + "inDegree": 5, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatLine.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatColors.cs::ChatColors", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentActionSpan", + "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatListSource.cs::ChatListSource", + "name": "ChatListSource", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/ChatListSource.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.678, + "inDegree": 2, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatListSource.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatColors.cs::ChatColors", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatMessageManager.cs::ChatMessageManager", + "name": "ChatMessageManager", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/ChatMessageManager.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": null, + "inDegree": 2, + "outDegree": 15, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatColors.cs::ChatColors", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentAction", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentActionSpan", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine", + "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment", + "src/EchoHub.Client/UI/Helpers/EmojiHelper.cs::EmojiHelper", + "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs::HexColorHelper", + "src/EchoHub.Client/UI/Helpers/NickColorHelper.cs::NickColorHelper", + "src/EchoHub.Core/Constants/MessageConventions.cs::MessageConventions", + "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ReplyRefDto", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment", + "name": "ChatSegment", + "kind": "record", + "file": "src/EchoHub.Client/UI/Chat/ChatSegment.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.093, + "inDegree": 5, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Chat/ChatSegment.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Chat/RenderHelpers.cs::RenderHelpers", + "name": "RenderHelpers", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/RenderHelpers.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.304, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Chat/RenderHelpers.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Chat/WelcomeBanner.cs::WelcomeBanner", + "name": "WelcomeBanner", + "kind": "class", + "file": "src/EchoHub.Client/UI/Chat/WelcomeBanner.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.358, + "inDegree": 1, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/UI/Chat/WelcomeBanner.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine", + "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs::AudioPlayerDialog", + "name": "AudioPlayerDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.425, + "inDegree": 0, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/AudioPlaybackService.cs::AudioPlaybackService" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs::ChannelPasswordDialog", + "name": "ChannelPasswordDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.265, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs::ConnectDialog", + "name": "ConnectDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs", + "subsystem": "src/EchoHub.Client/UI · InviteCode", + "complexity": 0.292, + "inDegree": 1, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Config/ClientConfig.cs::SavedServer", + "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs::ConnectDialogResult", + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs::ConnectDialogResult", + "name": "ConnectDialogResult", + "kind": "record", + "file": "src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs", + "subsystem": "src/EchoHub.Client/UI · InviteCode", + "complexity": 0.138, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs::CreateChannelDialog", + "name": "CreateChannelDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.22, + "inDegree": 1, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs::CreateChannelResult", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs::CreateChannelResult", + "name": "CreateChannelResult", + "kind": "record", + "file": "src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.108, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs::ProfileEditDialog", + "name": "ProfileEditDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.301, + "inDegree": 1, + "outDegree": 2, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs::ProfileEditResult", + "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs::HexColorHelper" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs::ProfileEditResult", + "name": "ProfileEditResult", + "kind": "record", + "file": "src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.123, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs::ProfileAction", + "name": "ProfileAction", + "kind": "enum", + "file": "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.026, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs::ProfileViewDialog", + "name": "ProfileViewDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.398, + "inDegree": 1, + "outDegree": 8, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine", + "src/EchoHub.Client/UI/Chat/ChatListSource.cs::ChatListSource", + "src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs::ProfileAction", + "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs::HexColorHelper", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchDialog", + "name": "SearchDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.295, + "inDegree": 1, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResult", + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResultType", + "src/EchoHub.Client/UI/ListSources/SearchListSource.cs::SearchListSource", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResult", + "name": "SearchResult", + "kind": "record", + "file": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.101, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResultType" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResultType", + "name": "SearchResultType", + "kind": "enum", + "file": "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.026, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs::StatusDialog", + "name": "StatusDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.25, + "inDegree": 1, + "outDegree": 3, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs::StatusDialogResult", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs::StatusDialogResult", + "name": "StatusDialogResult", + "kind": "record", + "file": "src/EchoHub.Client/UI/Dialogs/StatusDialog.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.093, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs::UpdateConfirmDialog", + "name": "UpdateConfirmDialog", + "kind": "class", + "file": "src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs", + "subsystem": "src/EchoHub.Client/Services · UpdateBackupService", + "complexity": 0.21, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs::DroppedFileParser", + "name": "DroppedFileParser", + "kind": "class", + "file": "src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.481, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Helpers/EmojiHelper.cs::EmojiHelper", + "name": "EmojiHelper", + "kind": "class", + "file": "src/EchoHub.Client/UI/Helpers/EmojiHelper.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.376, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Helpers/EmojiHelper.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs::HexColorHelper", + "name": "HexColorHelper", + "kind": "class", + "file": "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.32, + "inDegree": 4, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Helpers/HexColorHelper.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/Helpers/NickColorHelper.cs::NickColorHelper", + "name": "NickColorHelper", + "kind": "class", + "file": "src/EchoHub.Client/UI/Helpers/NickColorHelper.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.33, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/Helpers/NickColorHelper.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/ListSources/ChannelListSource.cs::ChannelListSource", + "name": "ChannelListSource", + "kind": "class", + "file": "src/EchoHub.Client/UI/ListSources/ChannelListSource.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.642, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Client/UI/ListSources/ChannelListSource.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/RenderHelpers.cs::RenderHelpers" + ] + }, + { + "id": "src/EchoHub.Client/UI/ListSources/SearchListSource.cs::SearchListSource", + "name": "SearchListSource", + "kind": "class", + "file": "src/EchoHub.Client/UI/ListSources/SearchListSource.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.581, + "inDegree": 1, + "outDegree": 4, + "doc": "Code/src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md", + "dependsOn": [ + "src/EchoHub.Client/UI/Chat/RenderHelpers.cs::RenderHelpers", + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResult", + "src/EchoHub.Client/UI/Dialogs/SearchDialog.cs::SearchResultType", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Client/UI/ListSources/UserListSource.cs::UserListSource", + "name": "UserListSource", + "kind": "class", + "file": "src/EchoHub.Client/UI/ListSources/UserListSource.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.592, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Client/UI/ListSources/UserListSource.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Client/UI/MainWindow.cs::MainWindow", + "name": "MainWindow", + "kind": "class", + "file": "src/EchoHub.Client/UI/MainWindow.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.132, + "inDegree": 2, + "outDegree": 25, + "doc": "Code/src/EchoHub.Client/UI/MainWindow.cs.md", + "dependsOn": [ + "src/EchoHub.Client/Services/ClipboardFiles.cs::ClipboardFiles", + "src/EchoHub.Client/Services/ClipboardImage.cs::ClipboardImage", + "src/EchoHub.Client/Services/UpdateBackupService.cs::UpdateBackupService", + "src/EchoHub.Client/Themes/ThemeManager.cs::ThemeManager", + "src/EchoHub.Client/UI/Chat/ChatColors.cs::ChatColors", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::AttachmentAction", + "src/EchoHub.Client/UI/Chat/ChatLine.cs::ChatLine", + "src/EchoHub.Client/UI/Chat/ChatListSource.cs::ChatListSource", + "src/EchoHub.Client/UI/Chat/ChatMessageManager.cs::ChatMessageManager", + "src/EchoHub.Client/UI/Chat/ChatSegment.cs::ChatSegment", + "src/EchoHub.Client/UI/Chat/WelcomeBanner.cs::WelcomeBanner", + "src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs::DroppedFileParser", + "src/EchoHub.Client/UI/Helpers/EmojiHelper.cs::EmojiHelper", + "src/EchoHub.Client/UI/Helpers/HexColorHelper.cs::HexColorHelper", + "src/EchoHub.Client/UI/Helpers/NickColorHelper.cs::NickColorHelper", + "src/EchoHub.Client/UI/ListSources/ChannelListSource.cs::ChannelListSource", + "src/EchoHub.Client/UI/ListSources/UserListSource.cs::UserListSource", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "name": "HubConstants", + "kind": "class", + "file": "src/EchoHub.Core/Constants/HubConstants.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.48, + "inDegree": 16, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Constants/HubConstants.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Constants/MessageConventions.cs::MessageConventions", + "name": "MessageConventions", + "kind": "class", + "file": "src/EchoHub.Core/Constants/MessageConventions.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.349, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Constants/MessageConventions.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "name": "ValidationConstants", + "kind": "class", + "file": "src/EchoHub.Core/Constants/ValidationConstants.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.431, + "inDegree": 6, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Constants/ValidationConstants.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Contracts/IChannelService.cs::ChannelListItem", + "name": "ChannelListItem", + "kind": "record", + "file": "src/EchoHub.Core/Contracts/IChannelService.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.116, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Contracts/IChannelService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "name": "IChannelService", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IChannelService.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.653, + "inDegree": 9, + "outDegree": 7, + "doc": "Code/src/EchoHub.Core/Contracts/IChannelService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChannelService.cs::ChannelListItem", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelMetaDto", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "src/EchoHub.Core/DTOs/CommonDtos.cs::PaginatedResponse", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "name": "IChatBroadcaster", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IChatBroadcaster.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.602, + "inDegree": 7, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/Contracts/IChatBroadcaster.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto" + ] + }, + { + "id": "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "name": "IChatService", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IChatService.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.625, + "inDegree": 8, + "outDegree": 5, + "doc": "Code/src/EchoHub.Core/Contracts/IChatService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/Contracts/IEchoHubClient.cs::IEchoHubClient", + "name": "IEchoHubClient", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IEchoHubClient.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.595, + "inDegree": 4, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto" + ] + }, + { + "id": "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "name": "IMessageEncryptionService", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs", + "subsystem": "src/EchoHub.Client/Services · IMessageEncryptionService", + "complexity": 0.39, + "inDegree": 11, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "name": "IUserService", + "kind": "interface", + "file": "src/EchoHub.Core/Contracts/IUserService.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.488, + "inDegree": 7, + "outDegree": 2, + "doc": "Code/src/EchoHub.Core/Contracts/IUserService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/AccountDtos.cs::DeleteAccountRequest", + "name": "DeleteAccountRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AccountDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.286, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedAttachmentDto", + "name": "ExportedAttachmentDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AccountDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · UserDataExportDto", + "complexity": 0.123, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedMessageDto", + "name": "ExportedMessageDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AccountDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · UserDataExportDto", + "complexity": 0.116, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/AccountDtos.cs::UserDataExportDto", + "name": "UserDataExportDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AccountDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · UserDataExportDto", + "complexity": 0.116, + "inDegree": 1, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedAttachmentDto", + "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedMessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginRequest", + "name": "LoginRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AuthDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.093, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginResponse", + "name": "LoginResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AuthDtos.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.123, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/AuthDtos.cs::RefreshRequest", + "name": "RefreshRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AuthDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/AuthDtos.cs::RegisterRequest", + "name": "RegisterRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/AuthDtos.cs", + "subsystem": "src/EchoHub.Client/UI · InviteCode", + "complexity": 0.108, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "name": "AttachmentDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.176, + "inDegree": 5, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "name": "ChannelCryptoDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.293, + "inDegree": 5, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "name": "ChannelDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.146, + "inDegree": 16, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelMetaDto", + "name": "ChannelMetaDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.146, + "inDegree": 4, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::CreateChannelRequest", + "name": "CreateChannelRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.108, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "name": "EmbedDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.123, + "inDegree": 6, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::JoinChannelResult", + "name": "JoinChannelResult", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.123, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "name": "MessageDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.153, + "inDegree": 20, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ReplyRefDto" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::RekeyChannelRequest", + "name": "RekeyChannelRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.182, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::ReplyRefDto", + "name": "ReplyRefDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.234, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::SendMessageRequest", + "name": "SendMessageRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs", + "complexity": 0.093, + "inDegree": 0, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::SendUrlRequest", + "name": "SendUrlRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::UpdateTopicRequest", + "name": "UpdateTopicRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ChatDtos.cs::UserDto", + "name": "UserDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ChatDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.123, + "inDegree": 0, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::ApiResponse", + "name": "ApiResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.108, + "inDegree": 0, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "name": "ChannelError", + "kind": "enum", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.026, + "inDegree": 5, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "name": "ChannelOperationResult", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.188, + "inDegree": 5, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "name": "ErrorResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.093, + "inDegree": 7, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::PaginatedResponse", + "name": "PaginatedResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.108, + "inDegree": 4, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "name": "UserError", + "kind": "enum", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.026, + "inDegree": 5, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "name": "UserOperationResult", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/CommonDtos.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.188, + "inDegree": 5, + "outDegree": 3, + "doc": "Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/User.cs::User" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/InviteDtos.cs::CreateInviteRequest", + "name": "CreateInviteRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/InviteDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.093, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/InviteDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/InviteDtos.cs::InviteDto", + "name": "InviteDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/InviteDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.123, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/InviteDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ModerationDtos.cs::AssignRoleRequest", + "name": "AssignRoleRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ModerationDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.093, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ModerationDtos.cs::BanRequest", + "name": "BanRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ModerationDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ModerationDtos.cs::KickRequest", + "name": "KickRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ModerationDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ModerationDtos.cs::MuteRequest", + "name": "MuteRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ModerationDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.093, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ProfileDtos.cs::AvatarUploadResponse", + "name": "AvatarUploadResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ProfileDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ProfileDtos.cs::UpdateProfileRequest", + "name": "UpdateProfileRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ProfileDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.101, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ProfileDtos.cs::UpdateStatusRequest", + "name": "UpdateStatusRequest", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ProfileDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.093, + "inDegree": 0, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "name": "UserPresenceDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ProfileDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.131, + "inDegree": 12, + "outDegree": 2, + "doc": "Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "name": "UserProfileDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ProfileDtos.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.161, + "inDegree": 9, + "outDegree": 2, + "doc": "Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/DTOs/ServerDtos.cs::EncryptionKeyResponse", + "name": "EncryptionKeyResponse", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ServerDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.086, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ServerDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/DTOs/ServerDtos.cs::ServerStatusDto", + "name": "ServerStatusDto", + "kind": "record", + "file": "src/EchoHub.Core/DTOs/ServerDtos.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.116, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/DTOs/ServerDtos.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "name": "Attachment", + "kind": "class", + "file": "src/EchoHub.Core/Models/Attachment.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.467, + "inDegree": 5, + "outDegree": 2, + "doc": "Code/src/EchoHub.Core/Models/Attachment.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "name": "AttachmentKind", + "kind": "enum", + "file": "src/EchoHub.Core/Models/AttachmentKind.cs", + "subsystem": "src/EchoHub.Client/UI · MainWindow", + "complexity": 0.226, + "inDegree": 9, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/AttachmentKind.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/Channel.cs::Channel", + "name": "Channel", + "kind": "class", + "file": "src/EchoHub.Core/Models/Channel.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.465, + "inDegree": 29, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/Models/Channel.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Message.cs::Message" + ] + }, + { + "id": "src/EchoHub.Core/Models/ChannelMembership.cs::ChannelMembership", + "name": "ChannelMembership", + "kind": "class", + "file": "src/EchoHub.Core/Models/ChannelMembership.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.231, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/ChannelMembership.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "name": "InviteCode", + "kind": "class", + "file": "src/EchoHub.Core/Models/InviteCode.cs", + "subsystem": "src/EchoHub.Client/UI · InviteCode", + "complexity": 0.339, + "inDegree": 7, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/InviteCode.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/Message.cs::Message", + "name": "Message", + "kind": "class", + "file": "src/EchoHub.Core/Models/Message.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.509, + "inDegree": 21, + "outDegree": 4, + "doc": "Code/src/EchoHub.Core/Models/Message.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/MessageType.cs::MessageType", + "src/EchoHub.Server/Setup/DataMigrationService.cs::DataMigrationService" + ] + }, + { + "id": "src/EchoHub.Core/Models/MessageType.cs::MessageType", + "name": "MessageType", + "kind": "enum", + "file": "src/EchoHub.Core/Models/MessageType.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.026, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/MessageType.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "name": "RefreshToken", + "kind": "class", + "file": "src/EchoHub.Core/Models/RefreshToken.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.427, + "inDegree": 9, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/Models/RefreshToken.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/User.cs::User" + ] + }, + { + "id": "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "name": "ServerRole", + "kind": "enum", + "file": "src/EchoHub.Core/Models/ServerRole.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.026, + "inDegree": 19, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/ServerRole.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/ServerStatsReport.cs::ServerStatsReport", + "name": "ServerStatsReport", + "kind": "class", + "file": "src/EchoHub.Core/Models/ServerStatsReport.cs", + "subsystem": "src/EchoHub.Server · ServerStatsReportService", + "complexity": 0.48, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/ServerStatsReport.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Models/User.cs::User", + "name": "User", + "kind": "class", + "file": "src/EchoHub.Core/Models/User.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.458, + "inDegree": 20, + "outDegree": 2, + "doc": "Code/src/EchoHub.Core/Models/User.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "name": "UserStatus", + "kind": "enum", + "file": "src/EchoHub.Core/Models/UserStatus.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.026, + "inDegree": 21, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Models/UserStatus.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto", + "name": "RoomCrypto", + "kind": "class", + "file": "src/EchoHub.Core/Security/RoomCrypto.cs", + "subsystem": "src/EchoHub.Client/Config", + "complexity": 0.679, + "inDegree": 7, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Security/RoomCrypto.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Services/AsciiBannerService.cs::AsciiBannerService", + "name": "AsciiBannerService", + "kind": "class", + "file": "src/EchoHub.Core/Services/AsciiBannerService.cs", + "subsystem": "src/EchoHub.Client/Services · AppOrchestrator", + "complexity": 0.411, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Services/AsciiBannerService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Services/FileValidationHelper.cs::FileValidationHelper", + "name": "FileValidationHelper", + "kind": "class", + "file": "src/EchoHub.Core/Services/FileValidationHelper.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.473, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Core/Services/FileValidationHelper.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Core/Services/ImageToAsciiService.cs::ImageToAsciiService", + "name": "ImageToAsciiService", + "kind": "class", + "file": "src/EchoHub.Core/Services/ImageToAsciiService.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.476, + "inDegree": 4, + "outDegree": 1, + "doc": "Code/src/EchoHub.Core/Services/ImageToAsciiService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcBroadcaster.cs::IrcBroadcaster", + "name": "IrcBroadcaster", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcBroadcaster.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.712, + "inDegree": 1, + "outDegree": 9, + "doc": "Code/src/EchoHub.Server.Irc/IrcBroadcaster.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Server.Irc/IrcGatewayService.cs::IrcGatewayService", + "src/EchoHub.Server.Irc/IrcMessageFormatter.cs::IrcMessageFormatter" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcClientConnection.cs::IrcClientConnection", + "name": "IrcClientConnection", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcClientConnection.cs", + "subsystem": "src/EchoHub.Tests/Irc", + "complexity": 0.6, + "inDegree": 3, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server.Irc/IrcClientConnection.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcCommandHandler.cs::IrcCommandHandler", + "name": "IrcCommandHandler", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcCommandHandler.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.131, + "inDegree": 1, + "outDegree": 16, + "doc": "Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "src/EchoHub.Server.Irc/IrcClientConnection.cs::IrcClientConnection", + "src/EchoHub.Server.Irc/IrcMessage.cs::IrcMessage", + "src/EchoHub.Server.Irc/IrcMessageFormatter.cs::IrcMessageFormatter", + "src/EchoHub.Server.Irc/IrcNumericReply.cs::IrcNumericReply", + "src/EchoHub.Server.Irc/IrcOptions.cs::IrcOptions" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcGatewayService.cs::IrcGatewayService", + "name": "IrcGatewayService", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcGatewayService.cs", + "subsystem": "src/EchoHub.Server.Irc", + "complexity": 0.586, + "inDegree": 2, + "outDegree": 7, + "doc": "Code/src/EchoHub.Server.Irc/IrcGatewayService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Server.Irc/IrcClientConnection.cs::IrcClientConnection", + "src/EchoHub.Server.Irc/IrcCommandHandler.cs::IrcCommandHandler", + "src/EchoHub.Server.Irc/IrcOptions.cs::IrcOptions" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcMessage.cs::IrcMessage", + "name": "IrcMessage", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcMessage.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.421, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server.Irc/IrcMessage.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server.Irc/IrcMessageFormatter.cs::IrcMessageFormatter", + "name": "IrcMessageFormatter", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcMessageFormatter.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.485, + "inDegree": 2, + "outDegree": 6, + "doc": "Code/src/EchoHub.Server.Irc/IrcMessageFormatter.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/MessageConventions.cs::MessageConventions", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ReplyRefDto", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcNumericReply.cs::IrcNumericReply", + "name": "IrcNumericReply", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcNumericReply.cs", + "subsystem": "src/EchoHub.Client/UI · Channel", + "complexity": 0.458, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server.Irc/IrcNumericReply.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Channel.cs::Channel" + ] + }, + { + "id": "src/EchoHub.Server.Irc/IrcOptions.cs::IrcOptions", + "name": "IrcOptions", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcOptions.cs", + "subsystem": "src/EchoHub.Server.Irc", + "complexity": 0.382, + "inDegree": 3, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server.Irc/IrcOptions.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server.Irc/IrcServiceExtensions.cs::IrcServiceExtensions", + "name": "IrcServiceExtensions", + "kind": "class", + "file": "src/EchoHub.Server.Irc/IrcServiceExtensions.cs", + "subsystem": "src/EchoHub.Server.Irc", + "complexity": 0.232, + "inDegree": 0, + "outDegree": 4, + "doc": "Code/src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Server.Irc/IrcBroadcaster.cs::IrcBroadcaster", + "src/EchoHub.Server.Irc/IrcGatewayService.cs::IrcGatewayService", + "src/EchoHub.Server.Irc/IrcOptions.cs::IrcOptions" + ] + }, + { + "id": "src/EchoHub.Server/Auth/JwtTokenService.cs::JwtTokenService", + "name": "JwtTokenService", + "kind": "class", + "file": "src/EchoHub.Server/Auth/JwtTokenService.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.467, + "inDegree": 2, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Auth/JwtTokenService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/User.cs::User" + ] + }, + { + "id": "src/EchoHub.Server/Config/ServerLogsOptions.cs::ServerLogsOptions", + "name": "ServerLogsOptions", + "kind": "class", + "file": "src/EchoHub.Server/Config/ServerLogsOptions.cs", + "subsystem": "src/EchoHub.Server · ServerLogsStreamService", + "complexity": 0.409, + "inDegree": 4, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Config/ServerLogsOptions.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole" + ] + }, + { + "id": "src/EchoHub.Server/Config/SpamOptions.cs::SpamOptions", + "name": "SpamOptions", + "kind": "class", + "file": "src/EchoHub.Server/Config/SpamOptions.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.432, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Config/SpamOptions.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/MuteExpirationService.cs::MuteExpirationService" + ] + }, + { + "id": "src/EchoHub.Server/Config/StatsOptions.cs::StatsOptions", + "name": "StatsOptions", + "kind": "class", + "file": "src/EchoHub.Server/Config/StatsOptions.cs", + "subsystem": "src/EchoHub.Server · ServerStatsReportService", + "complexity": 0.301, + "inDegree": 2, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Config/StatsOptions.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Config/UploadLimits.cs::UploadLimits", + "name": "UploadLimits", + "kind": "class", + "file": "src/EchoHub.Server/Config/UploadLimits.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.492, + "inDegree": 3, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Config/UploadLimits.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/AuthController.cs::AuthController", + "name": "AuthController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/AuthController.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.493, + "inDegree": 0, + "outDegree": 13, + "doc": "Code/src/EchoHub.Server/Controllers/AuthController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginRequest", + "src/EchoHub.Core/DTOs/AuthDtos.cs::LoginResponse", + "src/EchoHub.Core/DTOs/AuthDtos.cs::RefreshRequest", + "src/EchoHub.Core/DTOs/AuthDtos.cs::RegisterRequest", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Server/Auth/JwtTokenService.cs::JwtTokenService", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/ChannelsController.cs::ChannelsController", + "name": "ChannelsController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/ChannelsController.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelsController", + "complexity": 0.146, + "inDegree": 0, + "outDegree": 25, + "doc": "Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::CreateChannelRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::RekeyChannelRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::SendUrlRequest", + "src/EchoHub.Core/DTOs/ChatDtos.cs::UpdateTopicRequest", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto", + "src/EchoHub.Core/Services/FileValidationHelper.cs::FileValidationHelper", + "src/EchoHub.Core/Services/ImageToAsciiService.cs::ImageToAsciiService", + "src/EchoHub.Server/Config/UploadLimits.cs::UploadLimits", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/FilesController.cs::FilesController", + "name": "FilesController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/FilesController.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.381, + "inDegree": 0, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Controllers/FilesController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/InvitesController.cs::InvitesController", + "name": "InvitesController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/InvitesController.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.518, + "inDegree": 0, + "outDegree": 7, + "doc": "Code/src/EchoHub.Server/Controllers/InvitesController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/DTOs/InviteDtos.cs::CreateInviteRequest", + "src/EchoHub.Core/DTOs/InviteDtos.cs::InviteDto", + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/ModerationController.cs::ModerationController", + "name": "ModerationController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/ModerationController.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.729, + "inDegree": 0, + "outDegree": 16, + "doc": "Code/src/EchoHub.Server/Controllers/ModerationController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::AssignRoleRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::BanRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::KickRequest", + "src/EchoHub.Core/DTOs/ModerationDtos.cs::MuteRequest", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/ServerController.cs::ServerController", + "name": "ServerController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/ServerController.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.455, + "inDegree": 0, + "outDegree": 7, + "doc": "Code/src/EchoHub.Server/Controllers/ServerController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/DTOs/ServerDtos.cs::EncryptionKeyResponse", + "src/EchoHub.Core/DTOs/ServerDtos.cs::ServerStatusDto", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/DirectoryClaimStore.cs::DirectoryClaimStore" + ] + }, + { + "id": "src/EchoHub.Server/Controllers/UsersController.cs::UsersController", + "name": "UsersController", + "kind": "class", + "file": "src/EchoHub.Server/Controllers/UsersController.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.617, + "inDegree": 1, + "outDegree": 21, + "doc": "Code/src/EchoHub.Server/Controllers/UsersController.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/DTOs/AccountDtos.cs::DeleteAccountRequest", + "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedAttachmentDto", + "src/EchoHub.Core/DTOs/AccountDtos.cs::ExportedMessageDto", + "src/EchoHub.Core/DTOs/AccountDtos.cs::UserDataExportDto", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ErrorResponse", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::AvatarUploadResponse", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UpdateProfileRequest", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Services/FileValidationHelper.cs::FileValidationHelper", + "src/EchoHub.Core/Services/ImageToAsciiService.cs::ImageToAsciiService", + "src/EchoHub.Server/Config/UploadLimits.cs::UploadLimits", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/UserService.cs::UserService" + ] + }, + { + "id": "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "name": "EchoHubDbContext", + "kind": "class", + "file": "src/EchoHub.Server/Data/EchoHubDbContext.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.448, + "inDegree": 14, + "outDegree": 8, + "doc": "Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/ChannelMembership.cs::ChannelMembership", + "src/EchoHub.Core/Models/InviteCode.cs::InviteCode", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/RefreshToken.cs::RefreshToken", + "src/EchoHub.Core/Models/ServerStatsReport.cs::ServerStatsReport", + "src/EchoHub.Core/Models/User.cs::User" + ] + }, + { + "id": "src/EchoHub.Server/Hubs/ChatHub.cs::ChatHub", + "name": "ChatHub", + "kind": "class", + "file": "src/EchoHub.Server/Hubs/ChatHub.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.597, + "inDegree": 3, + "outDegree": 11, + "doc": "Code/src/EchoHub.Server/Hubs/ChatHub.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IEchoHubClient.cs::IEchoHubClient", + "src/EchoHub.Core/DTOs/ChatDtos.cs::JoinChannelResult", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Server/Program.cs::Program", + "name": "Program", + "kind": "file", + "file": "src/EchoHub.Server/Program.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.189, + "inDegree": 0, + "outDegree": 34, + "doc": "Code/src/EchoHub.Server/Program.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/Services/ImageToAsciiService.cs::ImageToAsciiService", + "src/EchoHub.Server/Auth/JwtTokenService.cs::JwtTokenService", + "src/EchoHub.Server/Config/ServerLogsOptions.cs::ServerLogsOptions", + "src/EchoHub.Server/Config/SpamOptions.cs::SpamOptions", + "src/EchoHub.Server/Config/StatsOptions.cs::StatsOptions", + "src/EchoHub.Server/Config/UploadLimits.cs::UploadLimits", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Hubs/ChatHub.cs::ChatHub", + "src/EchoHub.Server/Services/ChannelService.cs::ChannelService", + "src/EchoHub.Server/Services/ChatService.cs::ChatService", + "src/EchoHub.Server/Services/DirectoryClaimStore.cs::DirectoryClaimStore", + "src/EchoHub.Server/Services/FileCleanupService.cs::FileCleanupService", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService", + "src/EchoHub.Server/Services/LinkEmbedService.cs::LinkEmbedService", + "src/EchoHub.Server/Services/MessageEncryptionService.cs::MessageEncryptionService", + "src/EchoHub.Server/Services/MuteExpirationService.cs::MuteExpirationService", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::ServerDirectoryService", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::ServerLogsService", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs::ServerLogsSink", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs::ServerLogsStreamService", + "src/EchoHub.Server/Services/SignalRBroadcaster.cs::SignalRBroadcaster", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamGuard", + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector", + "src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs::ServerStatsReportService", + "src/EchoHub.Server/Services/UserService.cs::UserService", + "src/EchoHub.Server/Setup/DatabaseSetup.cs::DatabaseSetup", + "src/EchoHub.Server/Setup/FirstRunSetup.cs::FirstRunSetup" + ] + }, + { + "id": "src/EchoHub.Server/Services/ChannelService.cs::ChannelService", + "name": "ChannelService", + "kind": "class", + "file": "src/EchoHub.Server/Services/ChannelService.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.116, + "inDegree": 3, + "outDegree": 18, + "doc": "Code/src/EchoHub.Server/Services/ChannelService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::ChannelListItem", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelMetaDto", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "src/EchoHub.Core/DTOs/CommonDtos.cs::PaginatedResponse", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/ChannelMembership.cs::ChannelMembership", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::ServerLogsService", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamGuard", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdictKind" + ] + }, + { + "id": "src/EchoHub.Server/Services/ChatService.cs::ChatService", + "name": "ChatService", + "kind": "class", + "file": "src/EchoHub.Server/Services/ChatService.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.161, + "inDegree": 2, + "outDegree": 29, + "doc": "Code/src/EchoHub.Server/Services/ChatService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::AttachmentDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ReplyRefDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus", + "src/EchoHub.Core/Security/RoomCrypto.cs::RoomCrypto", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/ChannelService.cs::ChannelService", + "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService", + "src/EchoHub.Server/Services/LinkEmbedService.cs::LinkEmbedService", + "src/EchoHub.Server/Services/MuteExpirationService.cs::MuteExpirationService", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::ServerLogsService", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamGuard", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdictKind", + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector" + ] + }, + { + "id": "src/EchoHub.Server/Services/DirectoryClaimStore.cs::DirectoryClaimStore", + "name": "DirectoryClaimStore", + "kind": "class", + "file": "src/EchoHub.Server/Services/DirectoryClaimStore.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.6, + "inDegree": 3, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/DirectoryClaimStore.cs::RegistrationStatus" + ] + }, + { + "id": "src/EchoHub.Server/Services/DirectoryClaimStore.cs::RegistrationStatus", + "name": "RegistrationStatus", + "kind": "record", + "file": "src/EchoHub.Server/Services/DirectoryClaimStore.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.116, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/FileCleanupService.cs::FileCleanupService", + "name": "FileCleanupService", + "kind": "class", + "file": "src/EchoHub.Server/Services/FileCleanupService.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.407, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/FileCleanupService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/FileStorageService.cs::FileStorageService", + "name": "FileStorageService", + "kind": "class", + "file": "src/EchoHub.Server/Services/FileStorageService.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.451, + "inDegree": 6, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/FileStorageService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/LinkEmbedService.cs::LinkEmbedService", + "name": "LinkEmbedService", + "kind": "class", + "file": "src/EchoHub.Server/Services/LinkEmbedService.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.714, + "inDegree": 2, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto" + ] + }, + { + "id": "src/EchoHub.Server/Services/MessageEncryptionService.cs::MessageEncryptionService", + "name": "MessageEncryptionService", + "kind": "class", + "file": "src/EchoHub.Server/Services/MessageEncryptionService.cs", + "subsystem": "src/EchoHub.Client/Services · IMessageEncryptionService", + "complexity": 0.518, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/MessageEncryptionService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService" + ] + }, + { + "id": "src/EchoHub.Server/Services/MuteExpirationService.cs::MuteExpirationService", + "name": "MuteExpirationService", + "kind": "class", + "file": "src/EchoHub.Server/Services/MuteExpirationService.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.425, + "inDegree": 3, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/MuteExpirationService.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext" + ] + }, + { + "id": "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "name": "PresenceTracker", + "kind": "class", + "file": "src/EchoHub.Server/Services/PresenceTracker.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.608, + "inDegree": 8, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/PresenceTracker.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::DirectoryProtocol", + "name": "DirectoryProtocol", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.179, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::DirectoryRegistrationErrors", + "name": "DirectoryRegistrationErrors", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.348, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::ErrorDetail", + "name": "ErrorDetail", + "kind": "record", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.226, + "inDegree": 2, + "outDegree": 2, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::Response" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::RegisterServerDto", + "name": "RegisterServerDto", + "kind": "record", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.122, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::RegisterServerResult", + "name": "RegisterServerResult", + "kind": "record", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.085, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::Response", + "name": "Response", + "kind": "record", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.1, + "inDegree": 2, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/ServerDirectoryService.cs::ErrorDetail" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerDirectoryService.cs::ServerDirectoryService", + "name": "ServerDirectoryService", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerDirectoryService.cs", + "subsystem": "src/EchoHub.Server · ServerDirectoryService", + "complexity": 0.108, + "inDegree": 1, + "outDegree": 10, + "doc": "Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/Message.cs::Message", + "src/EchoHub.Server/Services/DirectoryClaimStore.cs::DirectoryClaimStore", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::DirectoryProtocol", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::DirectoryRegistrationErrors", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::ErrorDetail", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::RegisterServerDto", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::RegisterServerResult", + "src/EchoHub.Server/Services/ServerDirectoryService.cs::Response" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::LogBacklogEntry", + "name": "LogBacklogEntry", + "kind": "record", + "file": "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs", + "subsystem": "src/EchoHub.Server · ServerLogsStreamService", + "complexity": 0.093, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::ServerLogsService", + "name": "ServerLogsService", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs", + "subsystem": "src/EchoHub.Server · ServerLogsStreamService", + "complexity": 0.64, + "inDegree": 4, + "outDegree": 3, + "doc": "Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Server/Config/ServerLogsOptions.cs::ServerLogsOptions", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::LogBacklogEntry" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs::ServerLogsSink", + "name": "ServerLogsSink", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs", + "subsystem": "src/EchoHub.Server · ServerLogsStreamService", + "complexity": 0.333, + "inDegree": 2, + "outDegree": 3, + "doc": "Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Server/Config/ServerLogsOptions.cs::ServerLogsOptions", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs::ServerLogsStreamService" + ] + }, + { + "id": "src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs::ServerLogsStreamService", + "name": "ServerLogsStreamService", + "kind": "class", + "file": "src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs", + "subsystem": "src/EchoHub.Server · ServerLogsStreamService", + "complexity": 0.504, + "inDegree": 2, + "outDegree": 9, + "doc": "Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/Contracts/IEchoHubClient.cs::IEchoHubClient", + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Server/Config/ServerLogsOptions.cs::ServerLogsOptions", + "src/EchoHub.Server/Hubs/ChatHub.cs::ChatHub", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs::ServerLogsService", + "src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs::ServerLogsSink" + ] + }, + { + "id": "src/EchoHub.Server/Services/SignalRBroadcaster.cs::SignalRBroadcaster", + "name": "SignalRBroadcaster", + "kind": "class", + "file": "src/EchoHub.Server/Services/SignalRBroadcaster.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.658, + "inDegree": 1, + "outDegree": 7, + "doc": "Code/src/EchoHub.Server/Services/SignalRBroadcaster.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatBroadcaster.cs::IChatBroadcaster", + "src/EchoHub.Core/Contracts/IEchoHubClient.cs::IEchoHubClient", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Server/Hubs/ChatHub.cs::ChatHub", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker" + ] + }, + { + "id": "src/EchoHub.Server/Services/SpamGuard.cs::SpamGuard", + "name": "SpamGuard", + "kind": "class", + "file": "src/EchoHub.Server/Services/SpamGuard.cs", + "subsystem": "src/EchoHub.Server · SpamGuard", + "complexity": 0.656, + "inDegree": 3, + "outDegree": 6, + "doc": "Code/src/EchoHub.Server/Services/SpamGuard.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Server/Config/SpamOptions.cs::SpamOptions", + "src/EchoHub.Server/Services/ChannelService.cs::ChannelService", + "src/EchoHub.Server/Services/ChatService.cs::ChatService", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdict", + "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdictKind" + ] + }, + { + "id": "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdict", + "name": "SpamVerdict", + "kind": "record", + "file": "src/EchoHub.Server/Services/SpamGuard.cs", + "subsystem": "src/EchoHub.Server · SpamGuard", + "complexity": 0.122, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/SpamGuard.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdictKind" + ] + }, + { + "id": "src/EchoHub.Server/Services/SpamGuard.cs::SpamVerdictKind", + "name": "SpamVerdictKind", + "kind": "enum", + "file": "src/EchoHub.Server/Services/SpamGuard.cs", + "subsystem": "src/EchoHub.Server · SpamGuard", + "complexity": 0.026, + "inDegree": 4, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Services/SpamGuard.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector", + "name": "ServerStatsCollector", + "kind": "class", + "file": "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.372, + "inDegree": 5, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::StatsCounters" + ] + }, + { + "id": "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::StatsCounters", + "name": "StatsCounters", + "kind": "record", + "file": "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs", + "subsystem": "src/EchoHub.Core/DTOs · ApiClient", + "complexity": 0.116, + "inDegree": 1, + "outDegree": 1, + "doc": "Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md", + "dependsOn": [ + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector" + ] + }, + { + "id": "src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs::ServerStatsReportService", + "name": "ServerStatsReportService", + "kind": "class", + "file": "src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs", + "subsystem": "src/EchoHub.Server · ServerStatsReportService", + "complexity": 0.414, + "inDegree": 1, + "outDegree": 5, + "doc": "Code/src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Models/ServerStatsReport.cs::ServerStatsReport", + "src/EchoHub.Server/Config/StatsOptions.cs::StatsOptions", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Services/PresenceTracker.cs::PresenceTracker", + "src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs::ServerStatsCollector" + ] + }, + { + "id": "src/EchoHub.Server/Services/UserService.cs::UserService", + "name": "UserService", + "kind": "class", + "file": "src/EchoHub.Server/Services/UserService.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.698, + "inDegree": 2, + "outDegree": 9, + "doc": "Code/src/EchoHub.Server/Services/UserService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/ValidationConstants.cs::ValidationConstants", + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/User.cs::User", + "src/EchoHub.Server/Controllers/UsersController.cs::UsersController", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext" + ] + }, + { + "id": "src/EchoHub.Server/Setup/DataMigrationService.cs::DataMigrationService", + "name": "DataMigrationService", + "kind": "class", + "file": "src/EchoHub.Server/Setup/DataMigrationService.cs", + "subsystem": "src/EchoHub.Core/Models", + "complexity": 0.578, + "inDegree": 2, + "outDegree": 8, + "doc": "Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/DTOs/ChatDtos.cs::EmbedDto", + "src/EchoHub.Core/Models/Attachment.cs::Attachment", + "src/EchoHub.Core/Models/AttachmentKind.cs::AttachmentKind", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/MessageType.cs::MessageType", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext" + ] + }, + { + "id": "src/EchoHub.Server/Setup/DatabaseSetup.cs::DatabaseSetup", + "name": "DatabaseSetup", + "kind": "class", + "file": "src/EchoHub.Server/Setup/DatabaseSetup.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.334, + "inDegree": 1, + "outDegree": 4, + "doc": "Code/src/EchoHub.Server/Setup/DatabaseSetup.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Constants/HubConstants.cs::HubConstants", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Server/Data/EchoHubDbContext.cs::EchoHubDbContext", + "src/EchoHub.Server/Setup/DataMigrationService.cs::DataMigrationService" + ] + }, + { + "id": "src/EchoHub.Server/Setup/FirstRunSetup.cs::FirstRunSetup", + "name": "FirstRunSetup", + "kind": "class", + "file": "src/EchoHub.Server/Setup/FirstRunSetup.cs", + "subsystem": "src/EchoHub.Server · Program", + "complexity": 0.371, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Server/Setup/FirstRunSetup.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::FakeChannelService", + "name": "FakeChannelService", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChannelService", + "complexity": 0.754, + "inDegree": 0, + "outDegree": 8, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChannelService.cs::ChannelListItem", + "src/EchoHub.Core/Contracts/IChannelService.cs::IChannelService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelCryptoDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelMetaDto", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::ChannelOperationResult", + "src/EchoHub.Core/DTOs/CommonDtos.cs::PaginatedResponse" + ] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::FakeChatService", + "name": "FakeChatService", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Core/DTOs · ChatService", + "complexity": 0.695, + "inDegree": 0, + "outDegree": 6, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IChatService.cs::IChatService", + "src/EchoHub.Core/DTOs/ChatDtos.cs::ChannelDto", + "src/EchoHub.Core/DTOs/ChatDtos.cs::MessageDto", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserPresenceDto", + "src/EchoHub.Core/Models/Channel.cs::Channel", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::FakeEncryptionService", + "name": "FakeEncryptionService", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Client/Services · IMessageEncryptionService", + "complexity": 0.423, + "inDegree": 0, + "outDegree": 1, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IMessageEncryptionService.cs::IMessageEncryptionService" + ] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::FakeUserService", + "name": "FakeUserService", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Server · User", + "complexity": 0.634, + "inDegree": 0, + "outDegree": 6, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [ + "src/EchoHub.Core/Contracts/IUserService.cs::IUserService", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserError", + "src/EchoHub.Core/DTOs/CommonDtos.cs::UserOperationResult", + "src/EchoHub.Core/DTOs/ProfileDtos.cs::UserProfileDto", + "src/EchoHub.Core/Models/ServerRole.cs::ServerRole", + "src/EchoHub.Core/Models/UserStatus.cs::UserStatus" + ] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::TestDuplexStream", + "name": "TestDuplexStream", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Tests/Irc", + "complexity": 0.617, + "inDegree": 1, + "outDegree": 0, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [] + }, + { + "id": "src/EchoHub.Tests/Irc/TestHelpers.cs::TestIrcConnectionFactory", + "name": "TestIrcConnectionFactory", + "kind": "class", + "file": "src/EchoHub.Tests/Irc/TestHelpers.cs", + "subsystem": "src/EchoHub.Tests/Irc", + "complexity": 0.395, + "inDegree": 0, + "outDegree": 2, + "doc": "Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md", + "dependsOn": [ + "src/EchoHub.Server.Irc/IrcClientConnection.cs::IrcClientConnection", + "src/EchoHub.Tests/Irc/TestHelpers.cs::TestDuplexStream" + ] + } + ] +} \ No newline at end of file diff --git a/docs/auriondocs/Code/index.md b/docs/auriondocs/Code/index.md new file mode 100644 index 0000000..4e3f006 --- /dev/null +++ b/docs/auriondocs/Code/index.md @@ -0,0 +1,229 @@ +# HueByte/EchoHub — Documentation + +*Generated from branch `master`* +*Commit: `4dcb480d`* + +## Languages + +- **C#**: 128 files + +## Statistics + +- **Files processed:** 128 +- **Lines of code:** 22,133 +- **Symbols documented:** 598 +- **Validation retries:** 77 + +## Documentation Index + +### src/EchoHub.Client + +- [AppOrchestrator](src/EchoHub.Client/AppOrchestrator.cs.md) +- [Program](src/EchoHub.Client/Program.cs.md) + +### src/EchoHub.Client/Commands + +- [CommandHandler](src/EchoHub.Client/Commands/CommandHandler.cs.md) + +### src/EchoHub.Client/Config + +- [ClientConfig](src/EchoHub.Client/Config/ClientConfig.cs.md) +- [ConfigManager](src/EchoHub.Client/Config/ConfigManager.cs.md) + +### src/EchoHub.Client/Services + +- [ApiClient](src/EchoHub.Client/Services/ApiClient.cs.md) +- [AsyncRunner](src/EchoHub.Client/Services/AsyncRunner.cs.md) +- [AudioPlaybackService](src/EchoHub.Client/Services/AudioPlaybackService.cs.md) +- [AvatarHelper](src/EchoHub.Client/Services/AvatarHelper.cs.md) +- [ClientEncryptionService](src/EchoHub.Client/Services/ClientEncryptionService.cs.md) +- [ClipboardFiles](src/EchoHub.Client/Services/ClipboardFiles.cs.md) +- [ClipboardImage](src/EchoHub.Client/Services/ClipboardImage.cs.md) +- [ConnectionManager](src/EchoHub.Client/Services/ConnectionManager.cs.md) +- [EchoHubConnection](src/EchoHub.Client/Services/EchoHubConnection.cs.md) +- [NativeFolderPicker](src/EchoHub.Client/Services/NativeFolderPicker.cs.md) +- [NotificationSoundService](src/EchoHub.Client/Services/NotificationSoundService.cs.md) +- [OutgoingAttachment](src/EchoHub.Client/Services/OutgoingAttachment.cs.md) +- [PathSetup](src/EchoHub.Client/Services/PathSetup.cs.md) +- [RoomKeyProtector](src/EchoHub.Client/Services/RoomKeyProtector.cs.md) +- [RoomKeyStore](src/EchoHub.Client/Services/RoomKeyStore.cs.md) +- [UpdateBackupService](src/EchoHub.Client/Services/UpdateBackupService.cs.md) +- [UpdateChecker](src/EchoHub.Client/Services/UpdateChecker.cs.md) +- [UserSession](src/EchoHub.Client/Services/UserSession.cs.md) + +### src/EchoHub.Client/Themes + +- [Theme](src/EchoHub.Client/Themes/Theme.cs.md) +- [ThemeManager](src/EchoHub.Client/Themes/ThemeManager.cs.md) + +### src/EchoHub.Client/UI + +- [MainWindow](src/EchoHub.Client/UI/MainWindow.cs.md) + +### src/EchoHub.Client/UI/Chat + +- [ChatColors](src/EchoHub.Client/UI/Chat/ChatColors.cs.md) +- [ChatLine](src/EchoHub.Client/UI/Chat/ChatLine.cs.md) +- [ChatListSource](src/EchoHub.Client/UI/Chat/ChatListSource.cs.md) +- [ChatMessageManager](src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md) +- [ChatSegment](src/EchoHub.Client/UI/Chat/ChatSegment.cs.md) +- [RenderHelpers](src/EchoHub.Client/UI/Chat/RenderHelpers.cs.md) +- [WelcomeBanner](src/EchoHub.Client/UI/Chat/WelcomeBanner.cs.md) + +### src/EchoHub.Client/UI/Dialogs + +- [AudioPlayerDialog](src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs.md) +- [ChannelPasswordDialog](src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs.md) +- [ConnectDialog](src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md) +- [CreateChannelDialog](src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md) +- [ProfileEditDialog](src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md) +- [ProfileViewDialog](src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md) +- [SearchDialog](src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md) +- [StatusDialog](src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md) +- [UpdateConfirmDialog](src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs.md) + +### src/EchoHub.Client/UI/Helpers + +- [DroppedFileParser](src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs.md) +- [EmojiHelper](src/EchoHub.Client/UI/Helpers/EmojiHelper.cs.md) +- [HexColorHelper](src/EchoHub.Client/UI/Helpers/HexColorHelper.cs.md) +- [NickColorHelper](src/EchoHub.Client/UI/Helpers/NickColorHelper.cs.md) + +### src/EchoHub.Client/UI/ListSources + +- [ChannelListSource](src/EchoHub.Client/UI/ListSources/ChannelListSource.cs.md) +- [SearchListSource](src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md) +- [UserListSource](src/EchoHub.Client/UI/ListSources/UserListSource.cs.md) + +### src/EchoHub.Core/Constants + +- [HubConstants](src/EchoHub.Core/Constants/HubConstants.cs.md) +- [MessageConventions](src/EchoHub.Core/Constants/MessageConventions.cs.md) +- [ValidationConstants](src/EchoHub.Core/Constants/ValidationConstants.cs.md) + +### src/EchoHub.Core/Contracts + +- [IChannelService](src/EchoHub.Core/Contracts/IChannelService.cs.md) +- [IChatBroadcaster](src/EchoHub.Core/Contracts/IChatBroadcaster.cs.md) +- [IChatService](src/EchoHub.Core/Contracts/IChatService.cs.md) +- [IEchoHubClient](src/EchoHub.Core/Contracts/IEchoHubClient.cs.md) +- [IMessageEncryptionService](src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md) +- [IUserService](src/EchoHub.Core/Contracts/IUserService.cs.md) + +### src/EchoHub.Core/DTOs + +- [AccountDtos](src/EchoHub.Core/DTOs/AccountDtos.cs.md) +- [AuthDtos](src/EchoHub.Core/DTOs/AuthDtos.cs.md) +- [ChatDtos](src/EchoHub.Core/DTOs/ChatDtos.cs.md) +- [CommonDtos](src/EchoHub.Core/DTOs/CommonDtos.cs.md) +- [InviteDtos](src/EchoHub.Core/DTOs/InviteDtos.cs.md) +- [ModerationDtos](src/EchoHub.Core/DTOs/ModerationDtos.cs.md) +- [ProfileDtos](src/EchoHub.Core/DTOs/ProfileDtos.cs.md) +- [ServerDtos](src/EchoHub.Core/DTOs/ServerDtos.cs.md) + +### src/EchoHub.Core/Models + +- [Attachment](src/EchoHub.Core/Models/Attachment.cs.md) +- [AttachmentKind](src/EchoHub.Core/Models/AttachmentKind.cs.md) +- [Channel](src/EchoHub.Core/Models/Channel.cs.md) +- [ChannelMembership](src/EchoHub.Core/Models/ChannelMembership.cs.md) +- [InviteCode](src/EchoHub.Core/Models/InviteCode.cs.md) +- [Message](src/EchoHub.Core/Models/Message.cs.md) +- [MessageType](src/EchoHub.Core/Models/MessageType.cs.md) +- [RefreshToken](src/EchoHub.Core/Models/RefreshToken.cs.md) +- [ServerRole](src/EchoHub.Core/Models/ServerRole.cs.md) +- [ServerStatsReport](src/EchoHub.Core/Models/ServerStatsReport.cs.md) +- [User](src/EchoHub.Core/Models/User.cs.md) +- [UserStatus](src/EchoHub.Core/Models/UserStatus.cs.md) + +### src/EchoHub.Core/Security + +- [RoomCrypto](src/EchoHub.Core/Security/RoomCrypto.cs.md) + +### src/EchoHub.Core/Services + +- [AsciiBannerService](src/EchoHub.Core/Services/AsciiBannerService.cs.md) +- [FileValidationHelper](src/EchoHub.Core/Services/FileValidationHelper.cs.md) +- [ImageToAsciiService](src/EchoHub.Core/Services/ImageToAsciiService.cs.md) + +### src/EchoHub.Server + +- [Program](src/EchoHub.Server/Program.cs.md) + +### src/EchoHub.Server.Irc + +- [IrcBroadcaster](src/EchoHub.Server.Irc/IrcBroadcaster.cs.md) +- [IrcClientConnection](src/EchoHub.Server.Irc/IrcClientConnection.cs.md) +- [IrcCommandHandler](src/EchoHub.Server.Irc/IrcCommandHandler.cs.md) +- [IrcGatewayService](src/EchoHub.Server.Irc/IrcGatewayService.cs.md) +- [IrcMessage](src/EchoHub.Server.Irc/IrcMessage.cs.md) +- [IrcMessageFormatter](src/EchoHub.Server.Irc/IrcMessageFormatter.cs.md) +- [IrcNumericReply](src/EchoHub.Server.Irc/IrcNumericReply.cs.md) +- [IrcOptions](src/EchoHub.Server.Irc/IrcOptions.cs.md) +- [IrcServiceExtensions](src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md) + +### src/EchoHub.Server/Auth + +- [JwtTokenService](src/EchoHub.Server/Auth/JwtTokenService.cs.md) + +### src/EchoHub.Server/Config + +- [ServerLogsOptions](src/EchoHub.Server/Config/ServerLogsOptions.cs.md) +- [SpamOptions](src/EchoHub.Server/Config/SpamOptions.cs.md) +- [StatsOptions](src/EchoHub.Server/Config/StatsOptions.cs.md) +- [UploadLimits](src/EchoHub.Server/Config/UploadLimits.cs.md) + +### src/EchoHub.Server/Controllers + +- [AuthController](src/EchoHub.Server/Controllers/AuthController.cs.md) +- [ChannelsController](src/EchoHub.Server/Controllers/ChannelsController.cs.md) +- [FilesController](src/EchoHub.Server/Controllers/FilesController.cs.md) +- [InvitesController](src/EchoHub.Server/Controllers/InvitesController.cs.md) +- [ModerationController](src/EchoHub.Server/Controllers/ModerationController.cs.md) +- [ServerController](src/EchoHub.Server/Controllers/ServerController.cs.md) +- [UsersController](src/EchoHub.Server/Controllers/UsersController.cs.md) + +### src/EchoHub.Server/Data + +- [EchoHubDbContext](src/EchoHub.Server/Data/EchoHubDbContext.cs.md) + +### src/EchoHub.Server/Hubs + +- [ChatHub](src/EchoHub.Server/Hubs/ChatHub.cs.md) + +### src/EchoHub.Server/Services + +- [ChannelService](src/EchoHub.Server/Services/ChannelService.cs.md) +- [ChatService](src/EchoHub.Server/Services/ChatService.cs.md) +- [DirectoryClaimStore](src/EchoHub.Server/Services/DirectoryClaimStore.cs.md) +- [FileCleanupService](src/EchoHub.Server/Services/FileCleanupService.cs.md) +- [FileStorageService](src/EchoHub.Server/Services/FileStorageService.cs.md) +- [LinkEmbedService](src/EchoHub.Server/Services/LinkEmbedService.cs.md) +- [MessageEncryptionService](src/EchoHub.Server/Services/MessageEncryptionService.cs.md) +- [MuteExpirationService](src/EchoHub.Server/Services/MuteExpirationService.cs.md) +- [PresenceTracker](src/EchoHub.Server/Services/PresenceTracker.cs.md) +- [ServerDirectoryService](src/EchoHub.Server/Services/ServerDirectoryService.cs.md) +- [SignalRBroadcaster](src/EchoHub.Server/Services/SignalRBroadcaster.cs.md) +- [SpamGuard](src/EchoHub.Server/Services/SpamGuard.cs.md) +- [UserService](src/EchoHub.Server/Services/UserService.cs.md) + +### src/EchoHub.Server/Services/ServerLogs + +- [ServerLogsService](src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md) +- [ServerLogsSink](src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs.md) +- [ServerLogsStreamService](src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs.md) + +### src/EchoHub.Server/Services/Stats + +- [ServerStatsCollector](src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md) +- [ServerStatsReportService](src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs.md) + +### src/EchoHub.Server/Setup + +- [DataMigrationService](src/EchoHub.Server/Setup/DataMigrationService.cs.md) +- [DatabaseSetup](src/EchoHub.Server/Setup/DatabaseSetup.cs.md) +- [FirstRunSetup](src/EchoHub.Server/Setup/FirstRunSetup.cs.md) + +### src/EchoHub.Tests/Irc + +- [TestHelpers](src/EchoHub.Tests/Irc/TestHelpers.cs.md) \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/AppOrchestrator.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/AppOrchestrator.cs.md new file mode 100644 index 0000000..93e42c6 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/AppOrchestrator.cs.md @@ -0,0 +1,2239 @@ +# AppOrchestrator.cs + +> **Source:** `src/EchoHub.Client/AppOrchestrator.cs` + +## Contents + +- [AppOrchestrator](#apporchestrator) + - [AppOrchestrator (constructor)](#apporchestrator-constructor) + - [MainWindow](#mainwindow) + - [PendingUpdate](#pendingupdate) + - [ApplyAsciiSize](#applyasciisize) + - [AsciiSizeLabel](#asciisizelabel) + - [BuildOutgoingAttachmentAsync](#buildoutgoingattachmentasync) + - [CleanupPastedTempFiles](#cleanuppastedtempfiles) + - [ClearPendingReply](#clearpendingreply) + - [Dispose](#dispose) + - [EnsureRoomUnlockedForSendAsync](#ensureroomunlockedforsendasync) + - [HandleChannelJoinFromMessage](#handlechanneljoinfrommessage) + - [HandleChannelSelected](#handlechannelselected) + - [HandleCmdAssignRole](#handlecmdassignrole) + - [HandleCmdBanUser](#handlecmdbanuser) + - [HandleCmdChangeRoomPassword](#handlecmdchangeroompassword) + - [HandleCmdClearAttachments](#handlecmdclearattachments) + - [HandleCmdCreateInvite](#handlecmdcreateinvite) + - [HandleCmdDeleteAccount](#handlecmddeleteaccount) + - [HandleCmdExportData](#handlecmdexportdata) + - [HandleCmdJoinChannel](#handlecmdjoinchannel) + - [HandleCmdKickUser](#handlecmdkickuser) + - [HandleCmdLeaveChannel](#handlecmdleavechannel) + - [HandleCmdListInvites](#handlecmdlistinvites) + - [HandleCmdListUsers](#handlecmdlistusers) + - [HandleCmdMeta](#handlecmdmeta) + - [HandleCmdMuteUser](#handlecmdmuteuser) + - [HandleCmdNukeChannel](#handlecmdnukechannel) + - [HandleCmdOpenServers](#handlecmdopenservers) + - [HandleCmdQuit](#handlecmdquit) + - [HandleCmdRevokeInvite](#handlecmdrevokeinvite) + - [HandleCmdSendAction](#handlecmdsendaction) + - [HandleCmdSendBanner](#handlecmdsendbanner) + - [HandleCmdSendFile](#handlecmdsendfile) + - [HandleCmdSetAsciiSize](#handlecmdsetasciisize) + - [HandleCmdSetAvatar](#handlecmdsetavatar) + - [HandleCmdSetColor](#handlecmdsetcolor) + - [HandleCmdSetNick](#handlecmdsetnick) + - [HandleCmdSetStatus](#handlecmdsetstatus) + - [HandleCmdSetTheme](#handlecmdsettheme) + - [HandleCmdSetTopic](#handlecmdsettopic) + - [HandleCmdTestSound](#handlecmdtestsound) + - [HandleCmdUnbanUser](#handlecmdunbanuser) + - [HandleCmdUnmuteUser](#handlecmdunmuteuser) + - [HandleConnect](#handleconnect) + - [HandleCreateChannelRequested](#handlecreatechannelrequested) + - [HandleDeleteMessageRequested](#handledeletemessagerequested) + - [HandleDisconnect](#handledisconnect) + - [HandleEditProfile](#handleeditprofile) + - [HandleFilesStaged](#handlefilesstaged) + - [HandleImagePasted](#handleimagepasted) + - [HandleLoadMoreRequested](#handleloadmorerequested) + - [HandleLogout](#handlelogout) + - [HandleMessageSubmitted](#handlemessagesubmitted) + - [HandleProfileRequested](#handleprofilerequested) + - [HandleReplyCancelRequested](#handlereplycancelrequested) + - [HandleReplyRequested](#handlereplyrequested) + - [HandleSavedServersRequested](#handlesavedserversrequested) + - [HandleStatusRequested](#handlestatusrequested) + - [HandleThemeSelected](#handlethemeselected) + - [HandleViewProfile](#handleviewprofile) + - [InvokeUI](#invokeui) + - [JoinChannelWithPasswordPromptAsync](#joinchannelwithpasswordpromptasync) + - [NeedsUnlockPrompt](#needsunlockprompt) + - [NormalizeAsciiSize](#normalizeasciisize) + - [RunAsync](#runasync) + - [SendStagedMessage](#sendstagedmessage) + - [UnlockTrackedChannelAsync](#unlocktrackedchannelasync) + - [WireCommandHandlerEvents](#wirecommandhandlerevents) + - [WireConnectionManagerEvents](#wireconnectionmanagerevents) + - [WireMainWindowEvents](#wiremainwindowevents) +- [HandleCmdOpenProfile](#handlecmdopenprofile) +- [HandleSearchRequested](#handlesearchrequested) +- [PromptPassword](#promptpassword) +- [RefreshStagingTray](#refreshstagingtray) +- [UnlockRoomKeyAsync](#unlockroomkeyasync) + +--- + +## AppOrchestrator +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** class + +```csharp +public sealed class AppOrchestrator : IDisposable +``` + + +Central coordinator for the EchoHub terminal UI client: it wires MainWindow UI events and command input to the underlying services (connection manager, message manager, audio/update services, etc.), maintains ephemeral UI-facing state (staged attachments, per-channel user lists, temporary pasted files, declined E2E unlocks, pending reply targets), and exposes a small host-facing surface (MainWindow and PendingUpdate). Reach for AppOrchestrator when you need a single place to orchestrate cross-cutting app behavior rather than wiring UI components and services together manually. + +## Remarks +AppOrchestrator exists to centralize responsibilities that span UI, networking and local client state so the rest of the codebase can remain focused: UI widgets raise events and the orchestrator translates those into service calls, and connection/service events are translated back into UI updates. It owns short-lived caches (case-insensitive channel user lists), staging buffers (attachments and temporary pasted files), and user-interaction policies (for example, remembering which E2E unlock prompts were declined so the user isn't repeatedly nagged). It also exposes PendingUpdate so the host can perform an in-place restart safely after the TUI's main loop exits. + +## Notes +- PendingUpdate must be executed by the host only after the Terminal.Gui main loop and TUI have exited (console restored); running the updater while the TUI is still active can conflict with terminal state and in-place restart behavior. +- Temporary PNG files created for clipboard-image pastes are tracked and removed when their message is sent or when the staging tray is cleared—do not assume pasted screenshots persist on disk indefinitely. +- The channel user cache is case-insensitive (StringComparer.OrdinalIgnoreCase) and is guarded by an internal lock; callers should not bypass the orchestrator to modify that state directly. + + + +--- + +### AppOrchestrator (constructor) +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** constructor + +```csharp +public AppOrchestrator(IApplication app, ClientConfig config) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `app` | `IApplication` | — | +| `config` | [`ClientConfig`](Config/ClientConfig.cs.md) | — | + + +The AppOrchestrator constructor initializes the client by capturing the application context and configuration, creating core UI and service collaborators, wiring their inter-component events, and starting the update checker. It then initializes the main window with a disconnected state, readying the app for user interaction. + +## Remarks +As the composition root for the EchoHub client, AppOrchestrator centralizes the creation and wiring of the UI and service layer. It ensures that all collaborators exist before the app becomes interactive and that the event pipelines are in place so user actions, commands, and connection state changes flow through a single, predictable lifecycle. The initial 'Disconnected' status communicates to users that the app is not yet connected, and will transition as connections and updates occur. + +## Notes +- The constructor immediately starts the update checker via Start(); this can trigger asynchronous network activity during startup. +- The initialization sequence assumes non-null app and config; null values will throw during assignment. +- Be mindful of multiple AppOrchestrator instances: event subscriptions are established in the constructor and may accumulate if the object is created more than once. + +--- + +### MainWindow +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** property + +```csharp +public MainWindow MainWindow => _mainWindow +``` + + +Exposes the application's main window as a read-only property. It returns the private _mainWindow field, allowing callers to access the current MainWindow instance without exposing a setter or the backing field directly. Use this property when UI or orchestration code needs to interact with the main window in a controlled way, e.g., to trigger window-bound actions or dialogs, while preserving encapsulation. + +## Remarks +This property serves as an abstraction boundary between the app orchestrator and the UI layer. It decouples consumers from the concrete storage of the main window and provides a stable access point that can be replaced or mocked in tests without changing call sites. It also communicates ownership: the orchestrator owns and manages the MainWindow reference. If initialization order guarantees the value, callers can rely on its presence; otherwise, guard against nulls. + +## Notes +- Access before initialization may yield null; ensure initialization before first use. +- If the main window can be swapped at runtime (for testing or multi-window scenarios), consider adding a controlled mechanism to rebind the reference or introduce an interface the rest of the code depends on. +- This property is a simple passthrough of the backing field; for testability, consider introducing an abstraction (e.g., IMainWindow) if you need to mock interactions with the window. + +--- + +### PendingUpdate +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** property + +```csharp +public Func? PendingUpdate => _updateService.PendingUpdate +``` + + +PendingUpdate is a nullable `Func` that becomes non-null once the user confirms an in-app update. The host should invoke this function after the Terminal.Gui main loop exits and the console has been restored, allowing the updater to restart in-place without fighting the TUI. This property simply proxies the update action from the update service, decoupling the UI lifecycle from the restart logic. + +## Remarks +PendingUpdate exists to separate the moment of user confirmation from the actual restart work. It ensures the update runs after the UI has been torn down, avoiding conflicts with the Terminal.Gui lifecycle. By delegating to the update service's PendingUpdate, the hosting code remains agnostic of the specifics of how updates are performed. + +## Example +```csharp +// After the Terminal.Gui loop completes and the UI is torn down +var pending = appOrchestrator.PendingUpdate; +if (pending != null) +{ + await pending.Invoke(); +} +``` + +## Notes +- PendingUpdate may be null; guard against null before invoking. +- Because it returns a Task, await the invocation to ensure the update process completes (as appropriate for your app lifecycle). +- Call this only after the UI teardown to avoid interfering with the TUI. + +--- + +### ApplyAsciiSize +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void ApplyAsciiSize(string flag) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `flag` | `string` | — | + +**Returns:** `void` + + +Applies a user-selected ASCII size by updating the in-memory configuration, persisting it to disk, and refreshing the staging UI. If a current channel is active, it also broadcasts a system message to inform users that the image ASCII size has been updated, formatting the value via AsciiSizeLabel(flag). + +## Remarks +This method centralizes the side effects of changing the ASCII size: it updates the config, persists the change, updates the staging tray, and notifies the channel. It relies on AsciiSizeLabel to render a user-friendly label and on ConfigManager.Save to persist settings; callers should be aware exceptions from these operations propagate to the caller. + +## Notes +- Assumes _config is non-null; a null _config would cause a NullReferenceException. +- No input validation: the flag string is stored directly and passed to AsciiSizeLabel; ensure downstream code handles invalid values. +- Synchronous IO: ConfigManager.Save(_config) may block if disk IO is slow; consider invoking from a background task if called from UI event handlers. + +## Dependencies +- ConfigManager + +## Dependency APIs (verified signatures) + +- class [`ConfigManager`](Config/ConfigManager.cs.md) (`src/EchoHub.Client/Config/ConfigManager.cs`) + - field `string ConfigDir` + - field `string ConfigPath` + - property `string ConfigDirectory` + - field `Lock FileLock` + - field `JsonSerializerOptions JsonOptions` + - `ClientConfig Load()` + - `void Save(ClientConfig config)` + - `void SaveServer(SavedServer server)` + - `void RemoveServer(string url)` + +## Symbol To Document +- Name: `ApplyAsciiSize` +- Kind: `method` +- File: `src/EchoHub.Client/AppOrchestrator.cs` +- Language: `csharp` +- ID: `db251379-6f70-4217-ba11-e574fbf08e9d` + +--- + +### AsciiSizeLabel +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private static string AsciiSizeLabel(string flag) => flag switch +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `flag` | `string` | — | + +**Returns:** `string` + + +Converts a single-character size flag into a human-readable ASCII size label used by the UI. This private helper centralizes the mapping so callers don't duplicate string literals across the codebase. For flag \"s\" it yields \"Small (40x40)\", for flag \"l\" it yields \"Large (120x120)\", and for any other value it yields \"Medium (80x80)\". + +## Remarks +By keeping the label logic in one private, static method, the rest of the codebase benefits from a single source of truth for size labels. The switch expression makes the mapping straightforward to extend if new flags are introduced. Its private scope keeps coupling low and makes intent explicit within its containing type. + +## Example +```csharp +// Example usage within the same class +string small = AsciiSizeLabel("s"); // "Small (40x40)" +string defaultLabel = AsciiSizeLabel("x"); // "Medium (80x80)" +``` + +## Notes +- Access scope: AsciiSizeLabel is private to its declaring type, so it cannot be called from outside the class. If external callers need the same mapping, expose a public wrapper or move the method to a shared utility. + +--- + +### BuildOutgoingAttachmentAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private static async Task BuildOutgoingAttachmentAsync(string path, byte[]? roomKey, string size) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `path` | `string` | — | +| `roomKey` | `byte[]?` | — | +| `size` | `string` | — | + +**Returns:** `Task` + + +Reads a staged file into an OutgoingAttachment. If a roomKey is provided, the method reads the file into memory, determines whether it is a valid image, and for images generates a local ASCII preview using ImageToAsciiService at the requested size; the preview text is then encrypted with roomKey. The file bytes are encrypted with RoomCrypto and encapsulated in the attachment; the attachment also records a declaredKind of image, audio, or file, and includes the (encrypted) preview when available. If no roomKey is supplied, the method returns an OutgoingAttachment that streams the file directly with its name, skipping encryption and preview generation. This design enables end-to-end protection in encrypted channels while keeping behaviors for non-encrypted channels simple. + +## Remarks +This method acts as the orchestration point for turning a local file into the transportable OutgoingAttachment used by the client’s outbound pipeline. It encapsulates the conditional encryption and, for images, an on-device ASCII preview to surface a visual cue without exposing the raw image. By delegating validation, ASCII rendering, and crypto to dedicated helpers, it keeps the code focused on assembling the attachment rather than the details of how each piece works. + +## Notes +- If roomKey is null, the file is streamed directly without encryption or a preview. +- Large files will be fully loaded into memory for encryption; consider streaming or chunking if this is a concern. +- The preview is only produced for valid images; non-image files skip the preview. + +--- + +### CleanupPastedTempFiles +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private static void CleanupPastedTempFiles(IReadOnlyList files) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `files` | `IReadOnlyList` | — | + +**Returns:** `void` + + +Best-effort cleanup of pasted-image temp files and their per-paste folders. The method iterates the provided file paths, deletes each file, and then attempts to remove the containing directory if present; any failures are caught and logged at Debug level, so cleanup does not disrupt the calling workflow. + +## Remarks +Encapsulates the cleanup behavior so the paste pathway remains focused on its primary task. It uses a forgiving error-handling strategy: delete what you can, swallow failures, and report them only via debug logs. Because the directory deletion happens after the file removal, the directory will be removed only if it is empty, aligning with typical per-paste directory semantics. + +## Notes +- Directory.Delete is non-recursive by default; the directory will be removed only if empty after file deletion. +- Exceptions are swallowed; failures are only logged at Debug level; callers can't rely on exceptions to signal cleanup success. + +--- + +### ClearPendingReply +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void ClearPendingReply() +``` + +**Returns:** `void` + + +Clears the active pending-reply state by assigning null to the internal _pendingReply field and informing the UI that there is no current reply in progress by calling _mainWindow.SetReplyingTo(null). As a private helper, it's used within the orchestrator to finalize or abort the reply workflow and keep both the data and the user interface in sync. + +## Remarks +Centralizes reply-cleanup logic to avoid duplicating state-management across multiple code paths. By updating both the internal _pendingReply and the main window's replying-to state in one place, it guarantees consistent behavior whenever the reply flow ends. This abstraction helps decouple the decision to clear a reply from the specific UI or flow that triggers it, making future changes to the cleanup process easier. + +## Notes +- Must run on the UI thread due to SetReplyingTo updating the UI; calling from a background thread may cause cross-thread exceptions or UI glitches. + +--- + +### Dispose +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +public void Dispose() +``` + +**Returns:** `void` + + +Disposes EchoHub client resources in a defined teardown order. On disposal, it persists the last reads, then synchronously disposes the underlying connection, and finally disposes the update service. Call this when the orchestrator is shutting down to ensure all resources are released and the connection is cleanly closed. + +## Remarks +This Dispose implements a synchronous disposal flow that bridges an asynchronous disposal of the connection. The explicit GetAwaiter().GetResult() ensures the connection is fully closed before proceeding, but it can introduce deadlocks if called on a synchronization context that blocks. The order of operations — persist reads, close connection, then dispose updates — ensures state is captured before teardown and that dependent services are torn down only after the connection is terminated. + +## Notes +- Blocking on asynchronous disposal can lead to deadlocks in certain synchronization contexts; prefer calling this from a non-UI thread or consider an asynchronous disposal pattern if possible. +- If an exception is thrown during PersistLastReads, DisposeAsync, or _updateService.Dispose, disposal may be interrupted and not all resources may be released. +- This method is not guarded for multiple invocations; repeated calls may encounter disposed resources. + + +--- + +### EnsureRoomUnlockedForSendAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task EnsureRoomUnlockedForSendAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +This private guard ensures outbound messages to a channel are only sent when the room is accessible: if the channel is not end-to-end encrypted or already has a key, sending is allowed immediately. If the channel is encrypted but locked, it triggers the unlock flow and returns true only when unlocking succeeds; otherwise it reports an error and blocks the send. + +## Remarks +By centralizing the gating logic here, the sending path consistently enforces encryption constraints and user interaction for unlocking. It bridges the connection manager's RoomKeys state, the unlocking prompt, and the UI feedback loop so callers don't have to duplicate this logic. Keeping this logic in this dedicated helper reduces the risk of inconsistent encryption checks scattered across the codebase. + +## Notes +- Short-circuits and returns true if the channel doesn't require unlocking or already has a key; otherwise it may present an unlock prompt and potentially abort the send. +- If unlocking is required, it calls UnlockTrackedChannelAsync and may present a prompt to the user; a declined or failed unlock results in a false return and an error message. +- It relies on the RoomKeys state and uses UI feedback (via _mainWindow.ShowError) to communicate failures to the user; callers should respect the returned boolean and refrain from sending when false. + +--- + +### HandleChannelJoinFromMessage +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleChannelJoinFromMessage(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Responds to a request to join a channel coming from a message by first ensuring the connection is active; if not connected, it exits early. When connected, it marshals execution to the UI thread, guarantees the channel is present in the UI channel list, switches the UI to that channel, and then delegates to HandleChannelSelected to trigger further channel-activation handling. + +## Remarks +Acts as the glue between the messaging flow and the UI state. By marshaling to the UI thread and centralizing the sequence of ensuring the channel exists and becomes active, it helps prevent cross-thread issues and keeps the UI in sync with inbound join requests. The subsequent call to HandleChannelSelected ensures that any additional, per-channel activation logic is applied in a single, well-defined step. + +## Notes +- No input validation is performed on channelName here; downstream UI methods may interpret empty or invalid values in different ways. Validate as needed at call-sites if that matters for your scenario. +- The method is a no-op when not connected, so callers relying on its side effects must ensure connection lifecycle is managed appropriately. + +--- + +### HandleChannelSelected +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleChannelSelected(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +HandleChannelSelected is invoked when a user selects a channel in the client UI. It first verifies the client is connected and returns immediately if it is not; it also clears any pending reply that does not belong to the newly selected channel and persists the last-read positions before switching context. + +In the asynchronous workflow that follows, the method attempts to track the selected channel. If tracking succeeds, it prompts for a password as needed and, on a successful join, clears the left-channel exclusion for the joined channel. If the user cancels the password prompt, the channel is untracked and the UI switches back to the default channel. If tracking is not required but an unlock is needed, it triggers an unlock of the tracked channel. + +After handling join/unlock, the method tries to retrieve the channel history and load it into the UI; failures to fetch history are ignored. Finally, it refreshes the list of online users. + + +--- + +### HandleCmdAssignRole +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdAssignRole(string username, string roleStr) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `roleStr` | `string` | — | + +**Returns:** `Task` + + +Processes a user-issued command to assign a role to a specific user. It short-circuits when the current connection is not authenticated, preventing unauthorized role changes. It normalizes the incoming role string into a ServerRole enum (admin maps to Admin, mod to Mod, and any other value defaults to Member) and then calls the server API to apply that role to the given username. + +## Remarks +Acts as a small wrapper around the underlying API to centralize access control and input normalization for role assignment commands. By guarding the operation behind the authentication check, it ensures only authenticated sessions can modify roles. The conservative default to Member for unknown role strings provides a safe fallback that avoids elevating privileges due to unrecognized input. + +## Notes +- The operation does nothing if the client is not authenticated. +- Despite the authentication check, Api is accessed with a null-forgiving operator; if _conn.Api is null, this will throw at runtime. Ensure the API client is initialized alongside authentication. +- The role default to Member for unknown values can mask invalid input; if explicit validation is desired, this behavior may need to be revisited. + +--- + +### HandleCmdBanUser +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdBanUser(string username, string? reason) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `reason` | `string?` | — | + +**Returns:** `Task` + + +Handles the ban-user command by ensuring the client is authenticated and then delegating to the API to perform the ban. It accepts a target username and an optional reason; if the current connection is not authenticated, it returns without taking action. When authenticated, it invokes BanUserAsync on the API, passing along the username and reason. + +## Remarks +This method acts as a focused command handler: it enforces authentication and delegates the ban operation behind a single, well-defined API boundary. By isolating the authentication gate here, the rest of the command processing remains decoupled from the specifics of how a ban is performed. Any failures from BanUserAsync propagate to the caller, enabling centralized error handling or user feedback at a higher level. + +## Notes +- Silent return when not authenticated means callers may not observe a failure path for unauthenticated ban attempts; consider logging or surfacing a result if caller feedback is required. + +--- + +### HandleCmdChangeRoomPassword +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdChangeRoomPassword(string oldPassphrase, string newPassphrase) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `oldPassphrase` | `string` | — | +| `newPassphrase` | `string` | — | + +**Returns:** `Task` + + +Handles the user command to change the end-to-end encryption passphrase for the currently active channel. It validates that the client is authenticated and connected, that a channel is selected and encrypted, and then re-derives the join credentials for both the old and new passphrases. It then asks the backend to re-key the channel by wrapping the cached room key with the new derived key. History remains readable; the room key itself does not change, so previously encrypted content stays decryptable by existing history, while new members/devices must use the new passphrase. + +## Remarks +This function coordinates client state (the current channel and the cached room key) with a server-side RekeyChannelAsync call to effect a passphrase transition. It guards against common failure modes (not authenticated, no channel selected, channel not end-to-end encrypted, missing room key) by showing targeted UI errors. The derived key material (old and new) and a fresh salt ensure that only someone with the new passphrase can wrap/unwrap the room key going forward. + +## Notes +- If the channel is not end-to-end encrypted or lacks an encryption salt, the operation aborts with a user-facing error. +- The action requires that the room key for the channel is cached; otherwise the user is prompted to unlock/rejoin the channel. +- The change does not re-encrypt historical messages; it only re-wraps the room key under the new passphrase, so access for existing history remains intact while access for new participants depends on the new passphrase. + +--- + +### HandleCmdClearAttachments +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdClearAttachments() +``` + +**Returns:** `Task` + + +Clears the currently staged attachments, removing any files that are also present in the temporary pasted set, cleans up their temporary copies, clears the staging collection, and refreshes the staging UI. Invoke this when the user requests to discard all attachments added during the current operation; it centralizes the cleanup logic to keep in-memory state and the UI in sync. + +## Remarks + +This method coordinates between in-memory state (_stagedAttachments), the temporary-file tracking (_tempPastedFiles), and the UI update path (InvokeUI(RefreshStagingTray)). By encapsulating the cleanup sequence, callers avoid duplicating disposal and UI-refresh logic, and it guarantees that temporary files created for pasted content are removed in tandem with the in-memory state. + +## Example + +```csharp +// Example usage within the same class +private async Task DemoClearAttachmentsUsage() +{ + await HandleCmdClearAttachments(); +} +``` + +## Notes + +- The method returns Task.CompletedTask, so from a caller's perspective it is effectively synchronous; awaiting it does not introduce real asynchronous work. +- If other code mutates _stagedAttachments or _tempPastedFiles concurrently, results may be inconsistent; this method assumes a single-threaded (UI) invocation context. +- If CleanupPastedTempFiles(temps) throws, the task will fault; callers should consider exception handling around the command invocation. + +--- + +### HandleCmdCreateInvite +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdCreateInvite(int? maxUses, int? expiresHours) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `maxUses` | `int?` | — | +| `expiresHours` | `int?` | — | + +**Returns:** `Task` + + +Creates a channel-scoped invite by calling the API with the optional maxUses and expiresHours and displays the resulting code in the current channel; it includes uses, an optional expiry, and a tip to revoke with a slash command. If the user is not authenticated or there is no current channel, it exits early and performs the work asynchronously to keep the UI responsive. + +## Remarks +This method orchestrates authentication state, UI context, and remote API to provide a seamless command experience. It isolates the network call and UI update from the main thread using RunAsync, reducing UI latency and potential blocking, while presenting the user with a clear revoke path to manage the created invite. + +## Notes +- Relies on _conn.Api being non-null after authentication; if that invariant is violated, the null-forgiving operator may lead to a NullReferenceException. +- The expiry timestamp is formatted in local time when available, via ToLocalTime with the pattern "yyyy-MM-dd HH:mm". +- The outer method returns Task.CompletedTask immediately; the actual invite creation and UI update run asynchronously, so callers should not expect any awaitable work from this method. + + +--- + +### HandleCmdDeleteAccount +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdDeleteAccount() +``` + +**Returns:** `Task` + + +Deletes the currently authenticated user’s account from the server as part of the user command workflow. It first ensures the client is authenticated, presents a destructive confirmation dialog explaining that the account will be permanently removed (including profile, sessions, and uploaded files, with messages remaining attributed to 'deleted-user'), and only proceeds if the user confirms. If confirmation is given, it prompts for the account password, then asynchronously performs the deletion via the server API, clears saved tokens for the server, and performs cleanup. On success, the UI is reset (main window cleared, status set to Disconnected) and the user is informed that the account and uploaded data have been deleted. + +The operation is designed to run asynchronously to keep the UI responsive and to encapsulate the end-to-end flow of a high-risk action within a single command handler. + +--- + +### HandleCmdExportData +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdExportData() +``` + +**Returns:** `Task` + + +Exports the authenticated user\'s data by calling the server API and writing the resulting JSON to a timestamped file in the local downloads directory. The file is named echohub-export-{username}-{yyyyMMdd-HHmmss}.json to avoid collisions. The operation runs asynchronously so the UI remains responsive. After the file is created, a system message is posted to the current channel (if any) indicating the destination path and clarifying that the content is ciphertext and the server never had plaintext. + +## Remarks +The method centralizes the data-export workflow behind a command handler, encapsulating authentication gating, local persistence, and user feedback. It ensures the UI remains responsive by offloading work to an asynchronous runner and then dispatching a UI update once the export completes. This abstraction keeps the channel-communication logic separate from the networking and file-system concerns, making the export action reusable from the UI command surface. + +## Notes +- The final user notification is sent only when a non-empty channel is present; otherwise, no in-channel message is posted. +- If authentication fails, the method completes without performing the export, avoiding unnecessary work or side effects. +- The exported payload is treated as ciphertext in the UI message, reflecting that the server-side data is not plaintext within the export artifact. + +--- + +### HandleCmdJoinChannel +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdJoinChannel(string channelName, string? password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `password` | `string?` | — | + +**Returns:** `Task` + + +Handles the user command to join a channel by validating the connection, prompting for a password when required, removing any left-channel exclusion for the channel on success, updating the UI to include and switch to the channel, and loading previous history if available. It is invoked as part of the command execution flow when a user requests to join a channel, encapsulating the join logic and related UI updates in one place. + +## Remarks +It centralizes the channel-join flow in AppOrchestrator, coordinating connection state, password prompting, server configuration, and UI navigation. By clearing the left-channel exclusion on join (RemoveAll with a case-insensitive match), it ensures a fresh entry for the channel. UI updates are dispatched to the main thread via InvokeUI, and history loading is triggered when available, keeping the user experience cohesive even when past sessions exist. + +## Notes +- Skips work if there is no active connection; the method exits early when _conn.IsConnected is false. +- If the password prompt is canceled (history is null), the join is aborted without altering server state or UI. +- The cleanup of LeftChannels uses a case-insensitive match to ensure the channel name is removed regardless of casing. +- Exceptions are caught and shown to the user via the main window, which prevents the app from crashing but may hide internal details. + +--- + +### HandleCmdKickUser +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdKickUser(string username, string? reason) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `reason` | `string?` | — | + +**Returns:** `Task` + + +Handles the Kick User command by delegating to the underlying API to remove a user from the session. Before performing the kick, it checks that the connection is authenticated; if not, it exits without taking action. When authenticated, it calls KickUserAsync on the API, passing the target username and the optional reason. This method centralizes the guard logic and the actual kick call under a single handler, so higher-level command processing can rely on a single moderation action point rather than invoking the API directly. + +## Remarks +Acts as a boundary between command parsing and server-side moderation actions. It ensures that only authenticated sessions can initiate a kick, preventing unauthorized disruptions. The use of the null-forgiving operator on Api implies the API instance is expected to be non-null once authentication is established; this contract should be preserved by the surrounding code. + +## Notes +- Be aware that Api is accessed with the null-forgiving operator, so a non-null Api is required after authentication; otherwise a NullReferenceException may be thrown. +- Exceptions from KickUserAsync propagate to the caller; callers may need to catch and handle errors (e.g., log failures or surface user-visible errors). +- The reason parameter is optional; passing null means no reason will be recorded. + +--- + +### HandleCmdLeaveChannel +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdLeaveChannel() +``` + +**Returns:** `Task` + + +Handles the user command to leave a channel. It exits early when not connected or when no channel is selected, blocks leaving the default channel, calls LeaveChannelAsync, records the leave in the server configuration's LeftChannels so auto-join won't pull you back in, and posts a system message confirming the departure. If something goes wrong, it reports the error to the UI. + +## Remarks +Coordinates UI feedback, connection state, and user preferences. It separates the transient action of leaving a channel from the persistent config, ensuring the user's choice is remembered and doesn’t get undone by auto-join logic on reconnect. The UI thread marshalling via InvokeUI and the defensive checks guard against invalid states and repeated leaves. + +## Notes +- If the user is not connected or no channel is selected, the method returns without side effects. +- Leaving the DefaultChannel is explicitly blocked to avoid breaking the core chat experience. +- LeftChannels is updated using a case-insensitive check (OrdinalIgnoreCase) to deduplicate and persist the user's choice across sessions. +- Any exception during LeaveChannelAsync is surfaced to the user via ShowError. + +--- + +### HandleCmdListInvites +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdListInvites() +``` + +**Returns:** `Task` + + +After verifying authentication and a current channel, this method fetches invite codes from the API, formats each invite’s usage and state into a readable list, and posts the result as a system message to the active channel. If no invites exist, it guides the user on how to create one. + +## Remarks + +Serves as the UI-facing adapter for the invite-list feature by coordinating API access, formatting, and UI updates. Each invite is categorized as used up, expired, or active based on UseCount, MaxUses, and ExpiresAt: used up when UseCount >= MaxUses; expired when ExpiresAt has a value and is in the past; otherwise active. If ExpiresAt has a value, the expiration date is shown in local time using the format yyyy-MM-dd HH:mm. The multi-line message is posted to the channel via InvokeUI to ensure thread-safety, and failures are surfaced by RunAsync with the message Failed to list invites. + +## Notes + +- Early exits guard: returns Task.CompletedTask if not authenticated or there is no current channel, preventing API calls or UI updates. +- The method accesses _conn.Api using the null-forgiving operator, which assumes Api is non-null after authentication. +- Expiration handling relies on ExpiresAt being present to show an expiration timestamp and formats it using local time; if ExpiresAt is null, the invite is considered active unless UseCount/MaxUses dictate otherwise. + +--- + +### HandleCmdListUsers +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdListUsers() +``` + +**Returns:** `Task` + + +HandleCmdListUsers retrieves and displays the list of online users for the currently selected channel when the client is connected. It requests the online user list from the underlying connection and then updates the UI to present each user with their display name (falling back to username) and their status, including any status message. If there is no active connection or no channel selected, the method exits without performing work; any error during retrieval or UI update is caught and reported to the user. + +## Remarks +By centralizing the command handling for listing users, this method cleanly separates networking concerns from UI rendering. It uses InvokeUI to marshal updates to the main thread, ensuring thread-safety when modifying the UI. The rendered output displays a header indicating the channel, followed by one line per user that shows a display name and a textual status, including any optional status message when present. + +## Notes +- Guards against no connection or empty channel by returning early, making the call effectively a no-op in those cases. +- All exceptions during retrieval or UI updates are caught and surfaced to the user via a dialog, preventing crashes. +- The rendering relies on Status.ToString(); ensure Status is non-null in your UserSession model or guard accordingly to avoid potential NullReferenceException. + + +--- + +### HandleCmdMeta +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdMeta() +``` + +**Returns:** `Task` + + +Fetches the current channel's metadata from the API and renders a concise room-info block in the chat UI. The method only runs when the client is connected and a channel is selected, and it gracefully handles missing metadata or API errors by reporting them to the user. + +## Remarks +This symbol acts as the UI-facing bridge between the network layer and the chat view, encapsulating the logic to fetch channel metadata and translate raw values into human-friendly text. It centralizes formatting decisions (such as the estimated size display and the protection status label) and ensures all UI updates occur on the UI thread through InvokeUI, preventing cross-thread UI mutations. By using early returns for preconditions and clear error signaling, it keeps the UI responsive and predictable even when the channel information cannot be retrieved. + +## Notes +- If meta.EstimatedSizeBytes <= 0, the size is displayed as "0 B"; otherwise the value is converted via FormatFileSize to a human-friendly string. +- When the API returns null for the channel metadata, the method surfaces a user-facing error {Channel #} not found to avoid throwing. +- All UI updates are dispatched to the UI thread via InvokeUI to maintain thread safety during cross-thread operations. + + +--- + +### HandleCmdMuteUser +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdMuteUser(string username, int? duration) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `duration` | `int?` | — | + +**Returns:** `Task` + + +Handles the mute-user command by delegating to the API after ensuring the client is authenticated. If the client is not authenticated, it exits early without performing any action. + +## Remarks +This method serves as a small glue layer between command-handling logic and the backend API. It enforces the precondition that only authenticated sessions can mute users and centralizes that guard in one place. The actual mute action is performed by the Api.MuteUserAsync call; the code uses the null-forgiving operator on Api, which implies Api must be non-null when IsAuthenticated is true. + +## Notes +- Silent no-op when not authenticated means callers may not see feedback; consider surfacing an explicit denial to the user at the call site. +- The null-forgiving operator on Api implies Api must be initialized for authenticated sessions; a mismatch could throw NullReferenceException. +- There is no cancellation support in this path; the caller cannot cancel the operation here. + +--- + +### HandleCmdNukeChannel +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdNukeChannel() +``` + +**Returns:** `Task` + + +This private async method performs a destructive operation on the currently selected channel by calling NukeChannelAsync on the authenticated API. It first ensures there is an authenticated connection and a non-empty channel; if either condition is not met, it returns early. Otherwise, it invokes the server-side NukeChannelAsync with the selected channel. + +## Remarks +This method encapsulates the preconditions required to perform a channel-nuke, keeping the UI-orchestrator code free from direct API calls. It acts as a gatekeeper, ensuring that only an authenticated user with a selected channel can trigger the destructive server-side operation. The actual deletion is delegated to the API via NukeChannelAsync; thus, changes to the nuking behavior should be made at the API level. + +## Example +```csharp +// Example usage from within the same class +await HandleCmdNukeChannel(); +``` + +## Notes +- The method relies on _conn.IsAuthenticated and a non-empty current channel; if _conn.Api is null at this point, the null-forgiving access (_conn.Api!) could produce a NullReferenceException. Ensure the API surface is initialized after authentication. +- The operation is destructive; it intentionally performs a server-side action only when preconditions are satisfied, and it swallows precondition failures by returning early without throwing. +- This method does not guard against changes to authentication or channel state between the precondition checks and the API call, so consider synchronization if those state changes can occur concurrently. + +--- + +### HandleCmdOpenServers +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdOpenServers() +``` + +**Returns:** `Task` + + +Dispatches a UI action to open the saved servers UI by invoking HandleSavedServersRequested on the UI thread, and returns a completed Task. It acts as a command-handling bridge that does not perform long-running work itself, delegating the actual UI work to the UI layer. + +## Remarks +Helps keep command-handling code decoupled from UI-thread specifics. This abstraction lets the orchestrator trigger UI flows without assuming any UI state or thread affinity, and it centralizes the UI-dispatch pattern via InvokeUI. + +## Notes +- The returned Task is completed immediately; the actual UI work runs asynchronously on the UI thread. +- Exceptions raised by HandleSavedServersRequested are not propagated through the returned Task and should be handled within the UI path. +- This method is private and intended for internal orchestration; callers should not rely on its Task representing the completion of the UI action. + +--- + +### HandleCmdQuit +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdQuit() +``` + +**Returns:** `Task` + + +HandleCmdQuit is a private command handler that initiates application shutdown by marshaling a stop request to the UI thread and returning a completed Task. It is intended for quit commands where the actual stop must be executed within the UI context. + +## Remarks +By funneling the stop through InvokeUI, this symbol ensures the shutdown sequence runs on the UI thread, preventing cross-thread access issues. It centralizes quit behavior in the orchestrator, keeping UI concerns isolated from the command-processing path. The method returns a completed Task to maintain an asynchronous signature, while the actual stopping occurs asynchronously on the UI thread via RequestStop. If the UI thread handling fails, the shutdown may surface as an exception in that context. + +## Notes +- It does not await the stop; the caller should not assume the application is fully stopped after this method returns. +- Exceptions during UI marshaling or in the UI thread may propagate outside this method. +- Assumes _app is non-null and that RequestStop is safe to call on the UI thread. + +--- + +### HandleCmdRevokeInvite +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdRevokeInvite(string code) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `code` | `string` | — | + +**Returns:** `Task` + + +HandleCmdRevokeInvite revokes an invite by code when the user issues the revoke command. It first ensures the client is authenticated and that a channel is currently selected; if either check fails, it completes without performing any action. When both conditions are met, it runs the revoke operation asynchronously against the API and, after revocation, inserts a system message into the active channel confirming that the invite has been revoked, using the code formatted in upper-case via ToUpperInvariant(). + +## Remarks +Encapsulates the command-handling concerns for invites by coordinating authentication state, channel context, API invocation, and UI feedback. The early returns prevent unnecessary API calls and potential exceptions in invalid contexts. Using RunAsync ensures the UI remains responsive and that failures surface with a clear error message ("Failed to revoke invite"). + +--- + +### HandleCmdSendAction +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdSendAction(string text) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `text` | `string` | — | + +**Returns:** `Task` + + +HandleCmdSendAction orchestrates sending a CTCP ACTION message to the currently selected channel. It guards against being disconnected or lacking a channel, and when invoked, schedules a background send that first unlocks the room for sending and then dispatches the formatted action payload through the established connection, preserving the encryption used for ordinary messages. + +## Remarks +This method centralizes the CTCP ACTION sending logic: it validates the connection and channel state, formats the action text using the project’s action conventions, and routes the payload through the same encrypted send path used for regular messages. By gating the unlock step with EnsureRoomUnlockedForSendAsync, it respects per-channel locking and avoids sending actions to rooms that are not ready for sending. The CTCP ACTION content therefore benefits from the same encryption, routing, and error handling as normal messages. + +## Notes +- The actual network send is performed asynchronously inside RunAsync; failures surface through the RunAsync error path with the message 'Send failed'. +- If EnsureRoomUnlockedForSendAsync(channel) returns false, no message is sent; the operation aborts gracefully. + +--- + +### HandleCmdSendBanner +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdSendBanner(string text) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `text` | `string` | — | + +**Returns:** `Task` + + +Handles the user command to render and send an ASCII banner to the currently selected channel. It validates connectivity and a non-empty channel, renders the banner via AsciiBannerService.Render, and, if rendering succeeds, dispatches a background task to ensure the room is unlocked before sending the banner over the active connection. If rendering yields nothing, it surfaces a UI error detailing the allowed characters and the maximum input length sourced from AsciiBannerService.MaxInputLength. + +## Remarks +Consolidates the end-to-end flow from user command to network transmission by coordinating the UI layer, the ASCII banner renderer, and the messaging connection. It delegates permission checks to EnsureRoomUnlockedForSendAsync and offloads the actual send to a background task via RunAsync, preserving UI responsiveness and isolating concerns among rendering, validation, and transport. + +## Notes +- Early exits (not connected or no channel) return immediately without user-facing feedback. +- Rendering failures produce a user-facing error rather than throwing, tying the UX to the banner rendering service. +- The error message reflects AsciiBannerService.MaxInputLength, tying user feedback to the configured rendering limits. +- The banner is sent only after EnsureRoomUnlockedForSendAsync(channel) confirms the room is unlocked. + +--- + +### HandleCmdSendFile +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdSendFile(string target, string? size) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `target` | `string` | — | +| `size` | `string?` | — | + +**Returns:** `Task` + + +Handles the /send command to attach local files or transmit a URL to the current chat channel, validating authentication and a selected channel; URLs are sent immediately for non-encrypted channels while local files are staged for a single subsequent message up to the attachment limit, and any provided size flag updates the default ASCII size for future sends. + +## Remarks + +URLs are sent immediately when allowed by the channel's encryption state, bypassing the staging area; local files are queued in a staging collection and dispatched together with a caption when the user confirms. This separation ensures encrypted channels remain protected and enforces HubConstants.MaxAttachmentsPerMessage to prevent oversized messages; UI refresh via the staging tray keeps the user informed of what will be sent. + +## Notes + +- URL sends are blocked in encrypted channels; users see an error guiding them to download the file and send it instead. +- If the user is not authenticated, not connected, or no channel is selected, the method returns a completed task without user feedback. +- The ASCII size flag updates a global default for subsequent sends rather than applying to the current staged set. + +--- + +### HandleCmdSetAsciiSize +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdSetAsciiSize(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Opens or sets the ASCII-art size for attached images. If a recognizable argument is supplied, the size is applied immediately; otherwise, a UI dialog prompts the user to choose Small, Medium, or Large, and the chosen size is persisted as a preference for future attachments. + +## Remarks +This method centralizes the user experience for configuring ASCII art size by handling both direct argument parsing and an interactive picker. Parsing is delegated to NormalizeAsciiSize, and the actual update is performed by ApplyAsciiSize, with UI-affecting work marshaled through InvokeUI to ensure thread-safety. The two-path design supports quick scripted usage and an explicit, user-driven selection while keeping behavior consistent. + +## Notes +- If the argument does not yield a non-null flag, the interactive picker is shown; pressing Cancel results in no change. +- The mapping from the picker result to the internal values is explicit (Small -> "s", Medium -> "m", Large -> "l"). +- The method completes its Task synchronously from the caller's perspective; UI updates are executed asynchronously via InvokeUI. + + +--- + +### HandleCmdSetAvatar +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdSetAvatar(string target) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `target` | `string` | — | + +**Returns:** `Task` + + +Handles the Set Avatar command by updating the user's avatar when the client is authenticated. It uploads the specified target avatar via AvatarHelper.UploadAsync using the current API client, and on success posts a system message in the current channel to indicate that the avatar was updated. If an error occurs, the method logs the exception and shows a user-facing error dialog with the exception message. + +## Remarks + +This method acts as an orchestration boundary between authentication, server communication, and UI feedback. It delegates the actual upload to AvatarHelper.UploadAsync and uses InvokeUI to marshal UI updates onto the UI thread. Because the method ignores the UploadAsync result, its success is determined solely by the absence of an exception. + +## Notes + +- If not authenticated, the method returns early with no side effects. +- The error path surfaces ex.Message to the user, which may reveal internal details; consider masking sensitive information in production. + +--- + +### HandleCmdSetColor +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdSetColor(string color) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `color` | `string` | — | + +**Returns:** `Task` + + +Handles a color-setting command by updating the current user's nickname color via the profile API, but only when the client connection is authenticated. If not authenticated it exits early without performing any update. When authenticated, it constructs an UpdateProfileRequest with NicknameColor set to the supplied color and invokes UpdateProfileAsync on the API client to persist the change. + +## Remarks +Acts as a small command handler within AppOrchestrator that translates a user-issued color command into a persistence operation. It cleanly separates command validation (authentication check) from the transport to the backend profile service, delegating the actual update to the API layer. + +## Notes +- The method relies on _conn.IsAuthenticated being accurate; if that state changes between the check and the API call, updates could occur inconsistently. +- It assumes _conn.Api is non-null after authentication (using the null-forgiving operator). If Api is unexpectedly null, a NullReferenceException may be thrown. +- There is no input validation on the color value; invalid colors may be rejected by the backend or cause API-side validation errors. +- Exceptions from UpdateProfileAsync propagate to the caller; callers should handle potential failures when updating the profile. + +--- + +### HandleCmdSetNick +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdSetNick(string displayName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `displayName` | `string` | — | + +**Returns:** `Task` + + +Handles nickname changes by persisting the new DisplayName to the server when the client is authenticated, and then updates the UI to reflect the new nickname and a connected status. If the client is not authenticated, it exits early without performing any network or UI changes. + +## Remarks +Centralizes the nickname-change flow inside the AppOrchestrator, bridging the command, network call, and UI update. The UI updates are marshaled via InvokeUI to ensure thread affinity, and the Api reference is assumed non-null once IsAuthenticated holds, as evidenced by the null-forgiving operator. + +## Notes +- The method uses _conn.Api! to pass UpdateProfileRequest to the API, relying on IsAuthenticated to guarantee Api is non-null; if that guarantee ever fails, a NullReferenceException could occur. +- No input validation of displayName is performed here; validation and sanitization should occur at higher layers or via server-side checks. + +--- + +### HandleCmdSetStatus +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdSetStatus(UserStatus? status, string? message) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `status` | `UserStatus?` | — | +| `message` | `string?` | — | + +**Returns:** `Task` + + +Handles the command to set the current user's status and optional message. It only executes when the client is connected; it determines the final status and message from the provided arguments, preserving existing values when an argument is omitted and clearing the message when an empty string is supplied. The method updates the remote server via UpdateStatusAsync and then synchronizes the local session state. + +## Remarks +This abstraction centralizes how a user-initiated status change is applied across both server and client state. It ensures consistent behavior for preserving or clearing values and guarantees the UI and session reflect the server after a successful update. The operation is a no-op when the connection is unavailable, avoiding unintended network activity. + +## Notes +- Early return when not connected means there is no network call or local state change in offline scenarios. +- Null status or null message preserves the current values; an empty message clears the status message. +- The server update is performed before mutating the local session; if UpdateStatusAsync throws, the session remains unchanged. + +## Dependencies +- _conn +- _session + +## Dependency APIs +- _conn.IsConnected: bool +- _conn.UpdateStatusAsync(UserStatus newStatus, string? newMessage): Task +- _session.Status: UserStatus +- _session.StatusMessage: string? + +## Symbol To Document +- Name: HandleCmdSetStatus +- Kind: method +- File: src/EchoHub.Client/AppOrchestrator.cs +- Language: csharp +- ID: 2eb21054-d449-44d8-a265-4b55287688a4 + +--- + +### HandleCmdSetTheme +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdSetTheme(string name) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `name` | `string` | — | + +**Returns:** `Task` + + +Marshals a theme-change request to the UI thread via InvokeUI by invoking HandleThemeSelected(name). It does not perform the theme switch itself; instead it queues the work on the UI thread and returns a completed Task. This is useful when a command handler or non-UI code needs to trigger a theme change while preserving proper UI thread affinity. + +## Remarks +HandleCmdSetTheme acts as a small bridge between command reception and UI state mutation. By decoupling the theme-name parameter from the actual UI update, it keeps non-UI layers free of UI-thread requirements and centralizes the invocation in InvokeUI. The pattern helps prevent cross-thread access issues while keeping a concise, test-friendly signature. + +## Notes +- Awaiting the returned Task does not guarantee the theme has been applied; the UI action runs asynchronously on the UI thread after this call returns. +- Exceptions raised during HandleThemeSelected occur on the UI thread and are not surfaced through this Task; consider handling errors inside the UI action or via a global UI exception handler. + +--- + +### HandleCmdSetTopic +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdSetTopic(string topic) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `topic` | `string` | — | + +**Returns:** `Task` + + +HandleCmdSetTopic is the internal handler for the user command that sets the topic of the current channel. It first guards against an unauthenticated user and a missing channel context; if either condition is not met, it exits without performing any update. When both checks pass, it updates the channel topic via the API, and on success it marshals back to the UI thread to refresh the display and emit a system message confirming the new topic. If an error occurs during the API call or UI update, it surfaces an error message to the user. + +## Remarks +This method serves as the glue between the command processing layer, the network API, and the user interface. It encapsulates the end-to-end workflow for a topic update: validation of preconditions, server-side update, and immediate UI feedback, ensuring consistent state across the client and server while minimizing duplication of error handling across the command pipeline. + +## Notes +- The API reference is accessed with a null-forgiving operator (_conn.Api!), so a null Api client can result in a NullReferenceException. Consider guarding Api’ availability or ensuring lifecycle management guarantees a non-null Api before invocation. +- If authentication is missing or there is no active channel, the method returns without user-facing feedback, which means callers should ensure appropriate UX messaging when these preconditions fail. +- Exceptions raised by the API call or by UI updates invoked in the success path are caught and surfaced as a user-visible error message; such exceptions are not propagated to the caller. + +--- + +### HandleCmdTestSound +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdTestSound() +``` + +**Returns:** `Task` + + +When invoked, this private async handler triggers a test playback of the notification sound by delegating to the injected _notificationSound and awaiting PlayTestAsync. It serves as a small command-handler within AppOrchestrator to validate audio feedback without blocking the command processing flow. + +## Remarks +Acts as a thin orchestration boundary, delegating to the notification sound service. This keeps the command-handling flow decoupled from the specifics of sound playback, enabling the sound provider to be swapped or mocked in tests. Being private ensures it's only called from within the orchestrator's command-processing logic, preserving encapsulation. + +## Notes +- No cancellation token is passed to PlayTestAsync from this wrapper; if cancellation is required, consider extending the API or wiring cancellation from the caller. +- Exceptions from PlayTestAsync will bubble up to the caller; consider adding error handling if resilience is needed in the command pipeline. + +--- + +### HandleCmdUnbanUser +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdUnbanUser(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task` + + +Unbans a user by delegating to the client API after confirming the current connection is authenticated. If the connection is not authenticated, the method returns immediately without performing any API call. When authenticated, it invokes Api.UnbanUserAsync with the provided username and awaits its completion, ensuring the operation completes asynchronously without blocking the caller. + +## Remarks +This method serves as a small command-handler primitive within the orchestration layer. It encapsulates the authentication check and the unban operation, so higher-level command wiring does not need to duplicate this guard. By awaiting the API call, it preserves responsiveness and enables proper exception propagation to the caller if the unban fails. The null-forgiving operator on Api expresses the expectation that the API client is prepared after a successful authentication handshake. + +## Notes +- Exceptions from Api.UnbanUserAsync may propagate to the caller; callers should handle errors at a higher level. +- If invoked while not authenticated, the method performs no action and returns immediately. + +--- + +### HandleCmdUnmuteUser +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task HandleCmdUnmuteUser(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task` + + +Unmutes a user by delegating to the remote API after verifying that the current session is authenticated. If the client is not authenticated, the method returns immediately without issuing any API call. + +## Remarks +This method is a small piece of the command-handling layer in AppOrchestrator. It couples the authentication check to the concrete unmute operation, ensuring that unmute requests are only sent to the API when a user is authenticated. By encapsulating this flow in one place, it keeps higher-level command logic focused on parsing input while the API interaction remains centralized and straightforward. + +## Notes +- No error handling within this method; any exception thrown by UnmuteUserAsync will propagate to the caller. +- If _conn.Api is null even after authentication, the null-forgiving operator is used, which will throw at runtime if the API reference is missing. +- The method is private, so its behavior is only observable within the containing class (and tests) and is not part of the public API. + +--- + +### HandleConnect +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleConnect() +``` + +**Returns:** `void` + + +HandleConnect coordinates the user-initiated connection workflow. It first checks whether a connection is already active and, if so, prompts the user to disconnect before proceeding; if the user confirms, it initiates a disconnect. Otherwise it shows a ConnectDialog to select a server and credentials, logs the attempt, and runs the asynchronous connection. It calls _conn.ConnectAsync and updates the status bar as the connection progresses. If a saved refresh token exists but the attempt fails due to an expired or revoked session, it logs a warning, clears the saved token, informs the user, and aborts the connection attempt. On success, it records the resulting login, clears any pending unlocks, loads the last-read markers for the target server from the saved config, and updates the UI: sets the current user, loads channels, switches to the default channel, loads per-channel histories (honoring lastRead where available), focuses the input, and fetches the list of online users. Finally it persists the selected server configuration. + +## Remarks +HandleConnect serves as the central flow controller that binds the UI to the authentication/connection protocol and the post-connection UI state. It isolates network logic from the UI by performing the connect work inside RunAsync and marshaling UI updates via InvokeUI; it also coordinates reading and applying per-server state (channels, histories, last-read markers) so the user sees an up-to-date workspace after connecting. + +## Notes +- It only handles a special exception path when a saved refresh token is present; other exceptions bubble to the RunAsync failure handler and surface a generic "Connection failed" message, so callers should be prepared for a generic error state. +- The last-read history seeding relies on the SavedServers list in the config; if the server URL isn't found, lastRead will be null and histories will start from the most recent history loaded from the server. + +--- + +### HandleCreateChannelRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleCreateChannelRequested() +``` + +**Returns:** `void` + + +Handles the user-initiated request to create a channel. It validates that the client is authenticated and connected, prompts the user for channel details via a dialog, and, if the user proceeds, performs the creation workflow asynchronously. If a password is provided for the channel, it derives a per-channel join credential and locally wraps a new room key so that the channel content remains end-to-end encrypted (the passphrase never leaves the client). The workflow includes salt generation, key derivation, room key generation, base64-encoding of the salt, and wrapping the room key with the derived key, before sending the resulting wirePassword, saltB64, and wrappedKey to the server. On success, any generated room key is stored for the channel, the client joins the channel, and its history is loaded if present. UI state is updated to show the new channel, set its topic, and switch focus to it, followed by a refresh of online users. If the user cancels the dialog or the channel creation fails, the method exits without side effects. + +The method orchestrates UI interaction, server communication, encryption preparation, and post-create UI updates in a single, cohesive flow, thereby providing a predictable and secure channel creation experience from a single entry point. + + +--- + +### HandleDeleteMessageRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleDeleteMessageRequested(Guid messageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messageId` | `Guid` | — | + +**Returns:** `void` + + +Deletes a message in response to a user-initiated delete request. + +The method first guards against unauthenticated calls by returning early if the connection is not authenticated. When authenticated, it delegates the actual deletion to the server via the API and relies on the server to enforce the hierarchy rule (own message or Mod+ over a strictly lower role) and to broadcast the deletion to all clients. The local message list is updated only in response to that broadcast, not by mutating internal state directly within this method. + +## Remarks + +This function acts as a thin bridge between the UI action (delete request) and the network operation, deferring permission checks to the server to ensure consistent enforcement across clients. It also centralizes error handling through RunAsync, which surfaces a user-facing message ("Failed to delete message") if the server operation fails. By relying on the server broadcast to refresh local state, it avoids duplicating deletion logic on the client and keeps the UI in sync with server-side state changes. + +## Example + +```csharp +// Called when the user confirms deletion of a message with ID messageId +HandleDeleteMessageRequested(messageId); +``` + +## Notes +- The method is a no-op when the connection is not authenticated, avoiding any local or server interaction. +- The local message list is updated via server broadcasts rather than direct mutation inside this method, ensuring consistency with server-side state and other clients. + +--- + +### HandleDisconnect +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleDisconnect() +``` + +**Returns:** `void` + + +Handles the disconnection sequence for the EchoHub client orchestrator. It is invoked when the connection to the server is lost or a deliberate disconnect is initiated. The method centralizes teardown steps to ensure a consistent, user-friendly shutdown: it logs the disconnect, clears per-channel user state under a dedicated lock, resets the pending reply to avoid processing stale data, updates the UI to reflect that no reply is expected, persists the last-read state, and then kicks off an asynchronous cleanup of the underlying connection. The UI is updated on the main thread to display a disconnected state after cleanup, preserving responsiveness during teardown. + +## Remarks +This abstraction exists to provide a single, well-defined path for disconnect scenarios, reducing the risk of partial teardown and inconsistent UI state across call sites. By guarding channel-user state with a lock, it prevents race conditions during teardown, and by marshaling UI updates through InvokeUI, it maintains proper thread affinity between background work and the UI. Running the cleanup asynchronously ensures the user interface remains responsive while the connection is terminated and resources are released. + +## Example +```csharp +// Example usage: internally invoked when the underlying connection reports a disconnect +HandleDisconnect(); +``` + +## Notes +- Clearing _channelUsers is performed under _channelUsersLock to prevent races with other threads that may access the collection during disconnect. +- _pendingReply is set to null to avoid handling a stale or invalid reply after disconnect. +- UI updates are dispatched through InvokeUI to guarantee execution on the UI thread, even when called from a background context. +- The actual connection teardown happens asynchronously via RunAsync, so any resulting UI changes (e.g., the status bar showing "Disconnected") occur after cleanup completes. + + +--- + +### HandleEditProfile +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleEditProfile(UserProfileDto? currentProfile) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `currentProfile` | `UserProfileDto?` | — | + +**Returns:** `void` + + +Drives the user-initiated profile editing flow. It opens a ProfileEditDialog pre-populated with the current profile values, and if the user submits changes, it updates the server (when authenticated), refreshes the UI with the new display name, and optionally uploads a new avatar. It also applies any updated notification settings and persists the updated profile as the default preset in the local configuration. + +It encapsulates the end-to-end sequence as an asynchronous operation: show the dialog, validate the result, perform server updates, and reflect changes in both the UI and local config. The operation is guarded by an authentication check and is executed via RunAsync to avoid blocking the UI thread, with careful UI updates performed on the main thread where appropriate. + +## Remarks +Centralizes the profile-edit workflow in a single coordinator: it integrates the user dialog, the remote profile update, avatar handling, notification preference updates, and the persistence of a default profile preset. This orchestration ensures consistency across server state, UI presentation (display name and status), avatar state, and locally stored configuration. + +## Notes +- The code uses _conn.Api! after verifying IsAuthenticated; if Api can be null in edge cases, this could throw at runtime. Consider guarding Api against nulls or enforcing a stronger invariant that IsAuthenticated implies a non-null Api. +- Avatar upload failures are isolated: an exception will be logged and a user-visible error shown, but the rest of the profile updates (name, bio, colors, notifications) still apply. + + +--- + +### HandleFilesStaged +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleFilesStaged(string channel, IReadOnlyList files) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channel` | `string` | — | +| `files` | `IReadOnlyList` | — | + +**Returns:** `void` + + +Stages a batch of local files (multi-file paste or drag-and-drop) as attachments for the next message. It executes synchronously on the UI thread to ensure the staged attachment list is updated before the message is sent, preventing races with the routing path. If the client is not authenticated or connected, it returns immediately. It adds only up to the remaining attachment slots, reports an error if more files were provided than can be staged, and then refreshes the staging tray. + +## Remarks +This method centralizes the per-message attachment staging logic, tying the UI state (`_stagedAttachments`) to the maximum allowed attachments (`HubConstants.MaxAttachmentsPerMessage`). It guarantees a deterministic UI update by running on the UI thread and by refreshing the staging tray after updates, reducing the chance of inconsistent attachment state when users paste many files quickly. + +## Notes +- The channel parameter is currently unused by this method. +- If files.Count exceeds the available slots, only the portion that fits is staged; the user is shown an error message and the extras are ignored. + +--- + +### HandleImagePasted +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleImagePasted(string channel, byte[] png) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channel` | `string` | — | +| `png` | `byte[]` | — | + +**Returns:** `void` + + +Handles an image pasted from the clipboard by staging it as a temporary PNG in a per-paste folder so it flows through the same path-based staging and encryption pipeline as regular attachments. The temporary file is deleted once the message is sent. + +If the client is not authenticated or connected, the method returns early without attempting to stage anything. + +If the attachment limit for the current message has been reached, it shows an error and returns. + +It uses a unique, per-paste folder under the system temporary path (EchoHub/pasted/{8-char}) to preserve the familiar image.png name while letting multiple pasted images coexist in a single message. It writes the PNG as image.png, tracks the path in the internal _tempPastedFiles and _stagedAttachments collections, and refreshes the staging tray UI. + +If anything goes wrong, it logs the exception and informs the user via the main window. + +## Remarks + +This symbol acts as a glue between clipboard paste handling and the attachment pipeline, reducing ad-hoc clipboard writes and ensuring consistent processing downstream. By isolating each paste, it avoids file-name clashes and keeps UI behavior predictable (the image shows as image.png, even when multiple pastes exist). It relies on the existing authentication/connection state and the global attachment limit to maintain a robust UX. + +## Notes + +- No operation occurs if the user is not authenticated or not connected; the method returns quietly in that case. +- Temporary files are not cleaned up by this method; cleanup occurs later in the message lifecycle when the message is sent. +- Pasting images enforces HubConstants.MaxAttachmentsPerMessage; once reached, a user-visible error is shown and gating prevents further staging. + + +--- + +### HandleLoadMoreRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleLoadMoreRequested() +``` + +**Returns:** `void` + + +Loads the next page of chat history for the currently selected channel when the user requests more messages. It executes asynchronously and prepends the retrieved history to the channel's message list, typically in response to a 'Load more' action in the chat UI. + +## Remarks + +Separates concerns by consolidating the load-more behavior in this method, acting as the bridge between the connection layer, the currently selected channel, and the in-memory history store. It uses RunAsync to perform the network call off the UI thread and InvokeUI to apply the updated history safely to the UI. The per-channel guard (_channelsLoadingMore) prevents overlapping loads for the same channel, preserving responsiveness when users tap repeatedly. + +## Notes + +- Exits early if the client is not connected or no channel is selected, avoiding unnecessary work. +- The fetch uses HubConstants.DefaultHistoryCount as the batch size and computes the offset from the current message count; a finally block ensures the per-channel loading flag is cleared even if the fetch fails, and RunAsync surfaces a 'Failed to load more messages' error to the user. + +--- + +### HandleLogout +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleLogout() +``` + +**Returns:** `void` + + +Orchestrates the end-to-end logout sequence for the client: it logs the logout, persists pending read state, and initiates an asynchronous server logout. It then conditionally clears the saved token based on the API base URL, performs cleanup, and updates the UI to show a disconnected state. + +## Remarks +This method centralizes the logout workflow in AppOrchestrator, coordinating server communication, local state cleanup, and UI transitions. It delegates UI changes to InvokeUI to guarantee thread-safety and relies on RunAsync to provide contextual error handling with the 'Logout error' title. + +## Notes +- ClearSavedToken(baseUrl) is invoked only when baseUrl is non-null, preventing token removal in contexts without a configured API. +- UI updates are scheduled on the main thread via InvokeUI to avoid cross-thread interaction issues. +- If LogoutAsync fails, RunAsync provides the contextual error information ('Logout error'); subsequent steps inside the lambda are contingent on successful logout. + +--- + +### HandleMessageSubmitted +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleMessageSubmitted(string channelName, string content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `content` | `string` | — | + +**Returns:** `void` + + +Handles the submission of a user-typed message for a specific channel. It validates the connection and routes the content through command handling, staged attachments, or a plain text send, while updating the UI with errors or system messages as appropriate. + +## Remarks + +This method serves as the central orchestrator for message submission, coordinating the UI layer, command processor, and network transport. It enforces preconditions (an active connection and an unlocked room) and uses asynchronous execution to avoid blocking the UI thread, ensuring proper state transitions such as clearing a pending reply after a successful send. + +## Notes + +- Not connected: shows an error and aborts before performing any network activity. +- Command handling: commands are detected via IsCommand; when HandleAsync returns a result with a non-null Message, the UI is updated either with an error (if IsError) or a system message. +- Message sending paths: if there are staged attachments, a staged message is sent with the caption and attachments; otherwise, if there is a per-channel pending reply, the message is sent with a replyTo ID; in all sending paths, EnsureRoomUnlockedForSendAsync is awaited; after a pending-reply send, ClearPendingReply is invoked on the UI thread. + +--- + +### HandleProfileRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleProfileRequested() +``` + +**Returns:** `void` + + +Handles the internal action when a profile is requested by the user. It delegates directly to HandleViewProfile(null), which triggers the shared profile-view workflow for the current user without requiring a specific user identifier. + +## Remarks +By routing through this private method, the code preserves a clean separation between the act of requesting a profile and the details of how a profile is displayed. It keeps the event-name binding lightweight while centralizing the actual view logic in HandleViewProfile. If future requirements ever need to view a non-current profile, this wrapper can be adapted or extended to pass a concrete identifier without broadening the public API. + +## Notes +- The wrapper relies on the null argument to signal 'current user' to the profile viewer; changing the contract of HandleViewProfile would require updating this method. +- Because the method is private, tests must exercise the public paths that lead to this method rather than invoking it directly. + +--- + +### HandleReplyCancelRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleReplyCancelRequested() => ClearPendingReply() +``` + +**Returns:** `void` + + +This private method handles a cancel request for a pending reply by clearing any in-progress reply state. It delegates to ClearPendingReply to perform the reset, providing a semantically meaningful hook within the orchestrator's reply lifecycle. + +## Remarks +By naming this hook, the code communicates intent: cancellation of a pending reply is a distinct moment in the flow, and all necessary cleanup should be centralized here. This makes future changes to the cancellation behavior easier to implement without touching multiple call sites. + +## Notes +- This method is private; external callers should trigger cancellation through public channels that eventually surface this path. +- It is a synchronous wrapper around ClearPendingReply; no asynchronous operations are performed in this method. + +--- + +### HandleReplyRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleReplyRequested(Guid messageId, string sender, string snippet) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messageId` | `Guid` | — | +| `sender` | `string` | — | +| `snippet` | `string` | — | + +**Returns:** `void` + + +Handles a user action to reply to a specific message. It first checks for an active channel from the main window; if none exists, it returns without altering any UI state. When a channel is present, it records the target message and channel as the pending reply, shortens the provided snippet to a concise preview (40 characters max, with an ellipsis added if truncation occurs), and updates the UI to show who is being replied to along with that preview. + +## Remarks +Handles the internal UX state for message replies by coupling the selected message (messageId) with its channel and exposing a concise preview to the user. This keeps the reply context consistent across subsequent actions without requiring the higher-level UI to recompute the target context on every interaction. It also prevents initiating a reply when there is no active channel. + +## Notes +- Early return when there is no current channel; the method exits without updating pending state or UI. +- Snippet truncated to 40 characters with a trailing ellipsis (the character '…') when longer, ensuring a compact in-UI preview. +- This method directly manipulates UI state via _mainWindow; callers should ensure execution on the appropriate UI thread to avoid cross-thread exceptions. + +--- + +### HandleSavedServersRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleSavedServersRequested() +``` + +**Returns:** `void` + + +Shows the list of saved servers to the user by reading from the configuration and presenting it in a modal dialog. If there are no saved servers, it informs the user that none exist. + +## Remarks +This method centralizes the presentation logic for saved servers, decoupling data retrieval from display concerns. It relies on the configuration's SavedServers collection and uses a straightforward LINQ projection to build human-readable lines, including a session indicator when a refresh token is present and the last connected date. The formatting rules (username fallback to ? and the optional [session saved] tag) are encapsulated here, making future changes localized to this UI path. + +## Notes +- The function renders a modal dialog via MessageBox.Query, which blocks until the user dismisses it; callers should ensure this is invoked on the UI thread. +- The last connected date is formatted as yyyy-MM-dd, a culture-invariant representation; if LastConnected can be default or null, this may warrant data validation upstream. +- Username defaults to "?" when missing, and a server is labeled with "[session saved]" only if RefreshToken is non-empty, tying display state to authentication/session data. + +--- + +### HandleStatusRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleStatusRequested() +``` + +**Returns:** `void` + + +Handles a user-initiated request to change the current status. It presents StatusDialog to gather a new status and optional message, updates the local session with the chosen values, and, if a connection is active, persists the change asynchronously via the connection. + +## Remarks +This method is the bridge between the UI dialog and the rest of the application's state. It encapsulates the common pattern of mutating local session state plus a conditional remote update, so callers don't need to duplicate the sequence. If the user cancels the dialog (StatusDialog.Show returns null), no state is changed. The remote update runs asynchronously and uses a dedicated error message, allowing the UI to remain responsive and errors to be surfaced in a uniform way. + +## Notes +- The local session state is updated regardless of connectivity; the remote update only runs when _conn.IsConnected. +- If the user cancels the dialog, indicated by a null result, the method returns without modifying state. +- This method is private; callers should trigger it through the UI flow rather than invoking it directly. + +--- + +### HandleThemeSelected +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleThemeSelected(string themeName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `themeName` | `string` | — | + +**Returns:** `void` + + +Orchestrates the end-to-end theme switch when the user selects a theme. It loads the chosen theme via ThemeManager.GetTheme, applies it with ThemeManager.ApplyTheme, persists the selection by saving the updated config through ConfigManager.Save, and refreshes the UI to reflect the change. + +## Remarks +Centralizes the end-to-end theme-switch workflow for the app: the same sequence is used whenever a theme changes, ensuring runtime state, persisted configuration, and the visible UI stay in sync. It coordinates ThemeManager, ConfigManager, and the main window (via InvokeUI) to apply color schemes and trigger a UI redraw in a thread-safe manner. Keeping this logic in one private method reduces duplication and makes future theme-related behavior easier to evolve. + +## Notes +- No exception handling is shown in this snippet; exceptions from GetTheme, ApplyTheme, or Save may propagate unless handled by the caller. +- Assumes _config and _mainWindow are initialized before invocation; otherwise a null reference may occur. + +--- + +### HandleViewProfile +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleViewProfile(string? username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string?` | — | + +**Returns:** `void` + + +HandleViewProfile orchestrates the retrieval and presentation of a user’s profile. It determines whether the requested username represents the current user, fetches the profile asynchronously when authenticated, and routes the UI flow to either editing the own profile or viewing another user’s profile. + +## Remarks +This method centralizes the profile-view UX flow, coordinating session state, authentication status, data access, and the dialog-driven UI. By dispatching work to a background task and marshaling UI updates back to the main thread, it keeps the caller responsive while ensuring consistent dialog behavior for own vs. other profiles. The outcome of ShowOwn drives subsequent actions (EditProfile or SetStatus) via the ProfileAction return value, keeping subsequent logic cohesive within this symbol. + +## Notes +- The profile fetch only happens if authentication is present; target may be the current user or another user, and a non-empty target is required for the API call. +- All exceptions during data retrieval are caught and surfaced via ShowError on the UI thread; the flow gracefully aborts the view if loading fails. +- UI updates are performed on the UI thread using InvokeUI to avoid cross-thread issues. + +--- + +### InvokeUI +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void InvokeUI(Action action) => _app.Invoke(action) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `action` | `Action` | — | + +**Returns:** `void` + + +InvokeUI is a private helper that forwards an Action to the application's UI thread by calling _app.Invoke(action). It centralizes UI-thread marshaling within AppOrchestrator so UI updates scheduled from background or orchestrator code go through a single path, ensuring consistent threading semantics. + +## Remarks + +Centers the UI-thread marshaling logic in a single place, reducing boilerplate and the risk of inconsistent marshalling across callers. Because the method is private, its usage is limited to internal orchestration and can be changed without impacting public APIs. The actual dispatch timing depends on the implementation of _app.Invoke; if non-blocking behavior is required, prefer a non-blocking path (such as a BeginInvoke variant) when available. + +## Notes + +- The underlying _app.Invoke dictates whether the call blocks; this method does not introduce a new asynchrony model by itself. +- Avoid long-running work inside the Action passed to InvokeUI to prevent UI thread stalling; offload heavy work to background threads. + +--- + +### JoinChannelWithPasswordPromptAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task?> JoinChannelWithPasswordPromptAsync(string channelName, string? password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `password` | `string?` | — | + +**Returns:** `Task?>` + + +Joins a channel, automatically handling password prompts when the server requires authentication. If the channel is end-to-end encrypted, the user’s passphrase never leaves the client; a PBKDF2-derived authentication key is used to unwrap the room key locally, and the method returns the channel history. If the user cancels the password prompt, it returns null. + +## Remarks +This method centralizes the join-with-password flow, including encryption metadata handling, local key management, and UI coordination, so callers do not need to re-implement retry logic. It coordinates with the connection's room-key store to cache and unwrap encryption envelopes; when a fresh envelope is obtained, it unwraps it locally (using the derived key, if available) and fetches history so decryption uses the latest key. The password prompt is dispatched to the UI via InvokeUI and the result is awaited, ensuring a responsive user experience even on the UI thread. + +## Notes +- Cancellation returns null; callers should treat this as a failed join. +- Wrong passwords trigger a re-prompt loop via ChannelPasswordRequiredException handling. +- If crypto metadata cannot be retrieved, the join proceeds with best-effort encryption state and logs the incident for diagnostics. + +--- + +### NeedsUnlockPrompt +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private bool NeedsUnlockPrompt(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `bool` + + +Determines whether the orchestrator should prompt the user to unlock the room key for a given end-to-end encrypted channel. It returns true only when the channel is encrypted, has no cached key, and the user has not declined the unlock prompt during this session. If the channel isn't encrypted or a key is already cached, no prompt is needed. + +## Remarks + +By centralizing this decision, the code avoids spuriously prompting for unlocks. It leverages the RoomKeys service to inspect encryption status and key caching, and it uses a per-session declined-set to remember user choices, preventing repeated prompts for the same channel within a session. This method acts as a guard that the UI can consult before triggering any unlock UI. + +## Notes + +- The check to read _declinedUnlocks is performed under a lock to ensure thread-safe access to the collection. + +--- + +### NormalizeAsciiSize +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private static string? NormalizeAsciiSize(string? size) => size?.Trim().ToLowerInvariant() switch +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `size` | `string?` | — | + +**Returns:** `string?` + + +Normalizes common ASCII size descriptors into a canonical one-letter code used internally. It trims whitespace, lowercases the input, and maps 's'/'small' to 's', 'm'/'medium' to 'm', and 'l'/'large' to 'l'. Anything else (including null or unknown values) yields null, leaving it to the caller to decide how to proceed. + +## Remarks +Centralizes normalization logic for size inputs, ensuring consistent downstream handling wherever a compact size code is required. Since it returns null for unknown inputs, callers must guard against nulls or provide a fallback. The method is pure (no side effects) and deterministic given its input. + +## Notes +- Returns null for any value that isn't a recognized descriptor, including null or whitespace. +- Whitespace is trimmed and case-insensitive matching is applied, so variations like ' Small ' or 'S' are treated the same. + +--- + +### RunAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void RunAsync(Func work, string errorPrefix, string? logContext = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `work` | `Func` | — | +| `errorPrefix` | `string` | — | +| `logContext` | `string?` | `null` | + +**Returns:** `void` + + +Consolidates the execution of an asynchronous operation within the application context by routing it through AsyncRunner.Run. It passes the current application context, the work to perform, and the UI-facing error handler, along with an error prefix and optional log context. Use RunAsync to ensure uniform error reporting and logging for asynchronous tasks without duplicating the wiring at every call site. + +## Remarks +RunAsync is a tiny abstraction that centralizes cross-cutting concerns around asynchronous work: error handling, user feedback through the main window, and optional diagnostic logging. It decouples callers from the AsyncRunner wiring, so changes to error handling or the logging strategy can be made in one place without touching every invocation. + +## Notes +- Private accessibility means it can only be used within the containing class; callers should use higher-level methods that eventually invoke this helper. +- logContext is optional; omit it if there is no additional logging context, but providing a descriptive value improves traceability in logs and diagnostics. + +--- + +### SendStagedMessage +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void SendStagedMessage(string channel, string content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channel` | `string` | — | +| `content` | `string` | — | + +**Returns:** `void` + + +Sends one message with the given caption plus all staged files as attachments, then clears the staging tray. In encrypted channels each file is room-encrypted (blob + ASCII preview) client-side before upload; the caption is room-encrypted too. + +## Remarks +This method serves as the orchestration point for sending staged content. It encapsulates the encryption decision (via RoomKeys and RoomCrypto), attachment construction (via OutgoingAttachment), and the lifecycle management of the staging tray and temporary pasted files. By coordinating several collaborators, it provides a single, reliable path to publish a caption and its attachments while preserving staging integrity and user experience even in edge cases (e.g., locked rooms or upload failures). + +## Notes +- If the channel is locked, the send is blocked and the files remain staged for after the unlock. The operation exits early in this case. +- The content and attachments are encrypted only if a room key is available; otherwise they are sent in plaintext. +- Temporary pasted files are cleaned up in a finally block, and the staging tray is refreshed regardless of success or failure to prevent orphaned UI artifacts. + + +--- + +### UnlockTrackedChannelAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task UnlockTrackedChannelAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +UnlockTrackedChannelAsync unlocks an end-to-end encrypted channel that is already joined as part of the hub. It re-joins the channel to obtain the WrappedRoomKey envelope, unwraps the key, and, if a key exists in the local store, loads decrypted history into the UI before signaling that the channel is unlocked. The method returns true on a successful unlock and false if the envelope is missing, the key cannot be unwrapped, or an error occurs during the flow. + +## Remarks +This method centralizes the unlock sequence for channels the client is tracking, hiding the details of rejoining, envelope handling, and UI synchronization behind a single, reusable path. It relies on the connection's RoomKeys store to verify that a key has been unwrapped and on the UI dispatcher (InvokeUI) to surface decrypted history when available, ensuring the unlock outcome is reflected in the user interface in a thread-safe manner. + +## Notes +- The function returns false if the channel does not present a WrappedRoomKey (i.e., not an E2E channel) or if the key cannot be established, providing a clear early-out behavior for non-E2E or cancelled unlocks. +- All exceptions are caught and logged with a warning, preventing an unhandled exception from propagating to callers. +- History is loaded into the UI only when a non-null history payload is produced; otherwise, unlocking still succeeds but there is nothing to display. + +--- + +### WireCommandHandlerEvents +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void WireCommandHandlerEvents() +``` + +**Returns:** `void` + + +WireCommandHandlerEvents subscribes the AppOrchestrator to a broad suite of events exposed by the command handler. This centralized wiring ensures that whenever the command handler raises events such as OnSetStatus, OnJoinChannel, or OnExportData, the corresponding local handlers (HandleCmdSetStatus, HandleCmdJoinChannel, HandleCmdExportData, etc.) are invoked. Use this method during initialization to establish the one-to-one event-to-handler mappings instead of scattering subscriptions throughout startup code. + +## Remarks + +This method encapsulates the event-binding choreography between the command layer and the orchestrator. It provides a single, discoverable place where command-related concerns are wired, which helps keep the AppOrchestrator focused on reacting to high-level user commands rather than wiring subsystems. Because the wiring is performed in one place, tests can swap a mock _commandHandler or verify that specific events are connected to their expected handlers. If the set of command events changes, updating this method is the one authoritative location. + +## Notes + +- If _commandHandler is not initialized before calling this method, a NullReferenceException will occur when subscribing to events. Ensure proper initialization order during construction/startup. +- Renaming or removing events requires updating this wiring method to maintain coverage. + +--- + +### WireConnectionManagerEvents +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void WireConnectionManagerEvents() +``` + +**Returns:** `void` + + +## Source Code +Wires up the ConnectionManager's event handlers to drive the client UI for messages, joins/leaves, and presence updates. It subscribes to MessageReceived to display incoming messages and to notify the user when they are mentioned; it handles UserJoined and UserLeft to keep the per-channel online user list in sync and to refresh the UI when the current channel is active; and it reacts to UserStatusChanged to propagate presence updates across all channels and to update the cached channel user lists. The updates are marshaled onto the UI thread via InvokeUI, and thread-safety around the shared _channelUsers collection is maintained with a lock to avoid race conditions when users join, leave, or change status. + +## Remarks +This method centralizes all event wiring for the connection manager, isolating networking concerns from UI/presentation logic. It coordinates message display, system messages for joins/leaves, and presence updates in a single place, which simplifies reasoning about real-time behavior and makes testing easier. The design favors immediate UI feedback for the active channel while ensuring the in-memory presence cache stays consistent across channels. + +## Notes +- The code uses a lock (_channelUsersLock) to guard updates to the _channelUsers dictionary; avoid performing long-running work inside the locked region to prevent UI thread blocking. +- Notification sounds depend on a non-empty session username and on the message content mentioning that username; if either is missing, the sound is not played. +- Presence updates are propagated to all channels for status visibility, and the code path optimizes updates for the current channel by taking a snapshot when applicable. + +## Dependencies +- UserPresenceDto +- Content +- StringComparison +- Username +- Status +- UserStatus + +## Dependency APIs (verified signatures) +- record [`UserPresenceDto`](../EchoHub.Core/DTOs/ProfileDtos.cs.md) (`src/EchoHub.Core/DTOs/ProfileDtos.cs`) +- property `Content` (`src/EchoHub.Core/Models/Message.cs`) +- property `Username` (`src/EchoHub.Client/Config/ClientConfig.cs`) +- property `Status` (`src/EchoHub.Client/Services/UserSession.cs`) +- enum [`UserStatus`](../EchoHub.Core/Models/UserStatus.cs.md) (`src/EchoHub.Core/Models/UserStatus.cs`) + +## Symbol To Document +- Name: WireConnectionManagerEvents +- Kind: method +- File: src/EchoHub.Client/AppOrchestrator.cs +- Language: csharp +- ID: 8c768c24-e19f-4c25-b611-7ab4a805aa68 + +--- + +### WireMainWindowEvents +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void WireMainWindowEvents() +``` + +**Returns:** `void` + + +Wires the MainWindow's UI events to the orchestrator's handlers by subscribing to a broad set of On...Requested events exposed by _mainWindow. This centralized bootstrap method maps user interactions—such as connecting, disconnecting, logging out, submitting messages, staging files, pasting images, selecting channels, requesting profiles or status, changing themes, managing servers and channels, audio playback, file download/save, image operations, deleting messages, checking for updates, rolling back, viewing user profiles, joining channels from messages, searching, loading more results, and replying to messages—to their corresponding handler methods. Call this during initialization to ensure UI actions are routed into the application's business logic. + +## Remarks +Centralizes event wiring and decouples the UI from concrete business logic by acting as the single source of truth for how UI actions map to handlers. It makes the orchestrator's responsibilities explicit and simplifies testing and future changes, since all UI-to-logic subscriptions are declared in one place. + +## Notes +- Invoking WireMainWindowEvents more than once will attach duplicate handlers, causing each event to invoke handlers multiple times; ensure this is called once or guard against re-subscription. +- If _mainWindow is not initialized before calling this method, a NullReferenceException can be thrown during subscription; ensure proper initialization order. + + +--- + +## HandleCmdOpenProfile +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private Task HandleCmdOpenProfile(string? username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string?` | — | + +**Returns:** `Task` + + +This private command handler serves as the command-path bridge to open a user's profile: it dispatches a UI action to display the profile for the provided username and returns a completed Task. It doesn't navigate directly; InvokeUI marshals the call to the UI thread and delegates to HandleViewProfile for the actual rendering. The username parameter is nullable and is passed through to the underlying handler. + +## Remarks +This separation of concerns keeps command execution lightweight while centralizing UI-thread marshaling. By delegating to HandleViewProfile, the actual profile rendering logic remains centralized, promoting consistent navigation behavior across commands that open profiles. + +## Notes +- Returns immediately with Task.CompletedTask; the UI action runs asynchronously on the UI thread. +- The nullable username means callers should ensure compatibility with HandleViewProfile's expectations, or provide a fallback when null. + +--- + +## HandleSearchRequested +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void HandleSearchRequested() +``` + +**Returns:** `void` + + +Handles the search-driven user flow by presenting a dialog of channel names and dispatching the selected result to navigation or action handlers. If a channel is chosen, it switches to that channel and triggers additional channel-selection logic; if an action is chosen, it delegates to the corresponding handler (connect, disconnect, logout, profile, status, create-channel, delete-channel, saved-servers, toggle-users, updates, or quit). When the dialog is canceled, the method exits without side effects. + +## Remarks + +By acting as a centralized dispatcher, this method separates the UI interaction (SearchDialog.Show) from the concrete consequences of each choice. It delegates work to the AppOrchestrator's specialized handlers, ensuring consistent behavior for search-driven commands and simplifying future extension of supported actions. If new search result types or actions are introduced, this entry point will need parallel updates to the switch branches and handlers to maintain correctness. + +## Notes + +- The method only handles Channel and Action result types; additional types will be ignored unless handled here. +- Action keys are plain strings; adding new actions requires updating both the inner switch and the corresponding handler methods. +- Null results are treated as cancellation and result in an early return. + +--- + +## PromptPassword +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +} + + private string? PromptPassword(string prompt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `prompt` | `string` | — | + +**Returns:** `} + + private string?` + + +Prompts the user for a password via a modal dialog and returns the entered value, or null if the user cancels or submits an empty value. Use this helper when you need a blocking, masked password input in a Terminal.Gui-based UI, rather than duplicating dialog scaffolding in multiple places. + +## Remarks +This method encapsulates a small, reusable UI flow using Terminal.Gui components: a dialog with a label that shows the provided prompt, a masked text field (Secret = true), and Confirm/Cancel buttons. It returns the raw password string entered by the user, or null when the user cancels or omits input. The prompt text is injected into the label, allowing reuse with different messages without changing layout. The interaction relies on _app.Run(dialog) to present the modal and _app.RequestStop() to close it once the user makes a choice. + +## Notes +- The password value is kept in memory as a string until the method returns; avoid logging or persisting it in plaintext. +- Whitespace-only input is not treated as empty by this implementation; if your validation requires trimming, perform it after receiving the result. +- Because this is a private helper, callers should provide an appropriate prompt message to convey the expected credential. + + +--- + +## RefreshStagingTray +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private void RefreshStagingTray() +``` + +**Returns:** `void` + + +RefreshStagingTray updates the UI to reflect the current set of staged attachments by extracting their file names and passing them to the main window alongside a size label derived from the configuration. It is a UI helper invoked after modifications to the staging area to keep the display in sync with the underlying data. + +## Remarks +Serves as a UI adapter between the staging model and the presenter, encapsulating how the staged attachments are presented to the user. By using Path.GetFileName, it shows only the file names, avoiding full paths in the interface, and delegates formatting of the size indicator to AsciiSizeLabel(_config.DefaultAsciiSize). This separation simplifies updating presentation details without altering the staging logic. + +## Notes +- Null-reference risk if _mainWindow or _config is not initialized before this method runs. + +--- + +## UnlockRoomKeyAsync +> **File:** `src/EchoHub.Client/AppOrchestrator.cs` +> **Kind:** method + +```csharp +private async Task?> UnlockRoomKeyAsync(string channelName, JoinOutcome outcome) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `outcome` | [`JoinOutcome`](Services/EchoHubConnection.cs.md) | — | + +**Returns:** `Task?>` + + +UnlockRoomKeyAsync drives the interactive unlock flow for an encrypted channel that lacks a cached room key (for example, on a new device). It prompts the user for a passphrase until the room key can be unwrapped and stored, at which point it loads and returns the channel history; if the user cancels, it records the decline and returns the existing history without unlocking. + +## Remarks + +This helper encapsulates the user interaction required to unlock messages for a specific channel, separating the UI-driven password prompt and key-derivation loop from the rest of the connection logic. It uses a per-channel decline cache to avoid nagging after a user declines to unlock, and it clears that cache on a successful unwrap to resume normal history loading. + +## Notes + +- Early exit: if outcome.EncryptionSalt or outcome.WrappedRoomKey are null, the method returns outcome.History immediately. +- Asynchronous prompt: the passphrase prompt is dispatched to the UI and awaited without blocking the caller; the prompt is wired via a TaskCompletionSource and ChannelPasswordDialog.Show. +- Unlock success vs cancel: on success, the derived key is stored and the method returns the channel history; on cancel, the channel is added to _declinedUnlocks and history is returned unchanged. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Commands/CommandHandler.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Commands/CommandHandler.cs.md new file mode 100644 index 0000000..15e7561 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Commands/CommandHandler.cs.md @@ -0,0 +1,1233 @@ +# CommandHandler.cs + +> **Source:** `src/EchoHub.Client/Commands/CommandHandler.cs` + +## Contents + +- [CommandHandler](#commandhandler) + - [HandleAsciiSize](#handleasciisize) + - [HandleAsync](#handleasync) + - [HandleAvatar](#handleavatar) + - [HandleBan](#handleban) + - [HandleBanner](#handlebanner) + - [HandleClear](#handleclear) + - [HandleColor](#handlecolor) + - [HandleDeleteAccount](#handledeleteaccount) + - [HandleExport](#handleexport) + - [HandleHelp](#handlehelp) + - [HandleInvite](#handleinvite) + - [HandleKick](#handlekick) + - [HandleLeave](#handleleave) + - [HandleMe](#handleme) + - [HandleMeta](#handlemeta) + - [HandleMute](#handlemute) + - [HandleNick](#handlenick) + - [HandlePasswd](#handlepasswd) + - [HandleProfile](#handleprofile) + - [HandleQuit](#handlequit) + - [HandleRole](#handlerole) + - [HandleSend](#handlesend) + - [HandleServers](#handleservers) + - [HandleStatus](#handlestatus) + - [HandleTestSound](#handletestsound) + - [HandleTheme](#handletheme) + - [HandleTopic](#handletopic) + - [HandleUnban](#handleunban) + - [HandleUnmute](#handleunmute) + - [HandleUsers](#handleusers) + - [IsCommand](#iscommand) + - [IsValidHex](#isvalidhex) + - [StripQuotes](#stripquotes) + - [StatusUsage](#statususage) +- [CommandResult](#commandresult) +- [HandleDownloadPath](#handledownloadpath) +- [HandleJoin](#handlejoin) +- [HandleNuke](#handlenuke) +- [ParsePathAndSizeFlag](#parsepathandsizeflag) + +--- + +## CommandHandler +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** class + +```csharp +public class CommandHandler +``` + + +Parses user-entered slash commands and turns them into asynchronous events the rest of the client can handle. Use this when you want a single place to interpret textual commands (for example from a chat input box) and decouple parsing from the actual side effects; call IsCommand to quickly test whether an input should be sent to the handler. + +## Remarks +This class is an input-to-event bridge: it does not itself implement the side effects of commands but exposes one event per supported command (OnSetStatus, OnSendAction, OnCreateInvite, OnExportData, etc.). Handlers subscribe to these events to implement the application behavior. The source-level comments capture important parsing decisions made here — for example, status semantics (null status means keep the current status; null message means keep current message; empty message means clear it) and parsing details such as respecting quoted paths and an optional size flag when sending files. Those parsing responsibilities and the use of events keep command parsing isolated from platform-specific orchestration and UI code. + +## Example +```csharp +// subscribe to a couple of command events and pass a slash-command string to the handler +var commands = new CommandHandler(); +commands.OnSetStatus += async (status, message) => +{ + // apply status change (status may be null to mean "keep current") + await Task.CompletedTask; +}; +commands.OnSendAction += async action => +{ + // present an emote/action in the UI + await Task.CompletedTask; +}; + +if (commands.IsCommand("/me waves")) +{ + var result = await commands.HandleAsync("/me waves"); + // inspect result or propagate it to the UI +} +``` + +## Notes +- The IsCommand check is a simple StartsWith('/'); a bare "/" will be treated as a command by that predicate. +- Events are plain C# events and may be null if nobody has subscribed; callers should expect that raising a command could be a no-op unless subscribers are attached. +- Status handling has specific semantics encoded in comments: the orchestrator resolves null/empty values against session state (null = keep, empty string = clear). + +--- + +### HandleAsciiSize +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleAsciiSize(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleAsciiSize is a private asynchronous helper that processes the ASCII size command. If a consumer is attached via OnSetAsciiSize, it is invoked with the input string trimmed by the caller. A lack of argument follows the convention of opening the size picker, while a non-empty argument such as s, m, l, small, medium, or large is forwarded to the delegate to apply the chosen size. The method always returns a successful CommandResult to indicate the command was handled. + +## Remarks +By funneling ASCII-size logic through OnSetAsciiSize, this symbol decouples the command parsing from the actual size-management behavior (UI, persistence, or runtime configuration). The method remains flexible: if no delegate is supplied, the command is effectively a no-op but still reports success, allowing the caller to treat the input as handled. This pattern simplifies testing and enables swapping the size-setting behavior without changing the command-handler code. + +## Notes +- Potential NullReferenceException if OnSetAsciiSize is non-null and 'args' is null because args.Trim() is called without a null-check. +- Returning CommandResult(true) means callers should not rely on this method to signal whether a size was actually changed. + +--- + +### HandleAsync +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +public async Task HandleAsync(string input) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `input` | `string` | — | + +**Returns:** `Task` + + +HandleAsync is the central dispatcher for user-entered commands in the EchoHub client; it validates the input, parses the command and its arguments, and asynchronously delegates to the appropriate command-specific handler, returning a CommandResult that reflects success or failure. If the input doesn't look like a command it returns a failure immediately, and unknown commands produce a user-friendly error. + +## Remarks +This abstraction separates parsing from individual command implementations, normalizing input (lowercasing the command) and trimming whitespace so each handler can focus on its own logic. It uses the leading slash convention (input[1..]) and a switch expression to map to handlers, making it straightforward to add new commands by extending the switch. + +## Notes +- The command is case-insensitive due to ToLowerInvariant. +- Unknown commands yield a friendly error that points to /help; non-command inputs yield a simple failure. +- Command behavior is delegated to a family of HandleX methods, keeping parsing concerns isolated from command logic. + +--- + +### HandleAvatar +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleAvatar(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +This private async method handles the /avatar command: it validates the provided argument, trims surrounding quotes, and, if a handler is attached via OnSetAvatar, invokes it with the cleaned target. It returns a CommandResult indicating either a usage error when the argument is missing or a success message once the update completes. + +## Remarks +This method isolates command parsing from the avatar update mechanism. By exposing OnSetAvatar as a delegate, the app can supply concrete update behavior (e.g., uploading to a server or updating local state) without coupling the command logic to the implementation. The user-facing feedback is produced after the asynchronous update completes, ensuring the message reflects the outcome of the operation. + +## Notes +- If OnSetAvatar is null, the method completes without performing any update, but still returns a success message ('Uploading avatar...'). +- Exceptions thrown by OnSetAvatar are not caught within this method; callers should handle faulted tasks if the delegate fails. + +--- + +### HandleBan +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleBan(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the /ban command by validating input, parsing a required username and an optional reason, and invoking the OnBanUser callback when provided. If no arguments are given, it returns a usage message; otherwise it awaits the ban handler and responds with a banning message for the target user. + +## Remarks +HandleBan acts as a small bridge between the command-processing surface and the domain action of banning a user. It encapsulates input parsing and the optional ban callback behind a single method, enabling testability and decoupling from the actual ban implementation. Its behavior is explicitly contingent on the presence of OnBanUser: with it set, the ban logic runs; without it, the method still returns a result, but no action is performed. + +## Notes +- The ban action only occurs if OnBanUser is assigned; otherwise, the command completes with a 'Banning ...' message but no side-effect. +- The reason parameter is optional; if omitted, reason is passed as null to OnBanUser, which should handle it accordingly. +- Input parsing uses a single split with a maximum of two parts and trims whitespace, so arguments like "user" and "user reason" are handled predictably. + + +--- + +### HandleBanner +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleBanner(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Processes the /banner command by validating the provided text, trimming it, and optionally dispatching it to a banner sender. If the input is null, empty, or whitespace, it returns an error CommandResult containing a usage message. If a banner handler is registered via OnSendBanner, it awaits the handler with the trimmed text; finally it returns a successful CommandResult. + +## Remarks +Centralizes banner command handling and isolates input validation from the actual rendering logic. By exposing OnSendBanner as a delegate, the system can plug in different banner delivery strategies without changing the command code. Trimming before dispatch ensures consistent formatting and prevents trailing or leading whitespace from affecting the banner. + +## Example +```csharp +// Example: valid input +var result = await HandleBanner("Hello!"); +// If a subscriber is attached to OnSendBanner, it's invoked with "Hello!" and a success result is returned. + +// Example: invalid input (whitespace-only) +var error = await HandleBanner(" "); +``` + +## Notes +- If OnSendBanner is null, the method completes successfully without attempting to send a banner. +- Leading/trailing whitespace is trimmed before dispatch; inner whitespace is preserved. + +--- + +### HandleClear +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleClear() +``` + +**Returns:** `Task` + + +Describes the internal helper method HandleClear, which clears any attachments staged for a command by invoking the OnClearAttachments delegate if it's configured, awaits its completion, and then returns a CommandResult signaling success with the message "Cleared staged attachments." Because it is private, it is intended to be used internally by the command handling flow rather than as a public API. + +## Remarks +The method encapsulates the cleanup step of the command execution, ensuring a single point of behavior for clearing attachments and reporting results. It reduces duplication by handling the conditional delegate invocation and the standardized success result in one place. + +## Notes +- If OnClearAttachments is null, the method performs a no-op for the cleanup but still reports success. +- Exceptions raised by OnClearAttachments propagate to the caller; the method does not catch them. + +--- + +### HandleColor +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleColor(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the /color command by validating and normalizing the input hex color and, when valid, applying it through an optional callback. It accepts a string of arguments, ensures a color was provided, prepends a leading '#' if missing, enforces the #RRGGBB format, and calls OnSetColor(color) if a handler is attached before returning a CommandResult with a user-friendly message. + +## Remarks +By decoupling the color application from the parsing logic via OnSetColor, this method remains focused and testable. It normalizes input to a canonical #RRGGBB form and provides clear feedback for missing, malformed, or valid colors, integrating smoothly with the command-handling flow and the CommandResult feedback. + +## Notes +- If OnSetColor throws, the exception will propagate to the caller since there is no internal try/catch. +- If OnSetColor is null, no color is actually applied, though a confirmation message is still returned. + +--- + +### HandleDeleteAccount +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleDeleteAccount() +``` + +**Returns:** `Task` + + +HandleDeleteAccount is a private asynchronous helper that orchestrates the delete-account action by optionally invoking a deletion callback and then returning a CommandResult indicating success. If an OnDeleteAccount delegate is supplied, it is awaited; if not, the method completes immediately and signals success. + +## Remarks +By relying on the OnDeleteAccount hook, this method decouples the command handling from the actual deletion logic, enabling different delete implementations to be plugged in without changing the caller. It participates in a command-pattern flow where a successful outcome is reported via CommandResult once the delegate (if any) completes. Note that exceptions thrown by the deletion delegate will propagate to the caller; this method does not translate errors into a failure result itself. + +## Notes +- Be mindful that if OnDeleteAccount is null, the method returns a successful CommandResult without performing any deletion. +- There is no internal error-handling; exceptions thrown by OnDeleteAccount bubble up to the caller. + +--- + +### HandleExport +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleExport() +``` + +**Returns:** `Task` + + +HandleExport is a private asynchronous helper in CommandHandler that conditionally triggers an export operation and then signals success to the caller. When OnExportData is assigned, the method awaits OnExportData, allowing export logic to be injected without forcing callers to perform the export themselves; if OnExportData is null, the method completes immediately. The resulting CommandResult(true) communicates that the command finished successfully regardless of whether an export was performed, effectively making the export step optional and pluggable within the command handling workflow. + +## Remarks +Why this abstraction exists: It decouples the export behavior from the command flow, enabling tests and consumers to provide their own export logic via a delegate. It centralizes the export invocation behind a simple private method, which reduces repetition and makes the command-handling path easier to reason about. The null check ensures no-op behavior when no export is configured, while still preserving asynchronous semantics. + +## Notes +- If OnExportData throws, the exception propagates to the caller; HandleExport itself does not catch exceptions. +- Because the method is private, it can only be invoked within CommandHandler, ensuring export behavior is controlled and testable. + +--- + +### HandleHelp +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleHelp() +``` + +**Returns:** `Task` + + +Handles internal help for the client command interface. When invoked, it optionally triggers the OnHelp hook if assigned, then returns a successful CommandResult containing a large multi-line help text that lists available commands, their usage, and usage tips. This method is used by the command-handling flow to present a consistent help experience to users. + +## Remarks +By centralizing the help text in this method, the UI can display a single source of truth for command guidance. The OnHelp hook provides a minimal extension point for runtime customization or side effects without duplicating the static content. Because the method is private, it's intended to be invoked by the command-handling flow rather than consumed as part of the public API. + +## Notes +- The returned CommandResult is constructed with a success flag and the help message; the signature implies CommandResult(bool, string). +- The help content is embedded as a raw string literal; editing the literal updates every user-visible line of help. +- If OnHelp throws, the exception will propagate as part of the async flow since there is no internal try/catch. +- The content is not localized here; there is no localization mechanism evident in this snippet. + +--- + +### HandleInvite +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleInvite(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Parses and handles invite-related commands issued to the command handler. It recognizes three forms: /invite list to enumerate invites, /invite revoke to invalidate a specific invite, and /invite [maxUses] [expiresHours] to create a new invite with optional usage limits and expiration. It validates inputs, returns a CommandResult that signals success or error (with a usage message when inputs are invalid), and delegates the actual work to OnListInvites, OnRevokeInvite, or OnCreateInvite when those callbacks are provided. + +## Remarks +By centralizing the invite command parsing, this private method insulates the higher-level command flow from the details of argument interpretation and validation. It coordinates with the domain actions via the OnListInvites, OnRevokeInvite, and OnCreateInvite callbacks, enabling a clean separation between parsing logic and invite-management behavior. The returned CommandResult ensures callers observe a uniform success/error contract. + +## Notes +- It relies on StringSplitOptions and StringComparison for command parsing and case-insensitive subcommand matching, and it returns helpful usage messages when inputs are malformed. + +--- + +### HandleKick +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleKick(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the /kick command by validating input, extracting the target username and an optional reason, and delegating the actual kick action to a callback if one is registered. If no arguments are supplied, it immediately returns a CommandResult indicating the proper usage. When arguments exist, it splits them into username and an optional reason (up to two parts) and, if OnKickUser is not null, awaits the callback with the username and reason. It then returns a success CommandResult with the message 'Kicking {username}...'. + +## Remarks +Integrates input validation and a pluggable kick action via OnKickUser, acting as a thin mediator between the command parser and the actual moderation logic. It centralizes consistent user feedback and prevents empty or malformed kick commands from proceeding. + +## Notes +- If OnKickUser throws, this method does not catch the exception; the exception propagates to the caller. +- When args are valid but OnKickUser is null, the method still returns a success CommandResult reflecting the intent ("Kicking {username}..."). No action is performed in that case within this method. +- The argument parsing uses StringSplitOptions.TrimEntries and splits at most once, honoring the first space as the separator between username and optional reason. + +--- + +### HandleLeave +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleLeave() +``` + +**Returns:** `Task` + + +HandleLeave is an asynchronous helper used by the command-handling flow to perform a channel leave action when provided. If a consumer assigns OnLeaveChannel, it will be awaited before the method completes; if not, the method completes immediately. In either case, it returns a CommandResult representing success. + +## Remarks + +By delegating the actual leave operation to the OnLeaveChannel delegate, this symbol decouples the command-handling logic from the concrete leave behavior, enabling easier testing and composition. It acts as a thin wrapper around the optional leave action, ensuring a consistent CommandResult is produced for the rest of the pipeline. + +## Notes + +- If OnLeaveChannel is provided and it throws an exception, that exception propagates to the caller since there is no local error handling. +- The return value is always new CommandResult(true), so success is signaled regardless of whether a leave action existed or completed. +- This method is private; external components should not rely on it directly. + +--- + +### HandleMe +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleMe(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleMe handles the /me command by validating the provided action and, when valid, dispatching it to an OnSendAction callback. If the argument is missing or whitespace, it returns an error-style CommandResult with a usage message; if OnSendAction is registered, it awaits the callback with the trimmed text and then returns a successful CommandResult. + +## Remarks +By delegating the actual broadcast of the action to OnSendAction, this method remains focused on input validation and orchestration. The private scope indicates it is part of the internal command-processing pipeline, invoked by the higher-level handler when parsing a /me invocation. + +## Notes +- Exceptions raised by OnSendAction are not caught within this method; callers should rely on upstream exception handling. + +--- + +### HandleMeta +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleMeta() +``` + +**Returns:** `Task` + + +HandleMeta is a tiny asynchronous helper in the command handling workflow. If an OnRoomInfo callback has been registered, it awaits that callback to allow any optional room-information logic to run, and then returns a CommandResult indicating success. + +Use it when you want an optional, side-effect-free hook for room-info refresh during meta command handling without forcing callers to implement the null-check and await themselves; if OnRoomInfo is not provided, the method completes immediately with a successful result. + +## Remarks +HandleMeta acts as an abstraction that coordinates optional room-state enrichment with the command pipeline. By encapsulating the OnRoomInfo invocation, it decouples room-information concerns from the rest of the command logic, making it easy to inject or mock in tests. It guarantees a consistent success signal via CommandResult, even if OnRoomInfo performs no work. + +## Notes +- If OnRoomInfo throws, the exception will bubble up to the caller; there is no internal error handling here. +- The returned CommandResult(true) does not reflect the outcome of OnRoomInfo; use OnRoomInfo itself to signal failures if needed. +- Because OnRoomInfo is awaited, any long-running operation inside it will increase the total latency of this method. + +--- + +### HandleMute +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleMute(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Parses and handles the /mute command by extracting a username and an optional duration from the input, then delegates the actual mute action to an optional OnMuteUser handler and returns a CommandResult indicating the operation is in progress. + +## Remarks +This method serves as a thin, command-UI-oriented wrapper around a mute action. It defers the concrete muting logic to OnMuteUser, enabling testability and alternate mute implementations without changing the command parsing. It also demonstrates defensive parsing: it requires a non-empty arg string, splits into at most two parts (username and an optional duration), and only proceeds to invoke the handler if one is provided. The user-facing feedback is consistently formatted as a "Muting {username}..." message to keep the command responsive while the mute operation completes asynchronously. + +## Notes +- If OnMuteUser is null, no mute action is performed beyond returning the Muting message. +- If OnMuteUser throws an exception, HandleMute does not catch it; the exception will propagate to the caller. +- Only the first two space-delimited segments are considered: the first is the username, the second (if present) is parsed as an integer duration in minutes; if parsing fails, duration is treated as null (indefinite mute). + + +--- + +### HandleNick +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleNick(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleNick processes the /nick command by validating the supplied display name and applying it when possible. If the argument is missing or whitespace, it returns a CommandResult indicating the proper usage. If an OnSetNick callback is provided, it awaits that callback with the trimmed nickname, and finally returns a success CommandResult showing the updated display name. + +## Remarks +HandleNick acts as a focused, testable wrapper around nickname changes, separating input validation from persistence. By accepting an optional OnSetNick delegate, it delegates the actual update to the surrounding system while keeping the command-handling logic simple and easy to reason about. + +## Notes +- If OnSetNick is null, the method reports success but does not persist the nickname; ensure a listener is wired if persistence is required. +- If OnSetNick throws, the exception bubbles to the caller since there is no internal error-handling around the delegate. +- The input is trimmed before both passing to OnSetNick and composing the final message, ensuring consistent display without leading or trailing spaces. + +--- + +### HandlePasswd +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandlePasswd(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Parses and handles the /passwd command by validating its arguments and, when possible, delegating the actual password change to an optional callback. It expects two tokens: the old passphrase and the new passphrase, enforces a minimum length for the new passphrase, and returns a CommandResult indicating success or error. + +## Remarks +This method acts as a lightweight command-scaffold: it performs input validation and defers the real password change to OnChangeRoomPassword if provided. By isolating argument parsing from the change logic, it keeps command-handling concerns separate from the actual credential update, enabling test doubles or alternate implementations of the change process. The final outcome is indicated via CommandResult; errors produce usage information or length violations, while a successful path triggers the change callback and returns a non-error result. + +## Notes +- Input is split on a single space; passphrases containing spaces won't be accepted. +- If OnChangeRoomPassword is null, the method completes without invoking a change, yet still returns a success result. +- New passphrase must be at least 3 characters; there is no verification of the old passphrase here. + +--- + +### HandleProfile +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleProfile(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleProfile is a private asynchronous command handler that triggers a profile view by delegating to an optional OnOpenProfile callback. It normalizes the incoming argument into a username: if the provided args are null, empty, or whitespace, it uses null; otherwise it trims surrounding whitespace. If a listener is attached, it awaits the callback with the computed username, allowing the consumer to decide how to present the profile. Finally, it returns a successful CommandResult, indicating the command was processed at the wrapper level. + +## Remarks +By design this method decouples the command-handling surface from the actual navigation logic. It passes null when no explicit username is supplied, enabling the consumer to interpret that as a request for the current user's profile or a default view. The method is asynchronous only because it awaits the OnOpenProfile callback; the surrounding code can rely on the Task-based pattern without assuming internal navigation details. Note that exceptions raised by OnOpenProfile propagate to the caller, since there is no internal error handling here. + +## Notes +- If OnOpenProfile is null, the method completes trivially after returning a success result. +- Exceptions from OnOpenProfile bubble up to the caller; this method does not swallow errors. +- Input normalization ensures that whitespace-only arguments are treated as no username. + +--- + +### HandleQuit +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleQuit() +``` + +**Returns:** `Task` + + +HandleQuit is a private asynchronous method that executes the quit sequence by invoking OnQuit (if provided) and then returning a CommandResult indicating success. It provides a centralized quit path for the command-handling flow, enabling an optional host-defined cleanup step to run before signaling completion to the caller. + +## Remarks + +By centralizing quit semantics in HandleQuit, the class separates the mechanics of terminating a session from the rest of command processing. It wires an optional asynchronous hook (OnQuit) that external code can supply to perform cleanup or notifications during quit, without forcing callers to know about the hook's existence. Note that exceptions raised by OnQuit will propagate to the caller; this method does not swallow errors, preserving fail-fast semantics for quit-related failures. The method always returns a successful CommandResult when OnQuit completes, or immediately if no OnQuit is provided. + +## Notes + +- If OnQuit is null, the method returns a CommandResult that signals success immediately after the null check. +- Exceptions from OnQuit propagate to the caller and are not swallowed here. +- This method is private; external code cannot call it directly and must go through the public command-handling path. + +--- + +### HandleRole +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleRole(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Parses and validates a /role command string, requiring a username and a target role (admin, mod, or member). If valid, it optionally invokes OnAssignRole to apply the change and returns a CommandResult that communicates the outcome or usage errors. + +## Dependencies +- CommandResult +- StringSplitOptions + +## Dependency APIs (verified signatures) + +The REAL, parser-verified API surface of this symbol's collaborators: + +- record `CommandResult` (`src/EchoHub.Client/Commands/CommandHandler.cs`) + +## Remarks +HandleRole centralizes command parsing for role assignment. It isolates input validation (presence, tokenization, allowed roles) from the actual mutation performed by OnAssignRole, enabling easier testing and decoupling of concerns. By normalizing the role to lowercase, it accepts case-insensitive input while enforcing a strict set of roles. The method always returns a CommandResult, conveying either an error message with usage guidance or a confirmation that the role is being set. + +## Notes +- The arguments are split with a maximum of two parts, so the first token is the username and the second is the role; any extra tokens are ignored. +- Role normalization uses ToLowerInvariant to enable case-insensitive input while restricting to the allowed values: 'admin', 'mod', or 'member'. +- OnAssignRole is optional; if provided, it's awaited to perform the actual assignment; if not, the method still returns a confirmation message. + +--- + +### HandleSend +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleSend(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleSend implements the /send command handler. It validates the provided target (a file path or URL), extracts an optional size flag, and triggers the actual sending via the OnSendFile callback when available. It distinguishes between HTTP/HTTPS URLs and local files, returning a user-facing CommandResult that reflects either the ongoing action (Sending or Uploading) or any encountered error (usage, missing target, or missing file). + +## Remarks +HandleSend isolates user interaction from the sending mechanism by coordinating argument parsing and the send callback. It calls OnSendFile(target, size) when provided and then formats a helpful status message that includes the resolved file name (defaulting to 'image' when the URL lacks a file name). This method remains robust against missing files and invalid targets, giving clear guidance to the user while deferring the actual transmission to the registered callback. It also supports reading an optional size flag from the end or start of the argument string while honoring quoted paths. + +## Notes +- If OnSendFile is null, HandleSend still returns a status message (e.g., "Sending:..." or "Uploading:...") without performing a callback. +- For HTTP/HTTPS URLs, the file name is derived from the URL's path; if absent, a sensible default of "image" is used. +- It relies on an external ParsePathAndSizeFlag(args) helper; behavior depends on that implementation, so edge cases around quoting and flag placement should be considered. +- When targeting a local file, the method checks File.Exists and returns a "File not found: ..." error if absent. + +--- + +### HandleServers +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleServers() +``` + +**Returns:** `Task` + + +HandleServers centralizes the action of opening servers by invoking an optional host-provided callback and returning a success result. Developers reach for this helper when they want the command sequence to trigger server-opening behavior that may be supplied externally via OnOpenServers, rather than implementing the logic inline. + +## Remarks + +It decouples the behavior from the command flow by using a nullable delegate, making the logic easier to test and replace in different hosting environments. If OnOpenServers is null, the method still returns a successful CommandResult, providing a safe no-op path. Note that there is no try-catch around the await, so exceptions raised by OnOpenServers will propagate to the caller rather than being swallowed here. + +## Notes + +- Exceptions from OnOpenServers propagate to the caller (no internal suppression). +- The returned CommandResult(true) is independent of the success of OnOpenServers. +- This method is private and intended for internal command flow; external code should not rely on it directly. + +--- + +### HandleStatus +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleStatus(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Parses and handles the /status subcommands by interpreting either a status keyword or a status message, and then invokes an optional OnSetStatus callback to apply the change. It validates input, supports a message form (msg/message) to set or clear a status message, and returns a CommandResult that communicates success or a structured error (with usage guidance) when appropriate. + +## Remarks +This method centralizes the parsing logic for status-related subcommands and delegates the actual state mutation to a downstream callback via OnSetStatus, enabling clean separation between command parsing and state management. The OnSetStatus delegate is optional; if it is not provided, the method still returns a descriptive result but performs no external mutation. A strict policy is enforced: if a valid status keyword is supplied, no additional text is allowed; the special form msg/message may include a trailing message to set, otherwise the message is cleared. + +## Example +```csharp +// Example: set online status +var r1 = await HandleStatus("online"); + +// Example: set a status message +var r2 = await HandleStatus("msg System maintenance at 22:00"); + +// Example: clear the status message +var r3 = await HandleStatus("msg"); + +// Example: unknown status yields an error +var r4 = await HandleStatus("busy"); +``` + +## Notes +- The status argument is treated case-insensitively due to ToLowerInvariant, so "Online" and "online" behave the same. +- If a known status is supplied with additional text (e.g., "online extra"), the method returns an error including StatusUsage. +- Even when OnSetStatus is null, the method returns a meaningful CommandResult message and avoids side effects; hook up OnSetStatus to enact real status changes when available. + + +--- + +### HandleTestSound +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleTestSound() +``` + +**Returns:** `Task` + + +HandleTestSound is a private async helper that, when an OnTestSound callback is provided, awaits that delegate to play a test notification sound, and then returns a CommandResult signaling success with the message 'Playing notification sound...'. + +## Remarks +Serves as a thin abstraction that decouples the act of playing a test sound from the command result flow. By wrapping an optional callback in a single, awaitable operation, it keeps the surrounding command-handling code concise and testable, while allowing the actual sound playback logic to be supplied (or mocked) at runtime. + +## Notes +- If OnTestSound throws, the exception propagates to the caller because HandleTestSound doesn't catch it. +- The returned CommandResult is always constructed after OnTestSound completes (when present), with a hard-coded success value; the result does not reflect any potential failure inside the OnTestSound callback. + +--- + +### HandleTheme +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleTheme(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleTheme processes the /theme command. If the user supplies no name, it returns a usage message guiding the caller to provide a theme name from the User menu's theme list (e.g. Default, Transparent, TransparentLight, Hacker). If a name is provided, it forwards the trimmed name to the OnSetTheme callback (if it is set) and returns a confirmation indicating the theme was switched. + +## Remarks +By delegating to OnSetTheme, this method keeps command parsing separate from the actual theme application. It also ensures a consistent user feedback surface through CommandResult, regardless of how themes are implemented elsewhere in the codebase. + +## Notes +- Validation of the theme name itself is not performed here; it is expected to be validated by OnSetTheme or the surrounding UI layer. +- If OnSetTheme is null, the method still returns a success message, which means the theme change may not be applied. +- Whitespace-only input is rejected with the usage message due to the IsNullOrWhiteSpace check. + +--- + +### HandleTopic +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleTopic(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Processes a topic-setting command by validating that text is provided, optionally forwarding the trimmed topic to a consumer via OnSetTopic, and returning a CommandResult that indicates success or instructs the user on proper usage. If no text is supplied, it immediately returns an error result with a usage hint; otherwise it applies the topic (when a listener is present) and responds with a confirmation message reflecting the new topic. + +## Remarks + +- By accepting an optional OnSetTopic callback, this method decouples the command parsing from the actual topic application. It trims input to standardize the topic value and uses a single, consistent success message. The async nature allows the topic application to perform I/O-bound work without blocking the caller. + +## Notes + +- If OnSetTopic throws, the resulting Task will fault; callers may wish to handle exceptions when the topic application performs I/O or other operations. +- The method is private and intended to be used by the surrounding command-handling workflow; external callers should interact with higher-level command APIs rather than this helper directly. + +--- + +### HandleUnban +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleUnban(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the /unban command by validating the provided username and triggering the unban workflow if a handler is wired up. If the caller passes an empty or whitespace-only string, it returns an error CommandResult with a usage hint. When a username is supplied, it trims whitespace, calls the OnUnbanUser delegate if it exists, and then returns a success result with a live message indicating the unban operation is underway. + +## Remarks + +By delegating the actual unban action to OnUnbanUser, this method remains agnostic of how bans are enforced (in-memory, persisted, or communicated to another service). This separation concerns input validation, user feedback, and orchestration, while leaving the business logic to the registered handler. The approach also makes it straightforward to unit-test the command flow by supplying a mock OnUnbanUser and asserting that it was invoked with the trimmed username. + +## Notes + +- If OnUnbanUser throws, the exception will propagate to the caller since there is no try/catch here. +- The error path uses IsError: true to signal invalid usage; a non-empty username will yield a non-error CommandResult with the final message. + +--- + +### HandleUnmute +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleUnmute(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the /unmute command by validating its argument, optionally triggering a delegated action, and returning a user-facing result. If no username is provided, it returns an error CommandResult with usage instructions. When a username is supplied, it trims whitespace, invokes the OnUnmuteUser callback if present, and finally returns a success CommandResult indicating that the unmute process has started for that user. + +## Remarks +Encapsulates the unmute flow behind a private helper, decoupling the UI command parsing from the actual unmute operation. By deferring to an optional OnUnmuteUser delegate, it enables testability and flexible wiring of the unmute logic. The method also normalizes input by trimming the username before use. + +## Notes +- The input username is trimmed before passing to the callback and before including in the final status message, preventing issues caused by surrounding whitespace. +- If OnUnmuteUser is null, the method returns a success result without performing any side effects, allowing the UI to display a consistent message even when no backend action is wired. +- The method is private; it is intended to be invoked through the command-handling pipeline rather than called directly from external code to preserve encapsulation. + +--- + +### HandleUsers +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleUsers() +``` + +**Returns:** `Task` + + +Handles the 'list users' command by optionally invoking an OnListUsers callback and then returning a successful CommandResult. If a consumer provides OnListUsers, that callback is awaited; otherwise the method completes by returning a CommandResult indicating success. This wrapping method keeps the command dispatch path consistent while delegating the actual listing logic to the injected delegate. + +## Remarks +A thin wrapper in the command handling pipeline. It delegates the actual listing to OnListUsers via a delegate and then yields a consistent CommandResult(true). This separation allows tests to inject different listing behaviors without altering the caller, and keeps the path for listing users uniform. + +## Notes +- OnListUsers exceptions propagate to the caller; this method does not catch errors. +- No cancellation token is observed or supported here. + +--- + +### IsCommand +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +public bool IsCommand(string input) => input.StartsWith('/') +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `input` | `string` | — | + +**Returns:** `bool` + + +IsCommand is a tiny predicate that determines whether an input string should be handled as a command by checking if the first character is '/'. Use it at the entry point of the command-processing path to decide whether to route the input to the command parser rather than treating it as ordinary text, thereby keeping command-detection logic in one place. + +## Remarks +IsCommand encapsulates the slash-prefix convention used to invoke commands, providing a single, testable contract for command detection. This keeps command routing decoupled from unrelated input handling and makes future changes—such as supporting a different prefix or multiple prefixes—easier to implement. It also clarifies intent at call sites by replacing ad-hoc prefix checks with a well-named predicate. + +## Notes +- Null input may cause a NullReferenceException since input.StartsWith is called directly on input. +- Strings with leading whitespace won't be treated as commands unless trimmed; consider input = input.TrimStart() or adjust logic. + +--- + +### IsValidHex +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private static bool IsValidHex(string s) => + s.All(c => char.IsAsciiHexDigit(c)) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `s` | `string` | — | + +**Returns:** `bool` + + +This private helper returns true if every character in the input string is an ASCII hexadecimal digit (0–9, A–F, a–f); otherwise it returns false. It is intended for internal use within the command handler to validate hex-like input before parsing or converting it to binary data. + +## Remarks +IsValidHex centralizes hex-character validation, promoting consistent input checks across the command handling code. By leveraging the built-in IsAsciiHexDigit predicate, it stays robust against locale issues and clearly expresses the intent of the check. As a private static member, it remains an internal utility rather than part of the public API, simplifying maintenance and testing within the containing class. + +## Notes +- Null input will throw a NullReferenceException when evaluated, since the method dereferences the input string. If you need null-tolerant behavior, guard the parameter before calling this helper. +- An empty string is considered valid by this implementation because All over an empty sequence returns true. If empty input should be rejected, add an explicit check before invoking this method. + +--- + +### StripQuotes +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private static string StripQuotes(string s) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `s` | `string` | — | + +**Returns:** `string` + + +Removes surrounding quotes from a string when the value is wrapped in matching single or double quotes; otherwise it returns the input unchanged. Use this helper to normalize command arguments that may be quoted, instead of duplicating substring logic or handling quotes at every parse path. + +## Remarks +Private static helper inside the command handling path, StripQuotes encapsulates a small, focused normalization concern. It prevents scattering the same quote-stripping logic across multiple call sites and makes the intended behavior (remove only matching outer quotes) explicit. The method uses C# range and index syntax (s[1..^1], s[^1]) for a compact implementation. + +## Example +```csharp +string input = "\"hello\""; +string output = StripQuotes(input); // output == "hello" +``` + +## Notes +- It only strips when both ends are the same quote character. +- It does not interpret escape sequences or nested quotes; quotes inside remain. +- Because it is private, external consumers cannot call it; to reuse externally, expose a public wrapper or move to a shared utility. +- Requires C# 8+ for index and range syntax (s[^1], s[1..^1]). + +--- + +### StatusUsage +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** field + +```csharp +private const string StatusUsage = + "Usage: /status or /status msg (empty text clears it)" +``` + + +StatusUsage is a private constant string that holds the canonical usage text for the /status command used by the command handler. It defines two forms of input: either selecting a predefined status (online, away, dnd, invisible) or providing a custom message with /status msg . An empty text clears the current status. Centralizing this string avoids duplicating literals and helps keep the command’s user-facing guidance consistent across the codebase. + +## Remarks +By keeping the usage text in a private field, the implementation encapsulates help and validation concerns within CommandHandler.cs. This makes it easy to adjust the wording or supported syntax in one place. If localization or broader reuse is needed later, this constant should be replaced with a resource or exposed via a helper so external components can reference it consistently. + +## Notes +- If you extend supported presets, update both the hard-coded usage and the parsing logic; otherwise the command may reject valid inputs or mislead users. +- Because it's private, external code/tests can't reference it directly; consider exposing a read-only accessor or moving to a resource to improve testability. + +--- + +## CommandResult +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** record + +```csharp +public record CommandResult(bool Handled, string? Message = null, bool IsError = false) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Handled` | `bool` | — | +| [`Message`](../../EchoHub.Core/Models/Message.cs.md) | `string?` | `null` | +| `IsError` | `bool` | `false` | + + +Represents the outcome of handling a command as a compact, immutable value. It indicates whether the command was processed (Handled), carries an optional diagnostic or user-facing message (Message), and signals whether the outcome is an error (IsError). Use this as the return type from a command handler to convey success or failure without relying on exceptions, and to expose contextual details to the caller. + +## Remarks +CommandResult acts as a lightweight contract between command invokers and handlers. By being a C# 9 record, it benefits from value-based equality and immutability, enabling safe sharing and straightforward comparisons in tests or across layers. The IsError flag clarifies how callers should react, while a non-null Message can provide actionable context in logs or UI. + +## Example +```csharp +// Successful handling with no extra message +var success = new CommandResult(true); + +// Failed handling with diagnostic +var failure = new CommandResult(false, "Unknown command", true); +``` + +## Notes +- Message may be null; always guard before displaying to users. +- Records support with-expressions, so you can derive a near-identical result with a different Message or IsError without reconstructing all fields. + +--- + +## HandleDownloadPath +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleDownloadPath(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +Handles the download path configuration by consuming an optional argument. If the trimmed argument is empty, it signals the OnSetDownloadPath callback to open the native folder picker; if a value is provided, that value is used as the path to set directly. If OnSetDownloadPath is not wired, the call is a no-op and the method still returns a successful CommandResult. + +## Remarks + +Serves as a thin adapter between the command processing layer and the UI/persistence logic that applies the download path. It centralizes the branching logic: either prompt the user for a path via the native picker or apply a provided path, without forcing the caller to know which path was chosen. This keeps command handling simple while delegating the actual path application to a separate, testable component. + +## Notes + +- If OnSetDownloadPath is null, the method completes without changing the path; callers should ensure the callback is assigned before invocation. +- Whitespace-only arguments are treated as empty after trimming, which triggers the native folder picker behavior. +- The method does not perform path validation; downstream logic or the callback is responsible for validating the path. + +--- + +## HandleJoin +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleJoin(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `args` | `string` | — | + +**Returns:** `Task` + + +HandleJoin is a private asynchronous command handler that processes the /join command by validating input, extracting a channel and an optional password, and delegating the actual join operation to a callback if one is registered. It normalizes the channel name by removing a leading '#', and returns a usage error when no arguments are supplied; otherwise it invokes the join hook and returns a success result. + +## Remarks +HandleJoin serves as the bridge between user input and the join logic by decoupling command parsing from the actual join implementation. It relies on the OnJoinChannel callback to perform the real join work, enabling testability and flexibility by swapping in different join strategies. The normalization step (stripping a leading '#') supports common user conventions for channel identifiers. + +## Notes +- The password extraction line in the snippet appears garbled (a redaction artifact). Ensure a properly declared password variable is assigned from parts[1] when present. +- Accessing parts[1] without checking parts.Length could lead to an IndexOutOfRangeException if the user supplies only a channel name. +- If OnJoinChannel is null, the method will return a successful CommandResult even though no join occurred; consider whether a different outcome is desired when no handler is attached. + +## Dependencies +- CommandResult +- StringSplitOptions + +## Dependency APIs +- CommandResult (record) — src/EchoHub.Client/Commands/CommandHandler.cs +- StringSplitOptions (enum) — System/StringSplitOptions (used in the Split call) + +## Symbol To Document +- Name: HandleJoin +- Kind: method +- File: src/EchoHub.Client/Commands/CommandHandler.cs +- Language: csharp +- ID: 7f13a65c-5457-40c2-b652-518b98329639 + +--- + +## HandleNuke +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleNuke() +``` + +**Returns:** `Task` + + +HandleNuke is a concise asynchronous command handler that, when invoked, optionally invokes the OnNukeChannel callback to perform the nuking operation and then returns a CommandResult indicating the channel history is being nuked. + +## Remarks +This method acts as a thin wrapper around nuking logic, decoupling the command invocation from the actual nuking work by delegating to OnNukeChannel. It always returns a CommandResult, enabling a uniform response path whether or not a callback is attached. + +## Source Code +```csharp +private async Task HandleNuke() +{ + if (OnNukeChannel is not null) + await OnNukeChannel(); + return new CommandResult(true, "Nuking channel history..."); +} +``` + +## Dependencies +- CommandResult + +## Dependency APIs (verified signatures) +- record `CommandResult` (`src/EchoHub.Client/Commands/CommandHandler.cs`) + +## Symbol To Document +- Name: `HandleNuke` +- Kind: `method` +- File: `src/EchoHub.Client/Commands/CommandHandler.cs` +- Language: `csharp` +- ID: ecfce33b-9722-42e3-ab86-a70abb710ed8 + +--- + +## ParsePathAndSizeFlag +> **File:** `src/EchoHub.Client/Commands/CommandHandler.cs` +> **Kind:** method + +```csharp +private static (string Path, string? Size) ParsePathAndSizeFlag(string args) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Path` | `string` | — | +| `Size` | `string?` | — | + + +Parses a single argument string to extract a file path (which may be quoted) and an optional size flag (-s, -m, or -l). The flag can be placed either before or after the path, provided there is a separating space. The method returns a tuple (Path, Size) where Path is the cleaned file path and Size is null or the single-letter flag ('s', 'm', or 'l'). The Path is produced by stripping surrounding quotes via StripQuotes. + +## Remarks +Centralizes argument parsing for command-line handling. It supports both -flag path and path -flag formats, selecting the flag based on the first matching pattern and ensuring unambiguous separation by a space. The path is normalized by removing surrounding quotes, reducing downstream quoting concerns and making the return value straightforward to consume. + +## Notes +- If both start and end forms are present, the end form wins because the end-check runs first and the start form is only considered if no end flag was found. +- A space is required to delimit the flag from the path (either before or after); without the space, the flag is not recognized. +- This is an internal helper (private) intended for use within the command handling logic; external callers cannot rely on it directly. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Config/ClientConfig.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Config/ClientConfig.cs.md new file mode 100644 index 0000000..23b724f --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Config/ClientConfig.cs.md @@ -0,0 +1,124 @@ +# ClientConfig.cs + +> **Source:** `src/EchoHub.Client/Config/ClientConfig.cs` + +## Contents + +- [AccountPreset](#accountpreset) +- [ClientConfig](#clientconfig) +- [NotificationConfig](#notificationconfig) +- [SavedServer](#savedserver) + +--- + +## AccountPreset +> **File:** `src/EchoHub.Client/Config/ClientConfig.cs` +> **Kind:** class + +```csharp +public class AccountPreset +``` + + +AccountPreset is a lightweight data container that groups three optional account identity properties—DisplayName, Bio, and NicknameColor—so callers can apply or persist a predefined persona for an account. It is intended for use in client configuration (ClientConfig.cs), enabling a consistent, reusable identity profile to be attached to account-related logic. + +## Remarks +AccountPreset exists to keep related identity attributes together, reducing the surface area of APIs that need to accept or propagate persona data. It aligns with a configuration/templating pattern in the client, making it easier to serialize, store, and reuse account personas across components that render or modify user identity. + +## Notes +- All properties are nullable; callers must define default behavior when a property is null (e.g., preserve existing values or apply a fallback). +- Null-valued properties may be serialized depending on the chosen serializer; configure to ignore nulls if you prefer a clean configuration payload. +- There is no validation here; enforce constraints instead in the surrounding configuration or UI logic. + +--- + +## ClientConfig +> **File:** `src/EchoHub.Client/Config/ClientConfig.cs` +> **Kind:** class + +```csharp +public class ClientConfig +``` + + +ClientConfig is the central container for a user's preferences and runtime state in the EchoHub client. It aggregates saved servers, the active account preset, the UI theme, notification settings, and attachment-handling options such as the download path and ASCII-rendering size. + +## Remarks + +It acts as a single source of truth for components that configure server connectivity, UI theming, and how attachments are stored and rendered. Centralizing defaults and user-specific values reduces duplication and helps ensure consistent behavior across sessions and test environments. + +## Example + +```csharp +var config = new ClientConfig +{ + SavedServers = new List + { + new SavedServer { Name = "Work", Url = "https://work.example", RememberMe = true } + }, + DownloadPath = @"C:\Downloads", + DefaultAsciiSize = "m" +}; +``` + +## Notes + +- DownloadPath being null means attachments and saved images go to the OS Downloads folder. Ensure the application has write permissions to that location when relying on the default. +- DefaultAsciiSize accepts "s" (40×40), "m" (80×80), or "l" (120×120). This size applies to copy-paste/drag-drop attachments that do not carry a per-file size flag. + + +--- + +## NotificationConfig +> **File:** `src/EchoHub.Client/Config/ClientConfig.cs` +> **Kind:** class + +```csharp +public class NotificationConfig +``` + + +NotificationConfig is a lightweight data container used by the EchoHub client to express how notifications should behave. It encapsulates three related knobs: Enabled, Volume, and SoundFile. Developers instantiate this class to configure or override the client's notification behavior when wiring up configuration (for example, within ClientConfig) or when configuring the notifier component. The defaults indicate that notifications are enabled by default, a modest default volume, and no custom sound file unless specified. + +## Remarks + +By grouping notification-related settings into a single object, NotificationConfig reduces coupling between components that render or play notification sounds and the rest of the configuration. It also provides a clean extension point: new knobs can be added in the future without scattering settings across call sites, since a single configuration object can be passed around. + +## Example + +```csharp +var config = new NotificationConfig +{ + Enabled = true, + Volume = 40, + SoundFile = "assets/notify.wav" +}; +``` + +## Notes + +- Volume is stored as a byte (0–255). If your UI operates in a 0–100 range, map or clamp values appropriately before consumption. +- SoundFile is nullable; when it is null, the consumer should handle the absence of a custom sound (e.g., fall back to a default sound or skip audible notification based on the environment). + + +--- + +## SavedServer +> **File:** `src/EchoHub.Client/Config/ClientConfig.cs` +> **Kind:** class + +```csharp +public class SavedServer +``` + + +SavedServer is a client-side representation of a per-server configuration and its associated local state for the EchoHub client. It stores credentials and connection details (Name, Url, Username, RefreshToken), a RememberMe flag, and the last connection timestamp (LastConnected). It also holds per-channel state that remains on the client: ChannelKeys (end-to-end encrypted keys cached per channel), LeftChannels (channels the user explicitly left), and LastReadMessages (per-channel read markers). These keys live only on the user's machine; the server never sees them. + +## Remarks +SavedServer acts as the single source of truth for a user's relationship to a particular server within the client. By keeping ChannelKeys and LastReadMessages client-side, the app can decrypt and present channel content and maintain read state even after restarts, without leaking sensitive information to the server. LeftChannels honors user intent by preventing auto-joining of channels the user has consciously left, until they rejoin. This abstraction fits alongside other per-server configuration objects and collates server identity, credentials, and per-channel metadata for efficient session restore and UX. + +## Notes +- Sensitive data such as RefreshToken and ChannelKeys should be stored securely at rest; the server never holds these values. +- These collections are mutable; ensure proper synchronization if accessed from multiple threads to avoid data races or inconsistent state. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Config/ConfigManager.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Config/ConfigManager.cs.md new file mode 100644 index 0000000..48b2d37 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Config/ConfigManager.cs.md @@ -0,0 +1,21 @@ +# ConfigManager + +> **File:** `src/EchoHub.Client/Config/ConfigManager.cs` +> **Kind:** class + +```csharp +public static class ConfigManager +``` + + +ConfigManager provides a thread-safe, single-point API for loading and persisting the client's configuration to disk. Use Load to read the current ClientConfig and Save/SaveServer/RemoveServer to apply changes from the UI or background tasks (for example, after token refreshes or updating saved servers). + +## Remarks + +ConfigManager stores the configuration in a JSON file named config.json inside a per-user directory (.echohub) under the current user's profile. All file I/O is serialized with a private lock (FileLock) to prevent concurrent access from UI threads and background tasks. When you call SaveServer, the code locates an existing SavedServer by URL (case-insensitive) and updates it, or appends a new one if none exists; RemoveServer deletes entries by URL. The design uses best-effort error handling—exceptions are swallowed to avoid disrupting the app—but this means persistence failures are not surfaced to callers unless they implement their own checks. + +## Notes + +- Persistence operations swallow all exceptions, making failures non-fatal but potentially leading to invisible data loss. +- SavedServers are deduplicated by URL using a case-insensitive comparison; updating an existing URL won't create a duplicate. +- ConfigDir uses Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); on systems where a user profile is unavailable or access is restricted, initialization may fall back to a default path. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Program.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Program.cs.md new file mode 100644 index 0000000..3813afe --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Program.cs.md @@ -0,0 +1,15 @@ +# Program + +> **File:** `src/EchoHub.Client/Program.cs` +> **Kind:** file + + +The Program file serves as the application's entry point and startup bootstrap for the EchoHub client. It coordinates early startup tasks such as rollback handling, permission checks, configuration provisioning, logging setup, PATH preparation, post-update cleanup, and UI initialization before handing control to the main orchestrator and theme system. + +## Remarks +It functions as a central bootstrap that hides cross-cutting concerns from downstream components. By coordinating UpdateBackupService for rollback support, PathSetup for PATH hygiene, and ThemeManager for theming, it decouples startup sequencing from the rest of the application and ensures the runtime begins in a well-defined state. + +## Notes +- Rollback path exits the process after attempting a restore; normal startup does not proceed. +- If appsettings.json is missing, the code seeds it from an embedded example; if the resource isn't available, startup continues with defaults. +- Several operations are best-effort and exceptions are swallowed to avoid stopping startup (e.g., Unix permissions adjustments, cleanup of a leftover .old executable). \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/ApiClient.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/ApiClient.cs.md new file mode 100644 index 0000000..a6b809d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/ApiClient.cs.md @@ -0,0 +1,1422 @@ +# ApiClient.cs + +> **Source:** `src/EchoHub.Client/Services/ApiClient.cs` + +## Contents + +- [ApiClient](#apiclient) + - [ApiClient (constructor)](#apiclient-constructor) + - [BaseUrl](#baseurl) + - [RefreshToken](#refreshtoken) + - [Token](#token) + - [AssignRoleAsync](#assignroleasync) + - [AuthenticatedGetAsync](#authenticatedgetasync) + - [AuthenticatedRequestAsync](#authenticatedrequestasync) + - [BanUserAsync](#banuserasync) + - [CreateChannelAsync](#createchannelasync) + - [CreateInviteAsync](#createinviteasync) + - [DeleteChannelAsync](#deletechannelasync) + - [DeleteMessageAsync](#deletemessageasync) + - [DeleteMyAccountAsync](#deletemyaccountasync) + - [Dispose](#dispose) + - [DownloadFileToTempAsync](#downloadfiletotempasync) + - [EnsureAuthenticated](#ensureauthenticated) + - [EnsureSuccessAsync](#ensuresuccessasync) + - [ExportMyDataAsync](#exportmydataasync) + - [GetChannelCryptoAsync](#getchannelcryptoasync) + - [GetChannelMetaAsync](#getchannelmetaasync) + - [GetChannelsAsync](#getchannelsasync) + - [GetContentType](#getcontenttype) + - [GetEncryptionKeyAsync](#getencryptionkeyasync) + - [GetInvitesAsync](#getinvitesasync) + - [GetServerInfoAsync](#getserverinfoasync) + - [GetUserProfileAsync](#getuserprofileasync) + - [GetValidTokenAsync](#getvalidtokenasync) + - [KickUserAsync](#kickuserasync) + - [LoginAsync](#loginasync) + - [LoginWithRefreshTokenAsync](#loginwithrefreshtokenasync) + - [LogoutAsync](#logoutasync) + - [MuteUserAsync](#muteuserasync) + - [NukeChannelAsync](#nukechannelasync) + - [RefreshTokenAsync](#refreshtokenasync) + - [RegisterAsync](#registerasync) + - [RekeyChannelAsync](#rekeychannelasync) + - [RevokeInviteAsync](#revokeinviteasync) + - [SendMessageWithAttachmentsAsync](#sendmessagewithattachmentsasync) + - [SetTokens](#settokens) + - [UnbanUserAsync](#unbanuserasync) + - [UnmuteUserAsync](#unmuteuserasync) + - [UpdateChannelTopicAsync](#updatechanneltopicasync) + - [UploadAvatarAsync](#uploadavatarasync) +- [SendUrlAsync](#sendurlasync) +- [UpdateProfileAsync](#updateprofileasync) + +--- + +## ApiClient +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** class + +```csharp +public sealed class ApiClient : IDisposable +``` + + +A high-level HTTP client for EchoHub that centralizes authentication (login, refresh, logout) and common server operations (channels, messages, uploads, invites, profile). Use ApiClient when you want a single, in-memory service to manage access/refresh tokens, provide a token for long-lived connections (SignalR), and call the server's REST endpoints through convenient async methods. + +## Remarks +This class wraps an HttpClient and keeps the current access and refresh tokens in memory, exposing them via the Token and RefreshToken properties and notifying consumers through the OnTokensRefreshed event. GetValidTokenAsync is intended as the token provider for long-lived connections and will proactively refresh an access token that is near expiry (the implementation refreshes if the token expires within about 60 seconds). Methods that return DTOs commonly use nullable results to indicate "not found" or absence. + +## Example +```csharp +// Create the client and log in +using var api = new ApiClient("https://api.example.com"); +var login = await api.LoginAsync("alice", "s3cret"); + +// Persist tokens or react when they've been refreshed +api.OnTokensRefreshed += () => +{ + var latestAccess = api.Token; + var latestRefresh = api.RefreshToken; + // Save to secure storage if needed +}; + +// Use the token provider for a SignalR connection or call APIs that need auth +var tokenForSignalR = await api.GetValidTokenAsync(); +var channels = await api.GetChannelsAsync(); +``` + +## Notes +- GetValidTokenAsync may refresh the token when it will expire within ~60 seconds; callers should still handle server-side authorization failures. +- LogoutAsync is implemented as "best-effort" — it may not always revoke server-side state; clear persisted tokens yourself if you saved them. +- Tokens are stored only in memory by this client. To persist them across restarts, subscribe to OnTokensRefreshed and save Token/RefreshToken externally. + +--- + +### ApiClient (constructor) +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** constructor + +```csharp +public ApiClient(string baseUrl) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `baseUrl` | `string` | — | + + +Initializes an ApiClient with a base URL, normalizes the URL by removing any trailing slash, and configures an HttpClient whose BaseAddress is that normalized URL. This ensures that subsequent requests can be issued with relative URIs against the configured API host. + +## Remarks +This constructor centralizes HTTP client initialization for the API client, enforcing a consistent base address across calls. By normalizing the base URL, it prevents subtle URI mistakes when composing requests. It encapsulates the HttpClient setup so callers don’t have to manage base addresses or client lifetimes directly. + +## Example +```csharp +var client = new ApiClient("https://api.example.com/"); +``` + +## Notes +- baseUrl must be non-null; passing null will throw a NullReferenceException at TrimEnd('/'). +- If baseUrl is not a well-formed absolute URL, creating new Uri(BaseUrl) will throw UriFormatException. + + +--- + +### BaseUrl +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** property + +```csharp +public string BaseUrl +``` + + +BaseUrl is a read-only string property that exposes the root URL the ApiClient uses to construct request URIs. It provides a single source of truth for the API endpoint so callers can reason about where requests are sent without mutating the value at runtime. + +## Remarks +BaseUrl serves as the canonical root for all REST calls performed by the ApiClient. Centralizing the endpoint simplifies testing across environments (dev, staging, prod) because the rest of the client can build URIs without caring about the actual host. Since it is read-only, the value is established during construction; to change environments you create a new client instance with a different BaseUrl. It integrates with the request pipeline by being the starting point for path composition. + +## Notes +- Value is set in constructor; to change it, instantiate new ApiClient with a different BaseUrl. +- When combining with path segments, avoid manual string concatenation; prefer proper Uri or relative path builders to prevent double slashes. + +--- + +### RefreshToken +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** property + +```csharp +public string? RefreshToken => _refreshToken +``` + + +The RefreshToken property is a read-only accessor that returns the current value of the private _refreshToken field. Because it is nullable, callers should be prepared for a null value when no token is stored or when the token has been cleared. + +## Remarks +The property provides a lightweight way to observe or forward the stored refresh token without permitting mutation. It reinforces centralized token management by keeping updates to _refreshToken out of the consumer's hands, while still enabling advanced scenarios such as diagnostics or token-forwarding workflows that require the current token value. + +## Notes +- The value may be null; always account for a possible null return in calling code. +- Do not log or transmit the token in telemetry or UI streams; treat it as sensitive information and guard its exposure. + + +--- + +### Token +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** property + +```csharp +public string? Token => _accessToken +``` + + +Exposes the current access token as a read-only, nullable string. This property simply forwards the value stored in the private backing field _accessToken, providing a stable API surface for callers that need to read the token without mutating the field. Since the value can be null when no token is present, callers should handle null gracefully, for example by guarding token-dependent logic or by omitting the token from headers when it is absent. + +## Remarks +This property acts as a stable abstraction over the token storage, decoupling callers from how and where the token is stored. It allows the rest of the API client to evolve its token management (for example, refreshing tokens or lazy loading) without affecting callers that just need to read the current value. It also signals that token retrieval is a side-effect-free operation, reinforcing a read-only contract for consumers. + +--- + +### AssignRoleAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task AssignRoleAsync(string username, ServerRole role) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `role` | [`ServerRole`](../../EchoHub.Core/Models/ServerRole.cs.md) | — | + +**Returns:** `Task` + + +AssignRoleAsync assigns a server-side role to a user by issuing an authenticated POST request to the moderation API. It builds an AssignRoleRequest from the provided username and role and posts it to /api/moderation/role. The call is preceded by EnsureAuthenticated() and followed by EnsureSuccessAsync(response), so authentication is enforced and failures are surfaced as exceptions. The method is asynchronous and returns a Task that completes when the server confirms success. + +--- + +### AuthenticatedGetAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private async Task AuthenticatedGetAsync(string url) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `url` | `string` | — | + +**Returns:** `Task` + + +Performs a GET request against the provided URL and, if the response is 401 Unauthorized and a non-empty refresh token is available, automatically refreshes the token and retries the request. The original response is disposed before replacing it with the retried response. The caller is responsible for disposing the final HttpResponseMessage returned by this method. If the token refresh fails, the original response is returned unchanged. + +## Remarks +By centralizing this refresh-and-retry logic, the API client avoids duplicating authentication-handling boilerplate across multiple calls and ensures a consistent behavior when a token has expired. The method keeps retry logic deliberately simple: at most one retry is attempted, and only when a refresh token exists, to prevent potential retry storms and loops. + +## Notes +- Exceptions thrown by RefreshTokenAsync are swallowed; if the refresh process fails, the original 401 (or other status) is returned without propagating an error. +- The initial response is disposed when a retry occurs to avoid leaking resources; the caller must dispose the final response they receive. + +--- + +### AuthenticatedRequestAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private async Task AuthenticatedRequestAsync(Func> requestFactory) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `requestFactory` | `Func>` | — | + +**Returns:** `Task` + + +Performs an HTTP request with automatic token refresh on a 401 Unauthorized response. You supply a factory that creates the request; if the call yields 401 and a refresh token is present, it refreshes the token and retries once. The caller is responsible for disposing the returned HttpResponseMessage. + +## Remarks +Encapsulates the common pattern of refreshing an access token to keep HTTP call sites concise and consistent. It enforces a single refresh-and-retry cycle to avoid repeated token refresh attempts and unintended multiple requests. If the refresh fails or there is no refresh token, the original response is returned, allowing callers to handle authentication failures uniformly. The returned HttpResponseMessage should always be disposed by the caller. + +## Example +```csharp +// Inside the class that defines AuthenticatedRequestAsync, assuming a configured httpClient exists +HttpResponseMessage response = await AuthenticatedRequestAsync(() => httpClient.GetAsync("https://api.example.com/protected")); +``` + +## Notes +- If a 401 is observed without a valid refresh token, the call returns the original 401 without attempting a refresh. +- The final HttpResponseMessage must be disposed by the caller; the method disposes the original response only when a retry occurs and a new response is obtained. + +--- + +### BanUserAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task BanUserAsync(string username, string? reason = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `reason` | `string?` | `null` | + +**Returns:** `Task` + + +BanUserAsync bans a user by their username via the server's moderation API. It ensures the caller is authenticated, then issues a POST to /api/moderation/ban/{Uri.EscapeDataString(username)} with a BanRequest payload that carries the optional reason. The operation completes when EnsureSuccessAsync confirms a successful HTTP response; otherwise, it throws. Use this helper when you want to ban a user through the API client instead of assembling HTTP calls yourself. + +## Remarks +This method encapsulates the authentication check and the HTTP POST, providing a single, reusable surface for moderation actions. It hides the exact endpoint path and JSON payload, reducing duplication and centralizing error handling via EnsureSuccessAsync. + +## Notes +- Authentication is enforced by EnsureAuthenticated before performing the request; if the client is not authenticated, this will fail early. +- The username is URL-escaped with Uri.EscapeDataString to prevent route interpretation issues. +- BanRequest is constructed with the optional reason; passing null is allowed. + +--- + +### CreateChannelAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task CreateChannelAsync(string name, string? topic = null, bool isPublic = true, + string? [REDACTED:CONNECTION_STRING_PASSWORD] string? encryptionSalt = null, string? wrappedRoomKey = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `name` | `string` | — | +| `topic` | `string?` | `null` | +| `isPublic` | `bool` | `true` | +| `encryptionSalt` | `string? [REDACTED:CONNECTION_STRING_PASSWORD] string?` | `null` | +| `wrappedRoomKey` | `string?` | `null` | + +**Returns:** `Task` + + +Creates a new channel on the server by sending a CreateChannelRequest after ensuring the caller is authenticated. Use this method when you need to programmatically create a channel by name with optional topic and visibility settings, optionally including encryption-related data; it handles request construction, HTTP communication, and JSON deserialization into a ChannelDto. + +## Remarks +This abstraction centralizes the channel-creation workflow in the client. It automatically enforces authentication, builds the payload (including optional topic, visibility, and encryption-related fields), issues the POST to the /api/channels endpoint, and deserializes the response into a ChannelDto for the caller. By encapsulating these concerns, callers avoid manual HTTP handling and keep channel creation consistent across the codebase. The method returns a ChannelDto representing the newly created channel, or null if the response body cannot be parsed into that shape. + +## Notes +- Requires the client to be authenticated; an unauthenticated call will be rejected by EnsureAuthenticated/EnsureSuccessAsync. +- The JSON deserialization may yield null if the response body is empty or not compatible with ChannelDto. +- If encryptionSalt or wrappedRoomKey are provided, they influence the server-side setup for encrypted channel access; incorrect values may cause the server to reject the request. + +--- + +### CreateInviteAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task CreateInviteAsync(int? maxUses = null, int? expiresInHours = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `maxUses` | `int?` | `null` | +| `expiresInHours` | `int?` | `null` | + +**Returns:** `Task` + + +Creates a new invite by sending a POST request to the server with an optional maximum usage limit and expiration window. The operation requires the user to be authenticated and returns the created invite data when the server responds successfully. If maxUses or expiresInHours are not supplied, the server applies its defaults. Use this method when you need to programmatically generate a shareable invite with controlled usage or expiry. + +## Remarks +This method serves as a focused, typed abstraction over the invites API. It hides HTTP details (endpoint path, request payload, and response parsing) and centralizes authentication and basic success handling, so callers don’t need to manage HTTP lifecycles or error translation. It relies on InviteDto and CreateInviteRequest to shape the contract and on the underlying HTTP client to perform the request. + +## Notes +- Requires authentication; calling without a valid authenticated context will cause an exception via EnsureAuthenticated. +- maxUses and expiresInHours are nullable; omitting them defers to the server’s default behavior. +- Returns InviteDto?; callers should handle potential null if the response body is empty or deserialization yields no content. + +--- + +### DeleteChannelAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task DeleteChannelAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Deletes a channel on the server by its name. It first ensures the client is authenticated, then issues an authenticated HTTP DELETE to /api/channels/{encodedName}, where the channel name is URL-encoded to safely survive special characters. The response is validated with EnsureSuccessAsync, and the operation completes when the server confirms success. Use this method when you need to remove a channel from the backend by name, rather than performing a raw HTTP request. + +## Remarks +This method encapsulates the REST pattern for removing a resource and centralizes authentication and error handling. By encoding the channel name and validating the response, it provides a reliable, reusable operation for channel management across the client. It relies on EnsureAuthenticated, AuthenticatedRequestAsync, and EnsureSuccessAsync, aligning with the client's approach to API calls. + +## Example +```csharp +// Delete a channel named "general" +await apiClient.DeleteChannelAsync("general"); +``` + +## Notes +- The channel name is URL-encoded in the request path using Uri.EscapeDataString to handle spaces and special characters. +- Non-success HTTP responses will throw exceptions via EnsureSuccessAsync; consider wrapping in try/catch if you need to surface user-friendly errors. + +--- + +### DeleteMessageAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task DeleteMessageAsync(Guid messageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messageId` | `Guid` | — | + +**Returns:** `Task` + + +Deletes a moderation message identified by messageId by issuing an authenticated HTTP DELETE request, and then ensures the response indicates success. Use this method when you need to remove a specific moderation message through the client without dealing with authentication or direct HTTP handling. + +## Remarks +This method centralizes the common pattern of authenticated server mutations: vetting authentication, performing the HTTP call through a shared AuthenticatedRequestAsync wrapper, and validating success with EnsureSuccessAsync. It hides the details of the endpoint path and response handling from callers, offering a clean, exception-driven contract where failures surface as exceptions. The operation does not return a payload; callers rely on the absence of an exception to determine success. + +## Notes +- Non-success HTTP responses (such as 404, 403, or 5xx) are surfaced as exceptions via EnsureSuccessAsync. +- The call depends on a valid authenticated context; if authentication is not established, EnsureAuthenticated will throw before the HTTP request is issued. + +--- + +### DeleteMyAccountAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task DeleteMyAccountAsync(string password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `password` | `string` | — | + +**Returns:** `Task` + + +Deletes the currently authenticated user's account by issuing an HTTP DELETE to /api/users/me with a JSON payload containing the provided password to confirm intent. The method first verifies the caller is authenticated, performs the request, and then asserts a successful server response. Use this when a user explicitly wants to permanently remove their own account; the password requirement helps prevent accidental deletions. + +## Remarks +Encapsulates the account-deletion flow within the client to centralize authentication validation, request construction, and server response handling. The operation relies on a DeleteAccountRequest DTO to carry the password payload, aligning client and server contracts and keeping sensitive data isolated in the request body. The surrounding EnsureAuthenticated and EnsureSuccessAsync calls provide clear preconditions and postconditions for callers and tests, reducing boilerplate at call sites. + +## Example +```csharp +// Example usage: +await client.DeleteMyAccountAsync("P@ssw0rd!"); +``` + +## Notes +- This is a destructive, irreversible operation; confirm user intent and consider UX safeguards before invoking. +- The method does not return a value; failures surface as exceptions via EnsureSuccessAsync. Wrap calls in appropriate error handling if needed. +- The password is transmitted as part of the request payload; avoid logging the password and ensure transport security is in place. + +--- + +### Dispose +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public void Dispose() +``` + +**Returns:** `void` + + +Disposes the internal HTTP resource held by this ApiClient by delegating to _http.Dispose(). Call Dispose when you’re finished using the ApiClient to ensure network resources are released promptly, rather than waiting for finalization. + +## Remarks + +This is a straightforward implementation of the IDisposable pattern: the outer wrapper delegates cleanup to its disposable member. By disposing the inner _http resource, the ApiClient ensures that associated network resources (such as open connections) are released in a deterministic manner as soon as the caller is done with the instance. + +## Example + +```csharp +using (var client = new ApiClient()) +{ + // use client +} +``` + +## Notes + +- If the internal _http resource is shared with other components, disposing the ApiClient may affect those components; ensure ownership semantics are clear. +- After Dispose is called, subsequent use of the ApiClient (or its _http) may throw ObjectDisposedException unless the class guards against use after disposal. + +--- + +### DownloadFileToTempAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task DownloadFileToTempAsync(string relativeUrl, string fileName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `relativeUrl` | `string` | — | +| `fileName` | `string` | — | + +**Returns:** `Task` + + +Ensures authentication, retrieves content from the given relative URL via an authenticated GET, and validates the HTTP response. It then creates a temporary EchoHub directory under the system temp path, streams the response body to a uniquely named file there, and returns the file path. + +## Remarks +Centralizes the common pattern of authenticated download and temporary-file storage, reducing duplication across callers. The method uses a GUID-based filename to avoid collisions and writes the stream directly to disk, minimizing memory usage. It returns the path to the temporary file but does not perform cleanup; callers should delete the file when it is no longer needed to avoid littering the temp directory. + +## Notes +- Creates the EchoHub subdirectory in the system temporary path if it does not exist. +- Uses a GUID (with no dashes) as part of the filename to guarantee uniqueness. +- The return value is a path to the downloaded temporary file; callers are responsible for cleanup. +- No cancellation token or progress reporting is exposed by this API. + +--- + +### EnsureAuthenticated +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private void EnsureAuthenticated() +``` + +**Returns:** `void` + + +This private guard validates that the ApiClient is in a state suitable for making authenticated requests by ensuring the internal _accessToken is present. When the token is missing or empty, it signals misuse of the client by throwing InvalidOperationException with guidance to call LoginAsync or RegisterAsync before attempting any API calls. + +## Remarks +This centralizes the authentication precondition in ApiClient, so all protected operations rely on a single, consistent guard. It communicates a clear contract: you must authenticate prior to using the client. By encapsulating the check, code duplication is reduced and the error message remains uniform across methods that require authentication. + +## Notes +- The method only checks for a non-empty _accessToken; it does not validate token expiry or current validity. Expired or invalid tokens may still cause failures at the API boundary, which should be handled by higher-level logic if present. + +--- + +### EnsureSuccessAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private static async Task EnsureSuccessAsync(HttpResponseMessage response) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `response` | `HttpResponseMessage` | — | + +**Returns:** `Task` + + +Converts non-success HTTP responses into a single HttpRequestException with a best-effort error message. If the response is unsuccessful, it builds a message from the status code and reason phrase, then optionally enriches it by extracting a top-level 'error' or 'Error' property from a JSON body; if those properties are absent or parsing fails, it falls back to the raw body or the status message, and finally throws HttpRequestException with that message. + +## Remarks +Centralizes HTTP error handling in the client. It encapsulates the logic for translating HTTP failure responses into exceptions, so callers can catch HttpRequestException and rely on a consistent message shape. It uses JsonDocument to inspect the body for 'error'/'Error' fields and gracefully degrades when the body is not JSON or lacks those fields. + +## Notes +- Parsing failures during body extraction are swallowed; the catch block is intentionally empty, so a non-JSON body or parsing error won't crash the flow but may limit message richness. +- The fallback to using the raw body in the error message can reveal server details; avoid logging or exposing this in user-facing errors. +- The method is private and intended for internal use; external callers cannot invoke it directly. + +--- + +### ExportMyDataAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task ExportMyDataAsync() +``` + +**Returns:** `Task` + + +Downloads the authenticated user's complete data export as raw JSON text. The method authenticates the caller, performs an authenticated GET to /api/users/me/export, ensures the response indicates success, and returns the response body as a string for downstream processing or persistence. It is suited for data portability or backup scenarios where the consumer will parse or store the JSON themselves. + +## Remarks +This symbol provides a focused convenience around the ApiClient by hiding endpoint details and error handling behind EnsureAuthenticated and EnsureSuccessAsync. By returning raw JSON instead of a deserialized object, it offers maximum flexibility for downstream processing, partial deserialization, or deferred parsing in response to evolving export schemas. + +## Notes +- The payload is returned as raw JSON text; there is no deserialization here, so callers should parse it if they need structured data. +- The entire payload is read into memory via ReadAsStringAsync; for very large exports this can incur noticeable memory usage. Consider streaming approaches or server-side handling if the export size is a concern. + +--- + +### GetChannelCryptoAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetChannelCryptoAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Retrieves the public cryptographic metadata for a channel, indicating whether the channel is end-to-end encrypted and the key-derivation salt. If the channel does not exist, the method returns null. It requires an authenticated context, issues an HTTP GET to /api/channels/{channelName}/crypto with channelName URI-escaped, and deserializes the JSON body into a ChannelCryptoDto. + +## Remarks + +Encapsulates the remote API contract for channel crypto settings, providing a single, typed entry point for clients. It centralizes authentication enforcement and error handling so callers do not need to manage low-level HTTP concerns. The NotFound (404) path is represented by a null return value, while other HTTP errors are surfaced as exceptions by EnsureSuccessAsync. + +## Notes + +- 404 Not Found is mapped to null; non-success statuses throw. +- Channel name is escaped with Uri.EscapeDataString to ensure a safe, well-formed URL. +- JSON deserialization relies on the ChannelCryptoDto type; changes to the API shape may require updating the DTO. + +--- + +### GetChannelMetaAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetChannelMetaAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Fetches a channel's human-facing metadata (message count, unique posters, estimated size, created date, room id) for the /meta command. Returns null if it doesn't exist. The method authenticates the client, issues an HTTP GET to /api/channels/{channelName}/meta (with the channel name URI-escaped), returns null on a 404 Not Found, validates the response, and deserializes the JSON body into a ChannelMetaDto. The operation is asynchronous and relies on the client being authenticated prior to the call. + +--- + +### GetChannelsAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task> GetChannelsAsync() +``` + +**Returns:** `Task>` + + +Fetches the channels accessible to the currently authenticated user by calling the API endpoint `/api/channels`. It handles authentication, dispatches the HTTP GET, validates the response, and deserializes the JSON payload into a paginated wrapper, finally returning the list of [`ChannelDto`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) items (or an empty list if no data is available). This method provides a simple, strongly-typed surface for consumers who need to enumerate or process channels without dealing with HTTP details or pagination concerns. + +## Remarks +This symbol serves as a focused data fetch for the authenticated user's channels, encapsulating transport, auth, and error handling behind a clean API. It relies on `EnsureAuthenticated()` to confirm the user identity, `EnsureSuccessAsync(...)` to surface HTTP errors, and `ReadFromJsonAsync>()` to transform the payload. By returning `paginated?.Items ?? []`, callers always receive a non-null collection, even when the server returns no data. + +## Example +```csharp +var channels = await apiClient.GetChannelsAsync(); +foreach (var channel in channels) +{ + // Process each channel as needed +} +``` + +## Notes +- Returns an empty list when the API returns null or no items, never null. +- The method relies on authentication and HTTP status checks; callers should be prepared to handle exceptions from authentication failures or HTTP errors. + +--- + +### GetContentType +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private static string GetContentType(string fileName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `fileName` | `string` | — | + +**Returns:** `string` + + +GetContentType derives a MIME type from a filename by inspecting its extension. It centralizes a small, static mapping of common extensions to standard MIME types and falls back to application/octet-stream when the extension is unrecognized. + +## Remarks + +By using Path.GetExtension(fileName) and ToLowerInvariant(), the method performs case-insensitive matching and keeps the logic in a single place within ApiClient.cs, ensuring consistent Content-Type values across the client. Because it is private static, this helper is an internal concern of the API client and is not exposed as part of the public API; callers should rely on higher-level abstractions for content-type handling. + +## Notes + +- This method considers only the file extension and does not inspect the file contents; for security-sensitive scenarios, use content-based detection as needed. +- Unrecognized or missing extensions result in application/octet-stream, which is a safe default but may not reflect the actual content type. + +--- + +### GetEncryptionKeyAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetEncryptionKeyAsync() +``` + +**Returns:** `Task` + + +Gets the server-provided encryption key by performing an authenticated HTTP GET to /api/server/encryption-key. It first ensures an authenticated context, executes the request, verifies a successful response, deserializes the JSON payload into EncryptionKeyResponse, and returns the Key value. If the server returns no content, it throws an InvalidOperationException with the message "Server returned empty encryption key response." The caller receives the encryption key as a plain string for use in client-side encryption/decryption workflows. + +## Remarks +This method centralizes the retrieval of the server-supplied encryption key, encapsulating the endpoint path, authentication, and JSON deserialization behind a simple string return. It provides a stable surface for higher layers, hiding the details of the HTTP contract and error handling while ensuring a consistent failure path when the server cannot provide a key. Because keys may rotate or change over time, callers should decide on caching strategies appropriate to their security and consistency requirements. + +## Notes +- The call may throw if authentication fails, the HTTP response indicates failure, or the response body is empty (as explicitly guarded by the InvalidOperationException). +- The returned value is sensitive; avoid logging or persisting the key beyond its immediate use. + +--- + +### GetInvitesAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task> GetInvitesAsync() +``` + +**Returns:** `Task>` + + +GetInvitesAsync retrieves the invites for the currently authenticated user by issuing an authenticated HTTP GET to /api/invites. It ensures the caller is authenticated, verifies the HTTP response indicates success, and deserializes the JSON payload into a `List`. If the response body is null, an empty collection is returned, allowing callers to handle zero invites without additional null checks. + +## Remarks + +By encapsulating authentication, request dispatch, and JSON deserialization, this method hides boilerplate and enforces a consistent error-handling and data-contract approach for invite retrieval. It relies on the InviteDto data contract and the HTTP response content model to produce a strongly-typed result, reducing coupling between higher-level client code and the underlying HTTP details. + +## Example + +```csharp +var invites = await client.GetInvitesAsync(); +var total = invites.Count; +``` + +## Notes + +- Requires a valid authentication context; calling without authentication will cause EnsureAuthenticated to throw. +- Deserialization depends on the InviteDto contract; changes to server payload or InviteDto shape may require corresponding updates to this method and its callers. + +--- + +### GetServerInfoAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetServerInfoAsync() +``` + +**Returns:** `Task` + + +Retrieves the server's current status by making an asynchronous HTTP GET request to /api/server/info and deserializing the JSON response into a ServerStatusDto. It acts as a focused wrapper around a single API endpoint, allowing consumers to obtain server health and status information without performing HTTP requests or JSON parsing themselves. + +## Remarks +By delegating to the HttpClient-based call, this method encapsulates transport concerns and JSON deserialization, keeping UI components focused on rendering. It relies on an HttpClient instance provided to ApiClient (typically via dependency injection), which facilitates testing through mocks or stubs. If the API contract changes (e.g., a different endpoint or DTO), updating this single method reduces the spread of changes throughout the client. + +## Notes +- This method has no CancellationToken parameter; callers that need cancellation would need to adapt the signature or apply cancellation at a higher level. +- Non-success HTTP responses or JSON deserialization errors will surface as exceptions; callers should handle HttpRequestException or JsonException as appropriate. +- The return type is ServerStatusDto?, indicating callers should check for null before use, though the underlying HTTP call can still throw before a value is produced in some error cases. + +--- + +### GetUserProfileAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetUserProfileAsync(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task` + + +Gets the profile for a given username from the API. It requires the client to be authenticated, builds a GET request to /api/users/{username}/profile with the username safely escaped for the URL, validates that the response indicates success, and then deserializes the response JSON into a UserProfileDto. The return value is a UserProfileDto? representing the retrieved profile, or null if the payload is absent. + +## Remarks +By encapsulating the HTTP call and JSON deserialization, this method provides a typed, reusable access point for user-profile data. It aligns with the ApiClient's pattern of performing authenticated requests and interpreting JSON responses, reducing boilerplate for callers. + +## Example +```csharp +var profile = await client.GetUserProfileAsync("alice"); +if (profile is null) +{ + // handle missing profile +} +else +{ + // use profile +} +``` + +## Notes +- This method requires authentication; EnsureAuthenticated is called at the start and will raise if the client is not authenticated. +- The username is URL-escaped using Uri.EscapeDataString to ensure a safe path segment. +- The return type is nullable (UserProfileDto?), so callers should handle the null case appropriately. + +--- + +### GetValidTokenAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task GetValidTokenAsync() +``` + +**Returns:** `Task` + + +Gets a valid access token asynchronously. If there is no current token, it returns null. If the token is within 60 seconds of expiry and a refresh token is available, it attempts to refresh via RefreshTokenAsync; any exception from RefreshTokenAsync is swallowed to allow the caller to handle authentication failure, and the current token is returned anyway. This method is used by EchoHubConnection as the token provider for SignalR, centralizing token management so callers obtain a usable token without duplicating refresh logic themselves. + +## Remarks +This method centralizes the token lifecycle for EchoHubConnection's SignalR authentication. It reduces duplication by providing a single, reusable provider that handles refresh eligibility and fail-safe fallbacks. The refresh is best-effort; if RefreshTokenAsync fails or no refresh token is present, the method returns the current token, leaving the caller to respond to an authentication failure. + +## Notes +- Returns null when there is no access token, signaling the caller to re-authenticate. +- Refresh attempts occur only when the token is near expiry (within 60 seconds) and a refresh token is available. +- There is no explicit synchronization; concurrent calls may trigger multiple refresh attempts if used from multiple threads. + +--- + +### KickUserAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task KickUserAsync(string username, string? reason = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `reason` | `string?` | `null` | + +**Returns:** `Task` + + +KickUserAsync kicks a user by username through the moderation API. It ensures the client is authenticated, posts a KickRequest with the optional reason to the server, and validates the response, throwing on failure. + +## Remarks +This abstraction encapsulates the moderation HTTP call behind a typed DTO, keeping authentication and success handling centralized and out of the caller's business logic. It uses Uri.EscapeDataString to safely embed the username in the request path and relies on KickRequest to carry the optional reason payload, promoting a clean separation between transport concerns and domain logic. + +## Notes +- Requires an authenticated session; the method enforces this by calling EnsureAuthenticated() before issuing the request. +- Reason is optional; passing null results in a request with no explicit reason (as defined by KickRequest). +- Username in the URL is URL-encoded via Uri.EscapeDataString to form a safe request path. + +--- + +### LoginAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task LoginAsync(string username, string password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `password` | `string` | — | + +**Returns:** `Task` + + +LoginAsync authenticates a user by posting the supplied credentials to the API login endpoint, deserializes the LoginResponse, and stores the resulting tokens for subsequent requests. It hides HTTP transport and error handling behind a single asynchronous surface; use it when a user signs in to obtain and apply authentication tokens. + +## Remarks + +LoginAsync centralizes the authentication workflow within ApiClient, encapsulating the HTTP POST, response validation, and token application behind a single method. It guarantees token updates via SetTokens after a successful login so subsequent requests are authenticated, and any HTTP errors or a missing response body surface as exceptions. The response is disposed promptly through the using var pattern, ensuring resources are freed even in error cases. + +## Notes + +- Throws InvalidOperationException when the login response body is empty ("Login returned empty response."). +- Non-success HTTP statuses trigger exceptions via EnsureSuccessAsync. +- Relies on the server returning a non-null LoginResponse to feed SetTokens; if the payload does not provide tokens, subsequent authenticated calls may be ineffective. + +--- + +### LoginWithRefreshTokenAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task LoginWithRefreshTokenAsync(string refreshToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `refreshToken` | `string` | — | + +**Returns:** `Task` + + +Exchanges a refresh token for a new LoginResponse by posting a RefreshRequest to /api/auth/refresh, validates the HTTP response, and updates the client's stored tokens. Call this method when you need to refresh the access token without prompting the user to sign in again. + +## Remarks +Centralizes the token-refresh behavior within the API client: it encapsulates the HTTP call, JSON deserialization, and token state update. It relies on EnsureSuccessAsync to surface HTTP errors and on SetTokens to persist the new tokens, guaranteeing that subsequent requests use the refreshed credentials. + +## Notes +- Throws InvalidOperationException if the refresh response payload is empty (`ReadFromJsonAsync`() returns null). +- Non-success HTTP responses are surfaced via EnsureSuccessAsync; callers should handle exceptions that indicate refresh failure. +- This method mutates the client's token state via SetTokens(result); a successful return means the tokens were refreshed and are ready for use in subsequent requests. + +--- + +### LogoutAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task LogoutAsync() +``` + +**Returns:** `Task` + + +LogoutAsync ends the current session by (optionally) notifying the server to invalidate the refresh token and then clearing local authentication state. Call this when the user signs out to ensure both server-side revocation (when possible) and client-side cleanup. + +## Remarks +This method centralizes the sign-out flow in the client, coordinating server-side invalidation with a robust client-side cleanup. It uses a best-effort approach: if the server logout cannot be performed (e.g., network issues), the local sign-out still completes to prevent stale credentials from being used. Clearing the Authorization header in the HTTP client helps guarantee that subsequent requests are unauthenticated, even if other parts of the application held onto tokens in memory. + +## Notes +- The server logout is best-effort; any exception during the logout request is swallowed, so callers may not be notified of server-side success. +- The method clears both tokens and the Authorization header unconditionally, ensuring no authenticated state remains in the client after invocation. + +--- + +### MuteUserAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task MuteUserAsync(string username, int? durationMinutes = null, string? reason = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `durationMinutes` | `int?` | `null` | +| `reason` | `string?` | `null` | + +**Returns:** `Task` + + +Asynchronously mutes a user identified by username by sending a MuteRequest to the moderation endpoint. It requires authentication, constructs the URL with a safely escaped username, and posts a JSON body containing the optional duration and reason. The call completes once the server confirms success. + +## Remarks +Centralizes moderation API interactions for muting and hides HTTP details from callers. It relies on MuteRequest to carry the mute parameters and on the client’s authentication and success-handling scaffolding to provide consistent behavior across the application. + +## Notes +- durationMinutes is nullable; if omitted, the server may apply its default mute duration. +- reason is optional; omitting it mutes without a stated reason. +- If the server returns a non-success status, EnsureSuccessAsync will throw, propagating the failure to the caller. + +--- + +### NukeChannelAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task NukeChannelAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +NukeChannelAsync performs a server-side action to nuke a moderation channel identified by channelName. It ensures the client is authenticated, then issues an authenticated HTTP DELETE request to /api/moderation/channels/{Uri.EscapeDataString(channelName)}/nuke, and awaits the server's successful response. The method returns a Task and does not produce a value; it throws on error via EnsureSuccessAsync. + +## Remarks + +This wrapper abstracts a destructive moderation action behind a clear name and a consistent authorization pattern. It ensures that the operation is performed only after the client is authenticated and that a non-success HTTP response will surface an exception via EnsureSuccessAsync. This keeps the caller focused on intent (nuke the channel) rather than on HTTP details. + +## Example + +```csharp +// Example: Nuke a moderation channel named "general" +await apiClient.NukeChannelAsync("general"); +``` + +## Notes + +- This is a destructive admin operation; use with caution and ensure proper permissions. +- The channelName is URL-escaped to handle spaces or special characters. +- The method completes only after a successful HTTP response; exceptions are thrown for errors. + + +--- + +### RefreshTokenAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task RefreshTokenAsync() +``` + +**Returns:** `Task` + + +RefreshTokenAsync retrieves a new access token using the stored refresh token. It validates that a refresh token exists, posts it to the server's /api/auth/refresh endpoint as JSON, ensures the HTTP response indicates success, and then updates the client's token state from the returned LoginResponse. + +## Remarks +RefreshTokenAsync centralizes the token renewal flow inside the API client. It encapsulates the end-to-end interaction with the authentication service: validation of prerequisites, request construction, error propagation on HTTP or deserialization failures, and mutation of token state via SetTokens. Callers should rely on it to refresh credentials when needed, rather than handling HTTP details themselves. + +## Notes +- Throws InvalidOperationException when there is no refresh token available. (the early guard against missing _refreshToken) +- If the HTTP response indicates failure or the response body cannot be deserialized into a LoginResponse (i.e., it is null), the method propagates the error or throws InvalidOperationException("Token refresh returned empty response."). + + +--- + +### RegisterAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task RegisterAsync(string username, string password, string? displayName = null, string? inviteCode = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | +| `password` | `string` | — | +| `displayName` | `string?` | `null` | +| `inviteCode` | `string?` | `null` | + +**Returns:** `Task` + + +Registers a new user by sending a registration payload to the server and returning the resulting LoginResponse. It constructs a RegisterRequest from the supplied username, password, and optional displayName and inviteCode, posts it to /api/auth/register, ensures the HTTP response indicates success, deserializes a LoginResponse from the response body, stores authentication tokens via SetTokens, and then returns the result. This method encapsulates the end-to-end registration flow and hides HTTP transport and token management details from callers. + +## Remarks +RegisterAsync centralizes the end-to-end registration flow: request construction, transport, error handling, response parsing, and token persistence. By funneling these concerns through a single method, it ensures consistent error semantics (via EnsureSuccessAsync) and a single token-management strategy (via SetTokens) for a coherent authentication state on the client. + +## Example +```csharp +// Simple registration using only required parameters +var result = await apiClient.RegisterAsync("alice", "password"); +``` + +## Notes +- Deserialization can throw if the response body cannot be parsed as LoginResponse. +- If the server returns a non-success HTTP status, EnsureSuccessAsync will throw before parsing the body. +- Token storage is performed by SetTokens as a side effect; callers should expect authentication state to be updated after a successful registration. + +--- + +### RekeyChannelAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task RekeyChannelAsync(string channelName, RekeyChannelRequest request) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `request` | [`RekeyChannelRequest`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** `Task` + + +RekeyChannelAsync asynchronously initiates a key-rotation for a specific channel by posting a RekeyChannelRequest to the server and returning the updated ChannelDto. The call first asserts the caller is authenticated, then issues a POST to /api/channels/{escaped channelName}/rekey with the request payload, awaits a successful response, and deserializes the response body into a ChannelDto. The returned value may be null if the response has no content. + +--- + +### RevokeInviteAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task RevokeInviteAsync(string code) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `code` | `string` | — | + +**Returns:** `Task` + + +RevokeInviteAsync revokes a previously issued invitation identified by the supplied code. It ensures the caller is authenticated, then issues an authenticated HTTP DELETE to /api/invites/{Uri.EscapeDataString(code)} and finally validates the server response via EnsureSuccessAsync. + +## Remarks +By encapsulating the DELETE call behind EnsureAuthenticated/AuthenticatedRequestAsync, this method provides a single, consistent mechanism for removing invites and centralizes error handling and authentication concerns. It shields callers from HTTP details and small failure modes, while aligning with other client methods that perform authenticated operations. + +## Notes +- EnsureSuccessAsync will throw on non-success HTTP responses, so callers should handle exceptions for cases like missing or already-revoked invites. +- The invite code is URL-escaped with Uri.EscapeDataString to safely embed it in the request path. +- This method relies on prior authentication; if credentials are missing or invalid, EnsureAuthenticated will fail before the request is sent. + +--- + +### SendMessageWithAttachmentsAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task SendMessageWithAttachmentsAsync( + string channelName, string content, IReadOnlyList attachments, string? size = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `content` | `string` | — | +| `attachments` | `IReadOnlyList` | — | +| `size` | `string?` | `null` | + +**Returns:** `Task` + + +Sends a chat message to a channel with optional text and one or more attachments via multipart/form-data. For end-to-end encrypted channels, each attachment declares a kind and provides an encrypted preview (empty when none), and the caption is encrypted as well to protect metadata. + +## Remarks + +The method centralizes the multipart upload workflow for messages with attachments, including per-attachment encryption metadata handling and content-type determination. It performs authentication, constructs the form in a deterministic order so that per-file metadata (kind and preview) remains aligned with the corresponding file, and delegates transport and response handling to helper primitives (AuthenticatedRequestAsync and EnsureSuccessAsync). The optional size parameter enables a server-side formatting variation without changing the message payload. + +## Notes + +- For encrypted channels, DeclaredKind must be non-null to emit per-attachment kind and preview metadata; if DeclaredKind is null, those fields are omitted for that attachment. +- Each attachment is streamed individually with a Content-Type derived from the file name, and the server expects the metadata arrays (kind/preview) to line up with the corresponding files by index. +- The channel name is URL-escaped to form the request path, and an optional size query is appended when size is provided. + + +--- + +### SetTokens +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +private void SetTokens(LoginResponse result) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `result` | [`LoginResponse`](../../EchoHub.Core/DTOs/AuthDtos.cs.md) | — | + +**Returns:** `void` + + +Sets the local authentication state from a LoginResponse by storing the access token, refresh token, and expiration, updates the HttpClient to send a Bearer token with every request, and notifies subscribers that tokens have been refreshed. + +## Remarks +This method centralizes token management for the API client. By updating the shared HttpClient.DefaultRequestHeaders.Authorization, all outgoing requests automatically include the current access token, reducing boilerplate. The OnTokensRefreshed event allows other components to react to token updates (e.g., refresh UI or trigger persistence). It relies on a well-formed LoginResponse; callers should ensure result is non-null and contains valid Token/ExpiresAt values before invoking. + +## Notes +- No null checks exist for result or its properties; pass a valid LoginResponse to avoid NullReferenceException. +- DefaultRequestHeaders.Authorization is a global header on the HttpClient; concurrent token refreshes could race to set it, so coordinate refresh flows if ApiClient is used from multiple threads. + +--- + +### UnbanUserAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task UnbanUserAsync(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task` + + +UnbanUserAsync lifts a ban on a user by issuing an authenticated POST request to the moderation API. You call this when you need to programmatically remove a ban for a specific username, relying on the client’s authentication state and centralized error handling rather than crafting HTTP requests yourself. + +## Remarks +This method encapsulates the moderation action behind a stable API: it first ensures the caller is authenticated, then performs the request via a wrapper that handles authentication context, and finally asserts success through a centralized error-check. The username is URL-encoded to safely embed special characters in the path, and the payload is an empty JSON object, signaling a no-content action beyond the identifer in the URL. This pattern keeps moderation actions consistent across the client and reduces boilerplate for callers. + +## Example +```csharp +await apiClient.UnbanUserAsync("troublemaker42"); +``` + +## Notes +- The call requires a valid authenticated context; unauthenticated callers will be rejected by EnsureAuthenticated. +- The method uses Uri.EscapeDataString to safely include the username in the URL path. +- A non-success HTTP response will throw via EnsureSuccessAsync, so callers may want to handle exceptions to surface user-friendly errors. +- The request body is an empty object, reflecting a command-based action rather than data payload. + +--- + +### UnmuteUserAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task UnmuteUserAsync(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task` + + +UnmuteUserAsync unmutes a previously muted user by issuing a server request to the moderation API. Use this method when you need to lift a mute on a specific username from the EchoHub client. It enforces authentication, posts to the /api/moderation/unmute/{username} endpoint with an empty payload, and verifies the response signals success, abstracting away the HTTP boilerplate from callers. + +## Remarks +UnmuteUserAsync is a thin wrapper around the service's moderation unmute endpoint. It centralizes authentication and error handling, ensuring consistency across moderation operations. By escaping the username in the URL, it guards against path-breaking characters and injection issues. The method returns a Task and does not expose a value; success is communicated by completing normally or by exceptions produced by EnsureSuccessAsync. + +## Example +```csharp +// Example usage +await client.UnmuteUserAsync("john_doe"); +``` + +## Notes +- The request uses POST to /api/moderation/unmute/{Uri.EscapeDataString(username)} with an empty payload. +- Authentication is required; EnsureAuthenticated() enforces this before the HTTP call. +- The method does not return a value; success is indicated by normal completion, otherwise an exception is thrown by EnsureSuccessAsync. +- Username is URL-encoded to prevent issues with special characters. + +--- + +### UpdateChannelTopicAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task UpdateChannelTopicAsync(string channelName, string? topic) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `topic` | `string?` | — | + +**Returns:** `Task` + + +Updates the topic of a channel by performing an authenticated HTTP PUT to the server. Given a channel name and a desired topic, it builds UpdateTopicRequest and sends it to /api/channels/{channelName}/topic, with the channel name URL-escaped. It then validates the response and deserializes the updated ChannelDto from the response body. The method returns ChannelDto? to reflect a possibly absent payload. Use this when you need to change or clear a channel's topic in an authenticated context instead of composing the HTTP request manually. + +## Remarks +This method serves as the client-facing abstraction over a REST endpoint for channel topics. It centralizes authentication handling via EnsureAuthenticated and ensures consistent error handling with EnsureSuccessAsync, so callers don't need to manage HTTP status codes directly. It also encapsulates URL-encoding of the channel name, preventing issues with special characters. + +## Example +```csharp +// Example: update topic for a channel +var updated = await apiClient.UpdateChannelTopicAsync("general", "Discussions about general topics"); +``` + +## Notes +- Topic can be null to clear the topic. +- The response is deserialized to ChannelDto; if the server returns no content, the result may be null. +- The channel name in the URL is escaped to handle spaces or special characters. + +--- + +### UploadAvatarAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task UploadAvatarAsync(Stream imageStream, string fileName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `imageStream` | `Stream` | — | +| `fileName` | `string` | — | + +**Returns:** `Task` + + +Uploads the given image as the user's avatar by posting it as a multipart/form-data request to the server endpoint "/api/users/avatar". It ensures the caller is authenticated, builds the form data with the file attached under the field named "file", sets the content type from the file name, sends the request, validates the response, and deserializes the resulting JSON to return the AvatarAscii value (or null if missing). This method encapsulates the HTTP, content creation, and JSON parsing details, allowing callers to simply provide a stream and a filename to obtain the avatar representation. + +## Remarks +This method serves as a focused wrapper around the avatar-upload workflow. It centralizes authentication enforcement, multipart payload construction, endpoint contract (field name "file" and route "/api/users/avatar"), and server deserialization into a single, reusable call. By returning AvatarAscii from AvatarUploadResponse, it decouples UI concerns from image handling, enabling lightweight representations of avatars when a full image is not required. + +## Example +```csharp +// Assuming 'client' is an instance of ApiClient and the user is authenticated +using var stream = File.OpenRead("path/to/avatar.png"); +string? ascii = await client.UploadAvatarAsync(stream, "avatar.png"); +Console.WriteLine(ascii ?? "No avatar ASCII returned"); +``` + +## Notes +- The request uses multipart/form-data with the form field named "file" as required by the server contract. Changes to the field name or endpoint would break this integration. +- Ensure authentication is established before calling; the method invokes EnsureAuthenticated() and may fail if the user is not authenticated. +- The method returns AvatarAscii from AvatarUploadResponse, which may be null if the server omits it or the response cannot be deserialized. + +--- + +## SendUrlAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task SendUrlAsync(string channelName, string url, string? size = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `url` | `string` | — | +| `size` | `string?` | `null` | + +**Returns:** `Task` + + +SendUrlAsync posts a URL to the specified channel via the EchoHub HTTP API and returns the server’s MessageDto for the resulting message. Use this when you need to programmatically share a link in a channel and receive a typed representation of the posted message, with the client handling authentication, request construction, and response parsing. + +## Remarks + +By encapsulating the endpoint path construction, JSON payload, and authentication steps, this method reduces boilerplate for callers and enforces consistent error handling through EnsureSuccessAsync. It also escapes the channel name when building the URL to prevent routing errors caused by special characters. + +## Example + +```csharp +var result = await client.SendUrlAsync("general", "https://example.com", size: "1024"); +``` + +## Notes + +- The size parameter is appended as a raw query component; callers should pass URL-safe values or the method should be extended to URL-encode this value. +- The return value may be null if the response body is empty; callers should handle null appropriately. + + +--- + +## UpdateProfileAsync +> **File:** `src/EchoHub.Client/Services/ApiClient.cs` +> **Kind:** method + +```csharp +public async Task UpdateProfileAsync(UpdateProfileRequest request) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `request` | [`UpdateProfileRequest`](../../EchoHub.Core/DTOs/ProfileDtos.cs.md) | — | + +**Returns:** `Task` + + +Updates the authenticated user's profile by issuing a PUT request to /api/users/profile with the provided UpdateProfileRequest and returning the updated UserProfileDto. It first ensures the caller is authenticated, then performs the HTTP request, validates the response, and deserializes the JSON payload into a UserProfileDto (or null if the response has no body). + +## Remarks + +This method centralizes the concerns around making authenticated HTTP calls: enforcing authentication, handling HTTP success semantics, and deserializing the server payload into a typed DTO. It provides a clean, reusable surface for updating the user's profile without leaking HTTP details to callers. By wrapping EnsureSuccessAsync and JSON deserialization, it promotes consistent error handling and data shape assumptions across the client. + +## Notes + +- The return value may be null if the response body is empty; callers should guard against null. +- EnsureSuccessAsync will throw on non-success HTTP statuses, so error handling is centralized here. +- Deserialization uses `ReadFromJsonAsync`; ensure the response content is JSON matching UserProfileDto. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/AsyncRunner.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/AsyncRunner.cs.md new file mode 100644 index 0000000..247ed4a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/AsyncRunner.cs.md @@ -0,0 +1,18 @@ +# AsyncRunner + +> **File:** `src/EchoHub.Client/Services/AsyncRunner.cs` +> **Kind:** class + +```csharp +public static class AsyncRunner +``` + + +Eliminates repeated Task.Run/try/catch/app.Invoke(ShowError) boilerplate by consolidating the common pattern of running background work and surfacing errors to the UI. It runs the provided async work on a background thread and routes any exceptions to the UI thread for user notification. + +## Remarks +AsyncRunner encapsulates a cross-cutting concern: performing asynchronous work without blocking the UI and centralizing error reporting. It uses Task.Run to execute work off the calling thread and app.Invoke to marshal the error surface back to the UI. When an exception occurs, it logs the failure with the provided context (logContext if supplied, otherwise errorPrefix) and shows a UI message using showError prefixed by errorPrefix. Because Run is fire-and-forget (it returns void), callers should not rely on it for completion or exception propagation; choose a different pattern if you need to observe results. + +## Notes +- This method is fire-and-forget; exceptions are caught and surfaced but not propagated to the caller. +- The UI update and logging rely on the provided IApplication and showError delegate; ensure they are safe to call from a background thread; app.Invoke is used to marshal to the UI thread. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md new file mode 100644 index 0000000..2724154 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md @@ -0,0 +1,24 @@ +# AudioPlaybackService + +> **File:** `src/EchoHub.Client/Services/AudioPlaybackService.cs` +> **Kind:** class + +```csharp +public class AudioPlaybackService +``` + + +AudioPlaybackService is a thread-safe wrapper around an underlying audio player that exposes asynchronous playback controls and a finished event surface. Use it when you need serialized access to play, pause, resume, or stop audio and a consistent event interface without managing locks and state machines yourself. + +## Remarks +To prevent concurrent calls from interfering with playback state, the class serializes all operations using a SemaphoreSlim. When PlayAsync is invoked while something is already playing, it stops the current track before starting the new file; PauseAsync, ResumeAsync, and StopAsync perform their actions only when appropriate states are detected. The PlaybackFinished event is forwarded from the internal player, so callers can react to completion without depending on the concrete implementation of the _player. Exceptions raised by the underlying player are caught and logged with a warning, ensuring playback issues do not crash the application. + +## Example +```csharp +// Example usage +var audio = new AudioPlaybackService(); +await audio.PlayAsync("path/to/file.mp3"); +``` + +## Notes +- This wrapper serializes calls to avoid race conditions; however, it is not cancellation-aware. If you need to cancel an in-flight operation, extend the class with cancellation support or a dedicated cancellation mechanism. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/AvatarHelper.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/AvatarHelper.cs.md new file mode 100644 index 0000000..1ef8c6b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/AvatarHelper.cs.md @@ -0,0 +1,33 @@ +# AvatarHelper + +> **File:** `src/EchoHub.Client/Services/AvatarHelper.cs` +> **Kind:** class + +```csharp +internal static class AvatarHelper +``` + + +AvatarHelper centralizes the shared logic for uploading avatars by accepting either a local file path or an HTTP(S) URL, resolving the input to a stream, and uploading it via ApiClient.UploadAvatarAsync. It returns the ASCII art response from the server, providing a straightforward way to obtain the server-side representation of the uploaded avatar without duplicating local-file or network-handling code. + +## Remarks + +By supporting both local and remote sources behind a single UploadAsync entry point, AvatarHelper hides the mechanics of data retrieval and stream management from call sites and ensures consistent disposal of the stream. The actual upload is delegated to ApiClient, keeping concerns separated between data acquisition and server interaction. The class is internal, reinforcing its role as a reusable utility within the client layer rather than a public API. + +The method propagates errors from file access, HTTP fetch, or the server upload to the caller, which is appropriate for a small, focused helper that prioritizes simplicity over internal retries or resilience policies. + +## Example + +```csharp +// Example usage within the same assembly +var client = new ApiClient("https://api.example.org"); +string? artFromFile = await AvatarHelper.UploadAsync(client, @"C:\avatars\user.png"); +string? artFromUrl = await AvatarHelper.UploadAsync(client, "https://example.org/avatars/user.png"); +``` + +## Notes + +- Creating a new HttpClient per invocation can lead to socket exhaustion in high-throughput scenarios; consider reusing a shared HttpClient instance or using HttpClientFactory in production code. +- If the local path does not exist, a FileNotFoundException is thrown. +- When targeting a URL, if the URL's file name is missing or lacks an extension, the code defaults to using avatar.png as the upload file name. +- Exceptions from the HTTP request or the server upload propagate to the caller; there is no retry logic within this helper. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md new file mode 100644 index 0000000..144ef1c --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md @@ -0,0 +1,35 @@ +# ClientEncryptionService + +> **File:** `src/EchoHub.Client/Services/ClientEncryptionService.cs` +> **Kind:** class + +```csharp +public sealed class ClientEncryptionService : IMessageEncryptionService +``` + + +ClientEncryptionService provides client-side encryption for messages by applying AES-256-GCM using a key supplied by the server. It mirrors the server’s encryption format so messages are encrypted end-to-end between client and server. When no key has been set, Encrypt is a no-op and returns the plaintext to preserve compatibility with unauthenticated flows; once initialized, Encrypt produces a prefixed, base64-encoded payload containing the nonce and ciphertext+tag, and Decrypt reverses this process. If decryption fails due to a missing or mismatched key or corrupted data, a sentinel message is returned to indicate the failure and prompt re-authentication to refresh the key. + +## Remarks +This abstraction isolates cryptography behind a single, testable service that can be swapped or disabled without changing business logic. It enforces a clear security boundary: encryption only happens after a server-provided key is loaded, reducing the risk of leaking plaintext. The pre-key pass-through behavior preserves compatibility with existing flows during login or in environments where the key has not yet been fetched. + +## Example +```csharp +// Example: encrypt and decrypt with a server-provided key +var client = new ClientEncryptionService(); + +// Create a 32-byte key for demonstration (replace with real server-provided key) +var keyBytes = new byte[32]; +var base64Key = Convert.ToBase64String(keyBytes); +client.SetKey(base64Key); + +string plaintext = "Secret message"; +string encrypted = client.Encrypt(plaintext); +string decrypted = client.Decrypt(encrypted); +// decrypted should equal plaintext +``` + +## Notes +- Encrypt and Decrypt only work after a 32-byte key has been provided via SetKey; otherwise Encrypt returns plaintext and Decrypt returns content unchanged. +- If the encrypted content is tampered with, the key is wrong, or the payload is malformed, Decrypt returns the special placeholder: "[encrypted message — decryption failed, try re-logging to fetch the latest key]". +- The key is held in memory and is not rotated automatically; ensure proper key management and re-fetch after key rotation on the server. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md new file mode 100644 index 0000000..9290f01 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md @@ -0,0 +1,32 @@ +# ClipboardFiles + +> **File:** `src/EchoHub.Client/Services/ClipboardFiles.cs` +> **Kind:** class + +```csharp +public static class ClipboardFiles +``` + + +ClipboardFiles reads file paths from the clipboard when the clipboard contains a file-list (such as after copying files in Explorer/Finder). Use TryGetFiles to retrieve those paths so you can attach copied files directly without pasting textual paths; this works on Windows and Linux, while macOS and other platforms do not expose a file-list clipboard. + +## Remarks +ClipboardFiles encapsulates platform differences behind a single API. It isolates Windows-specific CF_HDROP handling and Linux's text/uri-list retrieval, performing path existence checks and filtering out non-file entries to return a clean list of existing paths. It returns true only when at least one file is found; otherwise false, letting callers gracefully fall back to other input methods. + +## Example +```csharp +if (ClipboardFiles.TryGetFiles(out var files)) +{ + Console.WriteLine($"Clipboard contains {files.Count} file(s): {string.Join(", ", files)}"); +} +else +{ + Console.WriteLine("Clipboard does not contain a file-list or contains only non-existent paths."); +} +``` + +## Notes +- Returns only existing files; non-existent or inaccessible paths are ignored. +- Windows implementation relies on CF_HDROP with a brief retry loop to tolerate clipboard contention. +- Linux implementation uses wl-paste or xclip (one must be available for success). +- macOS and other platforms do not provide file-list clipboard support. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardImage.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardImage.cs.md new file mode 100644 index 0000000..87b24d4 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/ClipboardImage.cs.md @@ -0,0 +1,29 @@ +# ClipboardImage + +> **File:** `src/EchoHub.Client/Services/ClipboardImage.cs` +> **Kind:** class + +```csharp +public static class ClipboardImage +``` + + +Reads raw image data from the OS clipboard and returns PNG-encoded bytes suitable for saving, embedding, or transmitting. Use this when you need a single, consistent PNG representation of whatever image the user has copied (browser-copied PNGs, screenshots, editor bitmaps) so callers don't need per-OS or per-format handling. + +## Remarks +This class normalizes multiple clipboard image formats into PNG. It prefers native clipboard PNG formats when available (preserving transparency) and falls back to platform clipboard bitmaps (CF_DIB on Windows) by wrapping the DIB bytes in a minimal BMP file header and decoding/re-encoding them as PNG. TryGetPng routes to OS-specific helpers and catches/logs errors, returning false on failure rather than throwing. + +## Example +```csharp +// Save whatever image is on the clipboard to a file named clipboard.png +if (ClipboardImage.TryGetPng(out var png)) +{ + System.IO.File.WriteAllBytes("clipboard.png", png); +} +``` + +## Notes +- DibToPng returns null for malformed or undecodable DIB input; TryGetPng propagates that as a failure (false). +- The implementation prefers registered PNG clipboard formats to preserve alpha; CF_DIB bitmaps are re-encoded and may lose or change metadata. +- Re-encoding a bitmap to PNG allocates memory and does CPU work; callers should avoid doing this in a tight loop. +- TryGetPng checks the platform (Windows/Linux/macOS) and will return false on unsupported platforms; failures are logged rather than thrown. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/ConnectionManager.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/ConnectionManager.cs.md new file mode 100644 index 0000000..f8ba1b7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/ConnectionManager.cs.md @@ -0,0 +1,63 @@ +# ConnectionManager.cs + +> **Source:** `src/EchoHub.Client/Services/ConnectionManager.cs` + +## Contents + +- [ConnectionManager](#connectionmanager) +- [ConnectResult](#connectresult) + +--- + +## ConnectionManager +> **File:** `src/EchoHub.Client/Services/ConnectionManager.cs` +> **Kind:** class + +```csharp +internal sealed class ConnectionManager : IAsyncDisposable +``` + + +Manages the full lifecycle of a live chat connection: authenticating with the server, establishing end-to-end encryption keys, creating and wiring the SignalR (EchoHub) connection, tracking joined channels, and exposing a thin event surface that the UI (AppOrchestrator) can subscribe to. Use this when you want a single, high-level component to own connection state and SignalR event forwarding instead of manipulating ApiClient and EchoHubConnection directly. + +## Remarks +This class centralizes the responsibilities that would otherwise be scattered across UI code: authentication and token rotation, attempting to fetch and apply the E2E encryption key, instantiating and wiring an EchoHubConnection, and keeping track of which channels have been joined. It forwards SignalR events as simple .NET events so the UI layer can react without needing to know SignalR details. ConnectionManager also implements IAsyncDisposable so callers can cleanly tear down both the EchoHubConnection and the underlying ApiClient. + +## Notes +- ConnectionManager may raise forwarded events from background threads (SignalR callbacks). UI handlers should marshal to the UI thread if required by the UI framework. +- ConnectAsync reports progress via the onStatus callback and will throw on authentication failure; callers are expected to handle expired saved sessions or retry logic. +- Failure to fetch the encryption key is treated as non-fatal: the manager logs a warning and proceeds without message encryption. +- Dispose of the manager (DisposeAsync) when the app shuts down to ensure the hub connection and ApiClient are cleaned up. + +--- + +## ConnectResult +> **File:** `src/EchoHub.Client/Services/ConnectionManager.cs` +> **Kind:** record + +```csharp +internal record ConnectResult( + LoginResponse Login, + List Channels, + Dictionary> Histories) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Login` | [`LoginResponse`](../../EchoHub.Core/DTOs/AuthDtos.cs.md) | — | +| `Channels` | `List` | — | +| `Histories` | `Dictionary>` | — | + + +Represents the outcome of a successful connection, returned to AppOrchestrator for UI updates. It bundles the authentication result, the current set of channels, and the initial histories for every auto-joined channel (keyed by channel name and including the default channel). As an immutable record, it serves as a single, self-contained snapshot that the UI can bootstrap from after a connect. + +## Remarks +This object centralizes the data needed to render the initial connected state, decoupling the connection logic from the UI orchestration. By passing a single ConnectResult, the AppOrchestrator can immediately populate channel lists and histories without issuing additional fetches, promoting a clean separation between connection handling and presentation concerns. + +## Notes +- ConnectResult is immutable; to reflect changes (e.g., new messages or channels), construct and pass a new instance rather than mutating the existing one. +- Histories is a dictionary keyed by channel name that contains the initial per-channel histories; ensure channel names in the dictionary align with the Channels list to avoid inconsistencies. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md new file mode 100644 index 0000000..305846a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md @@ -0,0 +1,158 @@ +# EchoHubConnection.cs + +> **Source:** `src/EchoHub.Client/Services/EchoHubConnection.cs` + +## Contents + +- [ChannelPasswordRequiredException](#channelpasswordrequiredexception) +- [EchoHubConnection](#echohubconnection) +- [RoomLockedException](#roomlockedexception) +- [JoinOutcome](#joinoutcome) + +--- + +## ChannelPasswordRequiredException +> **File:** `src/EchoHub.Client/Services/EchoHubConnection.cs` +> **Kind:** class + +```csharp +public sealed class ChannelPasswordRequiredException : Exception +``` + + +Thrown when joining a channel fails because a password is required or the provided password is incorrect. The UI catches this to prompt the user for credentials and retry the join, using ChannelName to provide channel context. + +## Remarks +ChannelPasswordRequiredException provides a precise signal for a password-related join failure. By carrying the ChannelName, it enables the UI to present a meaningful prompt and retry flow without inspecting lower-level errors. This focused exception helps keep join logic cohesive and testable by separating password-entry concerns from generic failure handling. + +## Example +```csharp +try +{ + // Code that attempts to join a channel and may throw ChannelPasswordRequiredException +} +catch (ChannelPasswordRequiredException ex) +{ + Console.WriteLine($"Password is required to join channel '{ex.ChannelName}'."); + // Prompt the user for a password and retry the join using the provided channel name +} +``` + +## Notes +- Be mindful that ChannelName may be null if constructed with null; guard accordingly before displaying it to users. + +--- + +## EchoHubConnection +> **File:** `src/EchoHub.Client/Services/EchoHubConnection.cs` +> **Kind:** class + +```csharp +public sealed class EchoHubConnection : IAsyncDisposable +``` + + +A SignalR-backed client wrapper that manages a HubConnection to the Echo chat hub, integrates client-side encryption/room-key lookup, and exposes simple event callbacks for incoming messages, presence and channel events. Reach for EchoHubConnection when you need a higher-level, event-driven connection to the server that automatically handles authentication token provisioning and reconnect behavior while decrypting incoming payloads for the UI. + +## Remarks +EchoHubConnection encapsulates the SignalR HubConnection lifecycle and maps server callbacks onto plain .NET events (e.g. OnMessageReceived, OnUserJoined, OnChannelUpdated). It supplies the HubConnectionBuilder with an AccessTokenProvider using the provided ApiClient so calls are authenticated, and it wires automatic-reconnect handlers that surface connection state changes via OnConnectionStateChanged and OnReconnected. Incoming MessageDto instances are passed through the client-side encryption pipeline (ClientEncryptionService and RoomKeyStore) so the UI sees decrypted content or a locked placeholder when a room key is not available. + +## Example +```csharp +// Subscribe to events and inspect connection state +var echo = new EchoHubConnection(serverUrl, apiClient, encryptionService, roomKeyStore); + +echo.OnMessageReceived += message => +{ + // MessageDto is provided by the library; content may be the LockedMessagePlaceholder + Console.WriteLine($"Message received in {message.ChannelName}: {message.Content}"); +}; + +if (echo.IsConnected) +{ + Console.WriteLine("Currently connected to the chat hub."); +} + +// Remember to dispose when finished +await echo.DisposeAsync(); +``` + +## Notes +- Events are raised directly from SignalR callbacks; handlers may not run on a UI thread — marshal to the UI thread if required. +- Encrypted messages for channels without a stored key are replaced with LockedMessagePlaceholder; supply the channel passphrase (through the app's key store flow) to see decrypted content. +- Call DisposeAsync to release the underlying HubConnection and related resources to avoid background network activity. + +--- + +## RoomLockedException +> **File:** `src/EchoHub.Client/Services/EchoHubConnection.cs` +> **Kind:** class + +```csharp +public sealed class RoomLockedException : Exception +``` + + +Thrown to signal a security-sensitive condition when attempting to send a message into an end-to-end encrypted channel whose room key isn't cached. The operation is blocked to prevent sending plaintext; catching this exception lets the UI prompt for the channel's passphrase and unlock the room before retrying. + +## Remarks + +RoomLockedException acts as a clear boundary between encryption policy and transport logic. By exposing the ChannelName, callers can present a channel-scoped unlock prompt without parsing the error text, and the sealed Exception type communicates a concrete, expected failure mode that downstream code can handle distinctly from generic errors. + +## Example + +```csharp +try +{ + // Simulated scenario: an attempt to send into a locked E2E channel + throw new RoomLockedException("Lobby"); +} +catch (RoomLockedException ex) +{ + // Use the information to drive the unlock UX + Console.WriteLine(ex.Message); + Console.WriteLine($"Unlock channel: {ex.ChannelName} by entering its passphrase."); +} +``` + +## Notes + +- Do not swallow this as a generic error; catch RoomLockedException to trigger the unlock UX and use ex.ChannelName to identify the affected channel. The displayed message is user-facing and not localized. + +--- + +## JoinOutcome +> **File:** `src/EchoHub.Client/Services/EchoHubConnection.cs` +> **Kind:** record + +```csharp +public sealed record JoinOutcome(List History, string? EncryptionSalt, string? WrappedRoomKey) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `History` | `List` | — | +| `EncryptionSalt` | `string?` | — | +| `WrappedRoomKey` | `string?` | — | + + +JoinOutcome is a sealed record that represents the result of joining a channel: it includes the decrypted history (History) and, for end-to-end encrypted channels, the key envelope necessary to unlock the room's content key (WrappedRoomKey). EncryptionSalt is the salt used to derive the encryption key when applicable. This type is typically produced by the join logic and consumed by the UI to render messages and initialize decryption if needed. + +## Remarks +This abstraction centralizes the outcome of a join into a single, immutable value that downstream components can rely on. The History is always present (even if empty), while EncryptionSalt and WrappedRoomKey are nullable to reflect that some rooms are not end-to-end encrypted or that keys may not be provisioned yet. By grouping history and encryption metadata together, the join logic can separate concerns: rendering chat versus handling cryptographic setup. + +## Example + +```csharp +using System.Collections.Generic; + +List history = new List(); +var joinResult = new JoinOutcome(history, null, null); +``` + +## Notes +- EncryptionSalt and WrappedRoomKey can be null; callers should verify non-null before attempting decryption-related steps. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md new file mode 100644 index 0000000..e91ab80 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/NativeFolderPicker.cs.md @@ -0,0 +1,96 @@ +# NativeFolderPicker.cs + +> **Source:** `src/EchoHub.Client/Services/NativeFolderPicker.cs` + +## Contents + +- [NativeFolderPicker](#nativefolderpicker) +- [FolderPickResult](#folderpickresult) +- [PickerOutcome](#pickeroutcome) + +--- + +## NativeFolderPicker +> **File:** `src/EchoHub.Client/Services/NativeFolderPicker.cs` +> **Kind:** class + +```csharp +public static class NativeFolderPicker +``` + + +Opens the OS-native folder picker by shelling out to the host OS, keeping the TUI free of GUI toolkit dependencies. It supports Windows, macOS, and Linux by delegating to platform-specific helpers and returns a FolderPickResult that communicates whether a folder was chosen, the dialog was cancelled, or the native picker is unavailable so the caller can fall back to a configured path. + +## Remarks + +NativeFolderPicker centralizes cross-platform behavior for obtaining a folder path without pulling in a GUI toolkit. It hides OS differences behind a single entry point, PickFolderAsync, and exposes a uniform result type (FolderPickResult with a PickerOutcome) that callers can inspect to either proceed with the chosen path or fall back to defaults. Failures are caught and logged, ensuring graceful degradation rather than exceptions propagating to the UI. + +## Notes +- Linux will not attempt a graphical picker if no graphical session is detected (DISPLAY or WAYLAND_DISPLAY are missing); in that case, the method returns Unavailable. +- On Windows, the initial directory is sanitized (apostrophes are doubled) to safely embed the path in the PowerShell script, and PowerShell is invoked via an encoded command to avoid quoting issues. +- If the platform-specific helper cannot be started, the code falls back to returning Unavailable instead of throwing, allowing callers to implement their own fallback strategy. + +--- + +## FolderPickResult +> **File:** `src/EchoHub.Client/Services/NativeFolderPicker.cs` +> **Kind:** record + +```csharp +public sealed record FolderPickResult(PickerOutcome Outcome, string? Path) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Outcome` | `PickerOutcome` | — | +| `Path` | `string?` | — | + + +FolderPickResult is an immutable data carrier that represents the outcome of a native folder-picking operation and, when successful, the path of the selected folder. + +## Remarks +Because FolderPickResult is a record, it benefits from value-based equality and straightforward pattern matching when consumed by calling code. The Path member is nullable to reflect that a folder may not be selected; always check the Outcome before using Path. This abstraction decouples application logic from platform-specific picker implementations, promoting testability and cross-platform compatibility. + +## Example +```csharp +var result = new FolderPickResult(PickerOutcome.Success, @"C:\Projects"); +if (result.Outcome == PickerOutcome.Success && result.Path is not null) +{ + Console.WriteLine(result.Path); +} +``` + +## Notes +- Path may be null when Outcome indicates cancellation or failure; always verify Outcome before accessing Path. + +--- + +## PickerOutcome +> **File:** `src/EchoHub.Client/Services/NativeFolderPicker.cs` +> **Kind:** enum + +```csharp +public enum PickerOutcome +{ + Chosen, + + Cancelled, + + Unavailable, +} +``` + + +PickerOutcome encodes the result of attempting to display a native folder picker. It defines three mutually exclusive states: Chosen (the user picked a folder and FolderPickResult.Path is set), Cancelled (the native dialog ran but no selection was made), and Unavailable (no native picker is available on the current machine). + +Use this enum to drive post-pick logic without scattering platform checks or error handling across call sites. + +## Remarks +This enum serves as a lightweight sum type for the outcome of a folder-picking operation. It centralizes decision points and pairs with FolderPickResult to obtain the actual path when Chosen is returned. Consumers can implement a fallback flow for Unavailable and provide a smooth user experience when Cancelled. + +## Notes +- Unavailable is not an error; it indicates the absence of a native picker and warrants a fallback strategy (e.g., a non-native picker or manual path entry). + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/NotificationSoundService.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/NotificationSoundService.cs.md new file mode 100644 index 0000000..2c5e31b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/NotificationSoundService.cs.md @@ -0,0 +1,19 @@ +# NotificationSoundService + +> **File:** `src/EchoHub.Client/Services/NotificationSoundService.cs` +> **Kind:** class + +```csharp +public class NotificationSoundService +``` + + +NotificationSoundService centralizes the playback of the notification sound. It resolves the sound file from configuration (if specified and found) or falls back to a bundled default, then plays the sound at a configurable volume when requested. The service exposes SetEnabled and SetVolume for simple runtime tuning, and PlayAsync for normal operation or PlayTestAsync for QA scenarios where playback should occur regardless of the Enabled flag. Internally it uses a semaphore to serialize concurrent playback, and a 10-second timeout to prevent a stuck caller if the sound does not finish. + +## Remarks +The class isolates all concerns around audio playback: path resolution, volume handling, concurrency, and fault tolerance. By hiding these details behind a single service, higher-level notification logic can simply request a sound without worrying about file presence, logging, or synchronization. The design anticipates environments where a sound file might be missing or playback might stall, and it ensures resources are released and the system remains responsive. + +## Notes +- Silent fallback if a sound file cannot be found; production environments should ensure the asset exists if audible alerts are required. +- The PlaybackFinished event and the 10-second timeout guard the system against hangs; the lock may be released before the sound finishes, which means subsequent playback requests can start while a prior one is still playing. +- PlayAsync respects the Enabled flag, while PlayTestAsync allows testing the sound regardless of Enabled. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md new file mode 100644 index 0000000..8e26356 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md @@ -0,0 +1,46 @@ +# OutgoingAttachment + +> **File:** `src/EchoHub.Client/Services/OutgoingAttachment.cs` +> **Kind:** record + +```csharp +public sealed record OutgoingAttachment( + Stream Stream, + string FileName, + string? DeclaredKind = null, + string? EncryptedPreview = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Stream` | `Stream` | — | +| `FileName` | `string` | — | +| `DeclaredKind` | `string?` | `null` | +| `EncryptedPreview` | `string?` | `null` | + + +OutgoingAttachment is a transport object that represents a single file to upload as part of a message. It bundles the data Stream and FileName, and optionally carries DeclaredKind and EncryptedPreview for encrypted channels, while non-encrypted channels typically set only Stream and FileName. + +## Remarks +OutgoingAttachment serves as a compact, immutable data carrier that travels through the sending pipeline. As a record, it uses value-based equality which helps comparisons and deduplication when attachments are tracked across requests. It also clarifies ownership: the record does not manage the lifetime of the underlying Stream; callers are responsible for opening and disposing streams as appropriate. + +## Example +```csharp +using System.IO; + +// Normal channel usage: only Stream and FileName are provided +var data = new byte[] { 0x01, 0x02, 0x03 }; +var stream = new MemoryStream(data); +var attachment = new OutgoingAttachment(stream, "data.bin"); + +// End-to-end encrypted channel usage: DeclaredKind and EncryptedPreview are set +var ciphertext = new MemoryStream(new byte[] { 0xAA, 0xBB, 0xCC }); +var asciiPreview = @"ASCII_ART_PREVIEW"; +var encryptedAttachment = new OutgoingAttachment(ciphertext, "image.png", "image", asciiPreview); +``` + +## Notes +- The lifetime of the underlying Stream is not managed by OutgoingAttachment; the caller must ensure the stream is disposed when appropriate. +- DeclaredKind and EncryptedPreview are intended for encrypted channels; in normal channels these values are typically null. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/PathSetup.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/PathSetup.cs.md new file mode 100644 index 0000000..1127023 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/PathSetup.cs.md @@ -0,0 +1,24 @@ +# PathSetup + +> **File:** `src/EchoHub.Client/Services/PathSetup.cs` +> **Kind:** class + +```csharp +public static class PathSetup +``` + + +PathSetup is a cross-platform helper that ensures the application's directory is present on the system PATH, enabling commands like echohub to be run from any terminal session without specifying the full path. EnsureOnPath checks for the directory and, if missing, updates PATH in a platform-appropriate way: Windows updates the user PATH; Unix-like systems append an export line to common shell profile files. + +## Remarks +By centralizing PATH manipulation, this abstraction reduces code duplication and the risk of divergent PATH states across platforms. It uses a lightweight, best-effort approach and logs outcomes to aid diagnostics when PATH updates fail or are skipped. The addition is clearly marked by a PathMarker to avoid duplicating lines in shell profiles. + +## Example +```csharp +PathSetup.EnsureOnPath(); +``` + +## Notes +- The method swallows exceptions and logs at debug level, so callers should not rely on exceptions to signal failure. +- Unix updates affect the user's shell environment; new terminal sessions are typically required to observe changes. +- Windows updates are done at the per-user level; system-wide PATH is not modified. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md new file mode 100644 index 0000000..6dc4b0b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md @@ -0,0 +1,30 @@ +# RoomKeyProtector + +> **File:** `src/EchoHub.Client/Services/RoomKeyProtector.cs` +> **Kind:** class + +```csharp +public sealed class RoomKeyProtector +``` + + +Encrypts cached room content keys at rest so the client config never holds them as plain base64. Windows uses DPAPI (current-user scope, format prefix "dp1:"). On other platforms the keys are AES-GCM encrypted with a per-user master key file stored next to the config with 0600 permissions (prefix "k1:") — without an OS keychain that is file-permission-level protection, not zero-knowledge: anyone who can read both the config and the key file can recover the room keys. Values with no recognized prefix are legacy plain-base64 keys from older clients; they load once and are re-encrypted. The room passphrase itself is never stored in any form. + +The RoomKeyProtector class provides a single API surface to protect and unprotect per-user room keys across platforms. The Protect method returns a string suitable for storage in the config, automatically selecting the appropriate protection mechanism for the current OS (DPAPI on Windows, file-based AES-GCM on others). TryUnprotect decodes a stored value back into a room key, reporting whether the value was a legacy (unencrypted) entry and whether the decryption succeeded. The implementation intentionally hides platform differences behind a consistent interface, so callers can persist and reload keys without worrying about the underlying cryptosystem. + +The constructor accepts a directory that holds the master key file and an optional flag to override the OS-provided protection path (useful for tests). The key file path is derived from the directory by appending the fixed file name roomkeys.key. Key loading is guarded by a small lock and the master key is cached after the first read. The Protect path prefixes the output to indicate how the data is protected ("dp1:" or "k1:"). + +The class ensures the room passphrase itself is never persisted, and it gracefully tolerates missing or unreadable key material by returning false from TryUnprotect (leaving the caller to prompt the user for action). + +````csharp +// Typical usage +var protector = new RoomKeyProtector("/config"); +byte[] roomKey = new byte[32]; // obtain from a secure source +string stored = protector.Protect(roomKey); + +if (protector.TryUnprotect(stored, out var recovered, out bool wasLegacy)) +{ + // recovered contains the room key if the value was decryptable + // wasLegacy is true only if the input was a legacy base64 key without a prefix +} +```` diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md new file mode 100644 index 0000000..187f28d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md @@ -0,0 +1,43 @@ +# RoomKeyStore + +> **File:** `src/EchoHub.Client/Services/RoomKeyStore.cs` +> **Kind:** class + +```csharp +public sealed class RoomKeyStore +``` + + +Holds and manages end-to-end encrypted room keys for a single client instance: it keeps a decrypted, in-memory cache for the active session and a per-server persisted, encrypted copy so users do not have to re-enter passphrases each launch. Use RoomKeyStore when you need a thread-safe local store that provides room keys to the runtime and ensures keys are encrypted at rest via RoomKeyProtector. + +## Remarks +RoomKeyStore links transient runtime state with the client's persisted configuration. It binds to a server (LoadForServer), loads that server's saved ChannelKeys (unprotecting them with RoomKeyProtector), and exposes methods to read, add, replace, or remove keys while persisting changes back to the SavedServer entry. It also records which channels are known to be encrypted so callers can avoid emitting plaintext into rooms without a cached key. The class performs a one-way upgrade of legacy unprotected entries to the protected format when possible and logs unreadable entries rather than failing. + +## Example +```csharp +var store = new RoomKeyStore(); +store.LoadForServer("https://chat.example.com"); + +// Generate and store a new room key for a channel +byte[] newKey = RoomCrypto.GenerateRoomKey(); +store.StoreKey("#team-room", newKey); + +// Retrieve a key for sending encrypted messages +if (store.TryGetKey("#team-room", out var key)) +{ + // Use `key` with RoomCrypto API to encrypt message content +} + +// Accept an encrypted envelope and store the unwrapped key only if the KEK opens it +string wrapped = "..."; // envelope string received +byte[] kek = /* key-encryption-key */ new byte[RoomCrypto.KeySizeBytes]; +if (store.TryStoreFromEnvelope("#other-room", wrapped, kek)) +{ + // successfully unwrapped and cached +} +``` + +## Notes +- Call LoadForServer(serverUrl) before persisting or retrieving server-scoped keys; the store clears and reinitializes its cache when bound to a server. +- Legacy (plain/base64) saved entries are upgraded to the protector-backed format when possible; entries that cannot be unprotected are ignored and logged. +- The class uses an internal lock for basic thread-safety of the in-memory cache; avoid holding returned keys while performing long synchronous work that might race with store mutations. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md new file mode 100644 index 0000000..ba601d4 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md @@ -0,0 +1,86 @@ +# UpdateBackupService.cs + +> **Source:** `src/EchoHub.Client/Services/UpdateBackupService.cs` + +## Contents + +- [BackupJsonContext](#backupjsoncontext) +- [UpdateBackupService](#updatebackupservice) +- [BackupInfo](#backupinfo) + +--- + +## BackupJsonContext +> **File:** `src/EchoHub.Client/Services/UpdateBackupService.cs` +> **Kind:** class + +```csharp +[System.Text.Json.Serialization.JsonSerializable(typeof(BackupInfo))] +internal partial class BackupJsonContext : System.Text.Json.Serialization.JsonSerializerContext +``` + + +BackupJsonContext is an internal partial class that provides the source-generated JSON serialization metadata for the BackupInfo type. It plugs into System.Text.Json’s source generator, enabling reflection-free serialization of BackupInfo when you configure a JsonSerializerOptions with this context. + +## Remarks +This symbol acts as the concrete carrier of serialization metadata for BackupInfo within the JSON pipeline of EchoHub’s client. By centralizing the generated type information in a single context, it keeps serialization concerns isolated from business logic and allows the type to evolve without scattering attributes across multiple call sites. The pattern here—one generated context per data contract—supports predictable performance improvements while preserving a clean, minimal public surface. + +## Notes +- The symbol is internal; it is intended for use within the containing assembly, not by external callers. +- The class is generated and partial; do not edit it by hand, as changes will be overwritten by the source generator. +- If you modify the BackupInfo shape, you must re-run code generation to keep the context in sync with the data contract. + +--- + +## UpdateBackupService +> **File:** `src/EchoHub.Client/Services/UpdateBackupService.cs` +> **Kind:** class + +```csharp +public static class UpdateBackupService +``` + + +Manages pre-update backups for the auto-updater and provides rollback support by snapshotting the running application prior to an update. Backups are stored under ~/.echohub/update-backup/ as backup.zip with a companion backup-info.json that records the version, application directory, and UTC timestamp. Use CreateBackup before applying an update; verify presence with BackupExists and inspect metadata with GetBackupInfo to drive a rollback if needed. The IsPostUpdate flag signals that a backup from a recent update exists, allowing startup logic to react accordingly. + +--- + +## BackupInfo +> **File:** `src/EchoHub.Client/Services/UpdateBackupService.cs` +> **Kind:** record + +```csharp +public record BackupInfo( + string Version, + string AppDirectory, + DateTimeOffset CreatedAt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Version` | `string` | — | +| `AppDirectory` | `string` | — | +| `CreatedAt` | `DateTimeOffset` | — | + + +BackupInfo is a lightweight, value-like record that encapsulates metadata about a created backup. It carries the backup Version, the AppDirectory that was backed up, and the CreatedAt timestamp, enabling complete backup metadata to be passed around as a single unit. + +## Remarks +BackupInfo, being a record with positional parameters, is immutable and benefits from value-based equality. This makes it ideal as a canonical data carrier when the UpdateBackupService reports or persists backup information, or when UI/logging layers need to compare or display backup entries. + +## Example +```csharp +var backup = new BackupInfo( + Version: "1.2.3", + AppDirectory: "/opt/MyApp", + CreatedAt: DateTimeOffset.UtcNow +); +``` + +## Notes +- Records provide structural equality; two instances with the same Version, AppDirectory, and CreatedAt compare as equal. +- CreatedAt uses DateTimeOffset to preserve offset information; prefer UTC (DateTimeOffset.UtcNow) when constructing backups to avoid timezone ambiguities. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateChecker.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateChecker.cs.md new file mode 100644 index 0000000..a36a8d0 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/UpdateChecker.cs.md @@ -0,0 +1,36 @@ +# UpdateChecker + +> **File:** `src/EchoHub.Client/Services/UpdateChecker.cs` +> **Kind:** class + +```csharp +public sealed class UpdateChecker : IDisposable +``` + + +Checks for application updates in the background, presents a TUI confirmation dialog when a new version is available, and defers the actual download/extract/restart work until after the terminal UI has been shut down. Use this class when the host application runs a Terminal.Gui main loop and needs a safe way to offer in-place updates without deadlocking the console or performing heavy I/O while the TUI still owns the terminal. + +## Remarks +This class encapsulates polling and manual update checks via an internal Updater instance and marshals user interaction back onto the provided IApplication main loop using _app.Invoke. When the user confirms an update, UpdateChecker does not perform the network/download work immediately; instead it sets PendingUpdate to an awaitable callback (ApplyUpdateAsync), stores the selected version, and requests the TUI to stop. The host is expected to call PendingUpdate after the main loop exits and the console has been restored so the update process can safely run headless (the Updater's update flow may restart the process and call Environment.Exit). + +## Example +```csharp +// During application startup +var updateChecker = new UpdateChecker(app); +updateChecker.Start(); // starts periodic checks in RELEASE builds + +// ... run Terminal.Gui main loop ... + +// After the main loop exits and the console is restored, run any pending update +if (updateChecker.PendingUpdate != null) +{ + await updateChecker.PendingUpdate(); +} +``` + +## Notes +- Start only activates the background poller in RELEASE builds (the Start method is no-op in non-RELEASE builds). +- PendingUpdate is deliberately set to a Task-returning delegate and intended to be invoked by the host after the TUI has fully stopped; running it while the TUI still owns the console can deadlock the restart flow. +- ApplyUpdateAsync attempts to create a pre-update backup with UpdateBackupService.CreateBackup; backup creation failures are logged and the update continues. +- ApplyUpdateAsync sets Console.OutputEncoding = UTF8 but swallows exceptions (useful when stdout is redirected or non-interactive). +- CurrentVersion reads the assembly version and falls back to "0.0.0" if unavailable. diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Services/UserSession.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Services/UserSession.cs.md new file mode 100644 index 0000000..980a9de --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Services/UserSession.cs.md @@ -0,0 +1,19 @@ +# UserSession + +> **File:** `src/EchoHub.Client/Services/UserSession.cs` +> **Kind:** class + +```csharp +internal sealed class UserSession +``` + + +Stores the current user's session state on the client, including username, online status, and an optional status message. Use this type as a lightweight, centralized container when you need to read or mutate the ephemeral session data for the active user, and call Reset to return all fields to their defaults (empty username, Online status, and no status message). + +## Remarks +Internally sealed and non-public, this class keeps the session representation stable within the client service layer and prevents inheritance. It relies on the UserStatus enum from the core models to express the user's current state consistently across the application. + +## Notes +- Not thread-safe by default; coordinate concurrent access if used from multiple threads. +- Reset mutates state in place; if you require preserving data, capture it before calling Reset. +- StatusMessage is nullable; null indicates that no message is provided. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Themes/Theme.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Themes/Theme.cs.md new file mode 100644 index 0000000..136525e --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Themes/Theme.cs.md @@ -0,0 +1,52 @@ +# Theme.cs + +> **Source:** `src/EchoHub.Client/Themes/Theme.cs` + +## Contents + +- [Theme](#theme) +- [ThemeColors](#themecolors) + +--- + +## Theme +> **File:** `src/EchoHub.Client/Themes/Theme.cs` +> **Kind:** class + +```csharp +public class Theme +``` + + +Theme is the central container for theming the EchoHub client UI. It holds a Name and four color palettes (Base, Menu, Dialog, Status) used across the main window and its chrome; plus an optional Border palette that can override only the frame borders while the rest remains tied to Base. If Border is null, the border colors fall back to the Base palette, letting themes tone borders down independently from text to achieve effects like glassy translucency. The palettes default to new ThemeColors instances, so a Theme is immediately usable and developers only configure what they need. Border supports hex literals like "#6E6E6E" and named colors, enabling quick tweaks without changing the rest of the palette. + +## Remarks +Theme isolates brand identity and UI chrome from layout logic, enabling themes to be swapped at runtime or per user preference. The per-area color groups—Base, Menu, Dialog, and Status—provide visual consistency while allowing targeted overrides; Border offers a focused knob for edge treatment without touching text colors. This composition reduces duplication: a single Theme can render across the chrome, with optional Border overrides to achieve distinctive looks without rewriting color logic. + +## Notes +- Name is marked as required; always provide a non-empty value during initialization. +- Border is nullable. If you don't set it, the UI uses Base colors for borders; set Border when you want to tint borders independently. +- Hex codes and named colors: ensure strings you assign are valid color tokens understood by the theming system to avoid fallback or misrendering. + +--- + +## ThemeColors +> **File:** `src/EchoHub.Client/Themes/Theme.cs` +> **Kind:** class + +```csharp +public class ThemeColors +``` + + +ThemeColors is a small data container that holds the color choices used by the UI theme. It exposes four properties—Foreground, Background, FocusForeground, and FocusBackground—each with a sensible default (White on Black for normal state, and White on Blue for focused state). This class centralizes theming values so UI components can render consistently and themes can be swapped by supplying a ThemeColors instance rather than scattering color literals throughout rendering code. + +## Remarks +- It acts as a cohesive value object for theming, separating concerns between color data and rendering logic. +- It enables swapping themes by replacing one ThemeColors instance rather than modifying rendering code. +- It is mutable, allowing runtime theme adjustments; if a ThemeColors instance is shared across threads, consider synchronization to avoid race conditions. + +## Notes +- If you mutate and share ThemeColors across threads, you may encounter race conditions; prefer per-thread copies or proper synchronization when updating values. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/Themes/ThemeManager.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/Themes/ThemeManager.cs.md new file mode 100644 index 0000000..bc369b1 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/Themes/ThemeManager.cs.md @@ -0,0 +1,601 @@ +# ThemeManager.cs + +> **Source:** `src/EchoHub.Client/Themes/ThemeManager.cs` + +## Contents + +- [ThemeManager](#thememanager) + - [ApplyTheme](#applytheme) + - [BuildColorScheme](#buildcolorscheme) + - [GetAvailableThemes](#getavailablethemes) + - [GetTheme](#gettheme) + - [ParseColor](#parsecolor) + - [SaveTheme](#savetheme) + - [ClassicTheme](#classictheme) + - [DefaultTheme](#defaulttheme) + - [DraculaTheme](#draculatheme) + - [HackerTheme](#hackertheme) + - [HighContrastTheme](#highcontrasttheme) + - [JsonOptions](#jsonoptions) + - [LightTheme](#lighttheme) + - [MonokaiTheme](#monokaitheme) + - [OceanTheme](#oceantheme) + - [SolarizedTheme](#solarizedtheme) + - [ThemeDir](#themedir) + - [TransparentLightTheme](#transparentlighttheme) + - [TransparentTheme](#transparenttheme) +- [BuiltInThemes](#builtinthemes) +- [GruvboxTheme](#gruvboxtheme) +- [NordTheme](#nordtheme) +- [RosePineTheme](#rosepinetheme) + +--- + +## ThemeManager +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** class + +```csharp +public static class ThemeManager +``` + + +ThemeManager_overview provides a centralized, static API for discovering, loading, applying, and persisting themes used by the EchoHub client UI. Call GetAvailableThemes to enumerate built-in and user-defined themes, GetTheme to fetch a theme by name, and ApplyTheme to switch the UI to a chosen theme. + +## Remarks +Conceptually, ThemeManager acts as the bridge between Theme data (the Theme class) and the runtime UI. It maintains a curated list of built-in themes and exposes logic to load additional themes from a user directory, surfacing them for selection without requiring changes to the runtime code. In addition, BuildColorScheme ensures color assignments for text areas align with the active theme, pinning Editable/ReadOnly roles so that transparent themes render correctly and inputs stay legible. This centralizes theming concerns and keeps theme-related behavior in one place, simplifying maintenance and experimentation with new themes. + +## Example +```csharp +var available = ThemeManager.GetAvailableThemes(); +var theme = ThemeManager.GetTheme("Default"); +ThemeManager.ApplyTheme(theme); +``` + +## Notes +- SaveTheme is best-effort and silently swallows failures; verify persistence if you rely on saved themes. +- GetAvailableThemes falls back to built-in themes when the theme directory cannot be read. +- ParseColor expects valid color identifiers defined by the theming system; supply colors that exist in the library or your Theme colors. + +--- + +### ApplyTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +public static void ApplyTheme(Theme theme) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `theme` | [`Theme`](Theme.cs.md) | — | + +**Returns:** `void` + + +Applies a Theme by registering color schemes for the core UI areas with SchemeManager. This single call maps the Theme's Base, Menu, Dialog, and optional Border sections to named schemes so the rest of the UI can render consistently according to the active theme. + +## Remarks +This method acts as a bridge between the Theme model and SchemeManager's scheme registry. It delegates color construction to BuildColorScheme for each region, ensuring Base, Menu, and Dialog colors stay in sync. The Border scheme uses theme.Border when provided, otherwise it falls back to the Base palette to preserve a coherent frame. By applying all four schemes in one place, ApplyTheme reduces the risk of components diverging toward inconsistent styling. + +## Notes +- Repeatedly calling ApplyTheme overwrites the previously registered schemes, so batch theme updates if you want to avoid intermediate flashes. +- The Border palette falls back to Base when Border is not provided; ensure the Base colors reflect the desired frame in that case. + +## Dependencies +- SchemeManager + +--- + +### BuildColorScheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +private static Scheme BuildColorScheme(ThemeColors colors) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `colors` | [`ThemeColors`](Theme.cs.md) | — | + +**Returns:** `Scheme` + + +BuildColorScheme converts ThemeColors into a Terminal.Gui Scheme by deriving two Attributes—Normal from Foreground and Background and Focus from FocusForeground and FocusBackground—then applying them to the Scheme's state properties (Normal, Focus, HotNormal, HotFocus, Disabled). It also pins Editable and ReadOnly to Normal to ensure input controls render against the theme background, avoiding opaque boxes in transparent themes. + +## Remarks +This method centralizes the theme-to-scheme translation, decoupling ThemeColors from the Scheme used by the UI. By deriving Normal and Focus once and reusing them for all relevant roles, and by tying Editable/ReadOnly to Normal, it guarantees consistent visual behavior for standard controls and editable regions across themes. The method being private static signals that it's an internal detail of the theming pipeline used by ThemeManager to assemble the active color scheme. + +## Notes +- If ThemeColors contain invalid color strings, ParseColor may throw; ensure colors are validated before calling BuildColorScheme. +- The returned Scheme is a new object each time; repeated calls may impact allocations. +- Editable and ReadOnly are deliberately mapped to Normal; if you need distinct input backgrounds, adjust the mapping accordingly. + +--- + +### GetAvailableThemes +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +public static List GetAvailableThemes() +``` + +**Returns:** `List` + + +The GetAvailableThemes method returns a list of Theme objects by starting with the built-in themes and augmenting that set with user-defined themes discovered in the ThemeDir directory. It iterates over all *.json files, deserializes each one into a Theme using JsonSerializer with the configured JsonOptions, and, if the resulting theme has a non-empty Name and does not duplicate an existing theme (case-insensitive comparison on Name), appends it to the collection. If ThemeDir does not exist or any IO or JSON parsing error occurs, the method gracefully falls back to returning only the built-in themes. + +## Remarks +This function encapsulates the theme-loading strategy: built-in themes establish the default baseline, while external JSON themes extend the collection without mutating the originals. It operates defensively, skipping malformed files and continuing execution in the face of read errors, which yields a predictable return value even under partial failure. De-duplication is driven by Theme.Name using a case-insensitive comparison to prevent accidental duplicates when names differ only by case. + +## Notes +- It swallows IO and JSON parsing exceptions, so failures to read or parse individual files do not propagate to the caller. +- Built-in themes take precedence: a user-defined theme with a Name that matches an existing built-in theme is ignored, ensuring stable baseline behavior. + +--- + +### GetTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +public static Theme GetTheme(string name) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `name` | `string` | — | + +**Returns:** [`Theme`](Theme.cs.md) + + +Resolves a Theme by name by searching the collection returned by GetAvailableThemes and returning the first match found when the theme name equals the provided name, ignoring case. It is the right choice when you need to map a user-provided theme name (from UI, config, or input) to a Theme object, with a fallback to DefaultTheme if no match exists. + +## Remarks +By centralizing theme resolution in this single method, callers can map a string (for example, user input) to a Theme object without duplicating comparison logic or null checks. The use of ordinal string comparison ensures consistent, culture-invariant matching across locales. The method relies on GetAvailableThemes providing a valid collection and on DefaultTheme representing a concrete theme. + +## Notes +- If GetAvailableThemes returns null, the call to Find will throw a NullReferenceException. +- The search is linear in the size of the themes collection; for large catalogs consider caching or indexing to improve lookup performance. +- Name comparison uses OrdinalIgnoreCase; if you need culture-aware matching, replace with a culture-aware comparison or normalize names elsewhere. + +--- + +### ParseColor +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +private static Color ParseColor(string colorName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `colorName` | `string` | — | + +**Returns:** `Color` + + +Parses a color name into a Color using Color.TryParse. If parsing succeeds, it returns the resulting Color (or White if the parsed color is null). If parsing fails, it returns Color.White. Use this helper when theme code needs to translate a color name string into a Color value, ensuring a valid color is always returned instead of propagating nulls. + +## Remarks + +Centralizes color-name parsing, reducing duplication and guarding ThemeManager's rendering paths against invalid color inputs. The fallback to White makes the UI predictable but at the risk of hiding misconfigurations; consider logging when a fallback occurs to aid debugging. + +## Notes + +- Invalid or unknown color names yield Color.White without throwing. +- No exception is thrown; a deterministic Color is always returned. + +--- + +### SaveTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** method + +```csharp +public static void SaveTheme(Theme theme) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `theme` | [`Theme`](Theme.cs.md) | — | + +**Returns:** `void` + + +Persists a Theme by serializing it to JSON and writing it to a file named after the theme under ThemeDir. Use SaveTheme to persist a user-selected theme so it can be reloaded on startup; it's a best-effort operation that silently swallows failures, so callers shouldn't rely on it for critical persistence. + +## Remarks +This abstraction encapsulates the simple idea of theme persistence: ensure the target directory exists, determine a file path from the Theme.Name, serialize to JSON using JsonOptions, and write the content. It uses Theme.Name as the file name, so two themes with the same name will overwrite each other; an enhanced naming strategy or unique IDs could help. Failures are swallowed, so any persistence failure is invisible to the caller; consider adding logging or a higher-level retry if persistence must be durable. The method depends on JsonOptions for serialization behavior and relies on the standard IO primitives (Directory, Path, JsonSerializer, File). + +## Notes +- The catch-all block hides errors; callers cannot detect save failures. +- Using Theme.Name directly as a file name may introduce invalid characters or path traversal risks if Name isn't sanitized. +- Existing theme JSON will be overwritten without backup or versioning. + +--- + +### ClassicTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme ClassicTheme = new() +``` + + +ClassicTheme is a private static readonly Theme that encapsulates the classic visual styling used by the UI. It defines the 'Classic' theme name and assigns color palettes for four UI zones — Base, Menu, Dialog, and Status — so the theming system can render consistent foregrounds, backgrounds, and focus states across the application. + +## Remarks +Why this abstraction exists: centralizes the classic color palette in one place, avoiding repetitive literals across components. It also stabilizes the look by exposing a single instance that the ThemeManager can switch to internally to apply the classic aesthetic. In short, ClassicTheme acts as the canonical, versioned styling bundle for the traditional UI appearance. + +## Notes +- Potential mutability: If Theme or ThemeColors expose public setters, the colors may be mutated after initialization. Consumers should rely on a stable palette or the code should enforce immutability. +- Accessibility considerations: The palette uses high-contrast combinations (e.g., White foreground on DarkGray/Blue). If your accessibility requirements change, adjust this Theme instance or provide alternative themes. + +--- + +### DefaultTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme DefaultTheme = new() +``` + + +Defines the canonical default theme used by the UI components within the ThemeManager. This private static readonly field initializes a single Theme instance named 'Default' with color settings for each UI region (Base, Menu, Dialog, Status). The nested ThemeColors specify the foreground, background, and focus colors, establishing a consistent look-and-feel across the application unless overridden by other theme configurations. Because it is static and readonly, the instance is created once at type initialization and cannot be reassigned, ensuring all consumers relying on the default palette see the same values. + +## Remarks +Centralizes the default visual styling to ensure a single, shared baseline across the UI. It prevents scattering color choices across components and makes it easier to reason about the default appearance of the application. If a different baseline is needed for testing or special scenarios, a separate Theme can be created and applied through the ThemeManager, rather than modifying this field. + +## Notes +- The field is private; external code cannot access or mutate DefaultTheme directly. +- Even though the reference is readonly, the nested ThemeColors objects may be mutable if their properties are settable; treat the default palette as effectively immutable at runtime unless you deliberately mutate its contents within ThemeManager. +- The color values are provided as names (e.g., 'Gray', 'White'); ensure the rendering layer recognizes these tokens to avoid unexpected visuals. + +--- + +### DraculaTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme DraculaTheme = new() +``` + + +DraculaTheme is a private static readonly Theme field that represents the Dracula-inspired color palette used by the theme system. It defines distinct color specifications for four UI surfaces—Base, Menu, Dialog, and Status—each with a foreground color, a background color, and explicit focus colors to ensure consistent, high-contrast visuals across the application. This field is intended for internal use by ThemeManager to apply a cohesive dark theme; external code should not rely on it directly. + +## Remarks +Having a single DraculaTheme instance centralizes the Dracula look, preventing drift in color choices across components. By keeping it private and readonly, ThemeManager can switch to Dracula without duplicating palettes, while still allowing other themes to be composed similarly. The explicit focus colors help maintain clear keyboard-navigation states even on dark surfaces. + +## Notes +- Private visibility prevents external code from referencing DraculaTheme directly. +- It is static readonly and assigned once; runtime mutation is not expected. +- Token names like BrightMagenta and Magenta map to concrete colors in the rendering layer; ensure the color system supports these tokens for accurate rendering. + +--- + +### HackerTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme HackerTheme = new() +``` + + +HackerTheme is a private, static, readonly Theme instance that encodes the color palette used by the Hacker appearance within the UI. It defines the colors for the Base, Menu, Dialog, and Status areas, providing a single source of truth that ThemeManager can apply to render a consistent dark-themed interface. + +## Remarks +This field centralizes the Hacker color scheme, ensuring consistent foreground/background pairs across all UI regions and their focus states. Because HackerTheme is private to ThemeManager, external code cannot reference or mutate it directly; changes to the palette must go through ThemeManager's public API or future extensions. The nested ThemeColors per region make it easy to tweak the palette in one place when refining the visual language. + +## Notes +- The static readonly modifier means HackerTheme is initialized once and its reference cannot be reassigned, but the contained ThemeColors objects may still be mutable depending on their type. +- External code should not rely on HackerTheme having a public accessor; to reuse the palette publicly, ThemeManager should expose a proper API rather than exposing internal details. + +--- + +### HighContrastTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme HighContrastTheme = new() +``` + + +Defines a private static readonly Theme instance named HighContrastTheme that captures a high-contrast color scheme used by the theming subsystem. It specifies color configurations for the Base, Menu, Dialog, and Status surfaces to maximize legibility and clearly indicate focus against a dark background. + +## Remarks +HighContrastTheme centralizes the high-contrast styling to avoid scattering color values throughout the codebase. The ThemeManager can switch to this theme to satisfy accessibility requirements without exposing public API changes. + +## Notes +- The nested ThemeColors objects may be mutable; mutating them would undermine the high-contrast guarantee. Treat HighContrastTheme as an internal constant and avoid altering its color properties at runtime. + +--- + +### JsonOptions +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly JsonSerializerOptions JsonOptions = new() +``` + + +JsonOptions is a privately scoped, preconfigured JsonSerializerOptions instance used by ThemeManager to serialize JSON with the project’s conventions. It enables indented output and camelCase property naming, ensuring that any JSON emitted while theming is both human-readable and aligned with the API surface. + +## Remarks +By using a private static readonly field, ThemeManager avoids repeated allocations and guarantees a single shared configuration for its JSON serialization within the class. Note that JsonSerializerOptions is mutable; while the field reference cannot be reassigned, changing its properties at runtime can lead to subtle, cross-call side effects. Treat this instance as effectively immutable after initialization. + +## Example +```csharp +// Within ThemeManager +var data = new { Theme = "Dark", Version = 1 }; +string json = JsonSerializer.Serialize(data, JsonOptions); +``` + +## Notes +- Mutating JsonOptions at runtime can cause inconsistent formatting across serialized outputs; prefer making changes only during initialization. +- This field is internal to ThemeManager; if different parts of the application require alternative formatting, construct and pass their own JsonSerializerOptions instead of reusing JsonOptions. + +--- + +### LightTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme LightTheme = new() +``` + + +LightTheme is a predefined Theme instance that encodes the light-mode color configuration used by the UI. It centralizes the color values for the base surface and for Menu, Dialog, and Status regions so the theming system can apply a consistent light appearance without constructing a new Theme object each time. + +## Remarks + +By consolidating the light palette in a single static object, LightTheme ensures visual consistency across components that render base surfaces, menus, dialogs, and status bars. It serves as a canonical reference for the light aesthetic within the theming subsystem, enabling ThemeManager to switch to a known, shared configuration. Because the field is private static readonly, it should be treated as a shared, effectively immutable source at runtime; mutating its nested color objects could lead to inconsistent visuals. + +## Notes + +- It is a static shared instance; mutating its nested ThemeColors at runtime would have global effects; treat as read-only after initialization. + +--- + +### MonokaiTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme MonokaiTheme = new() +``` + + +MonokaiTheme is a private static readonly field that defines the Monokai color palette used by the theme system. It holds a Theme named "Monokai" composed of four color blocks (Base, Menu, Dialog, Status), each described by ThemeColors with specific foreground, background, and focus colors. This single, shared instance provides a consistent color vocabulary for the UI, allowing ThemeManager and related rendering code to apply the Monokai look uniformly without scattering literals across the codebase. Because the field is private, its usage is internal to the class that declares it. + +## Remarks +MonokaiTheme serves as a centralized, reusable color configuration for the Monokai look. By grouping color sets into Base, Menu, Dialog, and Status, it expresses distinct chrome regions while keeping a single source of truth for the palette. This abstraction makes it straightforward for ThemeManager and UI components to consistently apply the Monokai styling. + +## Notes +- The Theme and ThemeColors instances are mutable; altering their properties would mutate the shared theme at runtime and affect all consumers within the process. +- External code cannot replace MonokaiTheme, but internal code could adjust its nested properties unless immutability is enforced; consider making Theme/ThemeColors immutable if a fixed theme is intended. + +--- + +### OceanTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme OceanTheme = new() +``` + + +OceanTheme is a predefined ocean-inspired color palette represented as a Theme instance. It groups color configurations for four UI regions—Base, Menu, Dialog, and Status—each with foreground, background, and focus colors, enabling a cohesive look across the application. The field is private static readonly, so the same Theme object is created once and reused, preventing accidental reassignment while keeping internal mutability restricted to the defining class. + +## Remarks +Centralizes theming decisions and reduces duplication by providing a single, cohesive palette that UI components can rely on. OceanTheme expresses a clear design intent (an ocean-like aesthetic) and is intended to be selected by theming logic to apply a consistent appearance across Base, Menu, Dialog, and Status surfaces. The per-area ThemeColors allow distinct focus and interaction states while preserving a unified visual language. + +## Notes +- Access is private to the ThemeManager class, preventing external code from directly reusing or mutating OceanTheme. +- The reference is readonly, so the field cannot be reassigned; internal mutability would require explicit code within the defining class. +- The color tokens (e.g., BrightCyan, DarkBlue, White, DarkCyan) must be valid tokens within the project’s visual system for the palette to render correctly. + +--- + +### SolarizedTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme SolarizedTheme = new() +``` + + +SolarizedTheme is a private static readonly Theme instance that encapsulates the Solarized color palette used by the UI. It defines color roles for four UI surfaces—Base, Menu, Dialog, and Status—specifying both normal foreground/background and focused-state foreground/background colors. The field is initialized once at type-load time and is then reused wherever a Solarized look is required, providing a single source of truth for this color scheme and preventing runtime mutations. + +## Remarks +This symbol acts as a centralized, immutable specification of the Solarized look. By housing the color tokens in a single Theme, ThemeManager can consistently apply the same palette across menus, dialogs, and status lines without scattering literals throughout the code. The private static readonly pattern communicates intent: SolarizedTheme is a predefined, non-changing theme available to internal consumers of ThemeManager, not something that should be modified at runtime. + +## Notes +- The theme uses string color tokens (e.g., "Cyan", "BrightYellow"), which are resolved by the theming subsystem to actual display colors. +- Because the field is readonly, any changes require rebuilding the Theme instance; runtime mutation is prevented. +- The four ThemeColors sections (Base, Menu, Dialog, Status) each specify both normal and focused color states to support focus indication. + +--- + +### ThemeDir +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly string ThemeDir = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".echohub", "themes") +``` + + +ThemeDir is a private, static readonly string that resolves to the user-specific themes directory by combining the current user’s profile folder with .echohub/themes. It provides a single, OS-agnostic path for ThemeManager to load and save theme files, avoiding scattered string literals. + +## Remarks +Centralizing the location of theme assets decouples theme storage from OS conventions and hard-coded paths, making future relocations or tests simpler. The static readonly nature guarantees a consistent path across all ThemeManager operations, computed at type initialization. If the target directory doesn't exist at runtime, higher-level startup or initialization code should ensure it is created before any read/write of themes. + +## Notes +- Directory existence: ensure creation to avoid IO errors when reading or writing themes. +- Hidden folder nuance: .echohub will be hidden on Unix-like systems; consider how this affects user visibility or directory listings in certain UI scenarios. + +--- + +### TransparentLightTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme TransparentLightTheme = new() +``` + + +Represents a canonical light-theme configuration used by the UI to render surfaces on light backgrounds. TransparentLightTheme is a private static readonly Theme instance that bundles a complete color palette for Base, Menu, Dialog, Status, and Border, enabling a consistent light appearance across the UI when a light or transparent background is in use. The defined colors map foregrounds, backgrounds, and focus states to maintain readability and clear focus cues (Blue for focused elements). + +## Remarks +By centralizing the light-theme palette in a single internal Theme instance, this symbol reduces drift between UI surfaces and makes it straightforward to derive alternate light variants from a single baseline. Its private visibility signals it's an internal default rather than a public customization point; external code should define and consume their own Theme instances instead of mutating this one. + +## Notes +- Border foreground uses #8F8F8F for softer borders on light terminals. +- Background values set to 'None' indicate transparency or reliance on the parent/background, aligning with a transparent-light aesthetic. + +--- + +### TransparentTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme TransparentTheme = new() +``` + + +Defines a single, shared Theme instance named TransparentTheme that implements a glassy, semi-transparent UI aesthetic. Declared private static readonly, it is initialized once and reused by the ThemeManager to apply a cohesive translucent look across Base, Menu, Dialog, Status, and Border color groups (most backgrounds are None to preserve translucency, with White foreground and BrightCyan focus colors; Dialog uses DarkGray to retain legibility; borders use muted grays to complete the glassy look). + +## Remarks +This symbol centralizes the glassy appearance so all UI surfaces adopting transparency share a single color model. Being private ensures the theme is an internal implementation detail of ThemeManager and not part of the public theming surface. If a project needs a similar variant publicly, it should be created as a separate, publicly accessible theme instance rather than exposing this private field. The pattern reduces drift between components and simplifies maintenance of the transparent aesthetic. + +## Notes +- The field is readonly, but its nested color objects are not guaranteed immutable; mutating their properties at runtime would alter the shared theme for all users. Treat the instance as immutable after initialization to preserve consistency. + +--- + +## BuiltInThemes +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly List BuiltInThemes = + [ + DefaultTheme, + TransparentTheme, + TransparentLightTheme, + ClassicTheme, + LightTheme, + HackerTheme, + SolarizedTheme, + DraculaTheme, + MonokaiTheme, + NordTheme, + GruvboxTheme, + OceanTheme, + HighContrastTheme, + RosePineTheme + ] +``` + + +BuiltInThemes is a private static readonly collection that enumerates the Theme instances shipped as built-in themes. It provides a stable, canonical set of themes (including DefaultTheme, TransparentTheme, TransparentLightTheme, ClassicTheme, LightTheme, HackerTheme, SolarizedTheme, DraculaTheme, MonokaiTheme, NordTheme, GruvboxTheme, OceanTheme, HighContrastTheme, and RosePineTheme) that ThemeManager can iterate over to present theme options and initialize theming state. Because the field is private and readonly, external code cannot modify this collection at runtime; it is intended as an internal baseline that ensures consistent theming behavior across the application. + +## Remarks +Centralizes the shipped themes into a single place, guaranteeing a consistent ordering and a single source of truth for what counts as built-in. This reduces duplication and makes it easier to adjust defaults or add new themes by updating the initializer, rather than sprinkling Theme references throughout the code. Because it's private, consumers must rely on public Theme-related APIs or ThemeManager flows to query or apply themes. + +## Notes +- The list is constructed from static Theme instances defined elsewhere (the DefaultTheme, TransparentTheme, etc.). +- As a private, readonly field, it cannot be replaced or mutated at runtime; new themes must be added via source changes. +- If you need to expose or customize the built-in set, provide a public API rather than accessing this field directly. + +--- + +## GruvboxTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme GruvboxTheme = new() +``` + + +GruvboxTheme is a private, static, readonly Theme instance that encodes the Gruvbox color palette for the EchoHub client UI. It defines colors for core regions—Base, Menu, Dialog, and Status—each with a Foreground, Background, FocusForeground, and FocusBackground value. This single object acts as the canonical Gruvbox styling source consumed by the theming subsystem to render a consistent look across the application. Because the field is private and readonly, external callers should rely on ThemeManager's public mechanisms to obtain themed resources rather than mutate or reference this field directly. + +## Remarks + +By centralizing the palette in one immutable object, GruvboxTheme reduces drift between UI regions and simplifies theming changes. The per-region color groups reflect a clean separation of concerns: Base handles the main chrome, Menu for navigation, Dialog for modal surfaces, and Status for status indicators; the consistent focus colors ensure accessible emphasis when keyboard navigation occurs. This pattern makes it straightforward to swap themes by replacing the underlying Theme instance without scattering color literals throughout the code. + +## Notes + +- The readonly reference prevents re-assignment, but if Theme or ThemeColors are mutable, their values can still be mutated at runtime. +- This field is private; there is no direct public API here—consumers should obtain theme data via ThemeManager's public surface rather than accessing GruvboxTheme directly. + +--- + +## NordTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme NordTheme = new() +``` + + +NordTheme defines the internal, immutable Nord color palette used by ThemeManager to style the UI. It is a single Theme instance configured with per-surface color mappings (Base, Menu, Dialog, Status) so the Nord look is applied consistently without duplicating color definitions throughout the code. + +## Remarks +This symbol centralizes the Nord appearance, providing a single source of truth for foreground/background and focus colors across different UI surfaces. It is private to ThemeManager, which means external code should interact with the public theming API rather than reference or mutate this instance. The approach reduces drift between surfaces and makes it easy to switch themes by swapping higher-level theme providers rather than tweaking individual components. + +## Notes +- Be aware that the readonly modifier applies to the field reference; nested ThemeColors instances may still be mutable if their properties expose setters. If true immutability is required, consider making Theme and ThemeColors immutable or returning defensive copies. + + +--- + +## RosePineTheme +> **File:** `src/EchoHub.Client/Themes/ThemeManager.cs` +> **Kind:** field + +```csharp +private static readonly Theme RosePineTheme = new() +``` + + +RosePineTheme is a private static readonly Theme instance that encapsulates the RosePine color palette used by the UI. It defines per-area color configurations for Base, Menu, Dialog, and Status, pairing foreground and background colors with their focused variants. This centralized definition provides a single source of truth for the RosePine look and is consumed by the theming subsystem rather than by external code, helping maintain a cohesive visual style across the application. + +## Remarks +Centralizes theme-related color data to ensure visual consistency and to simplify theme swapping or adjustment. Keeping the field private hides implementation details from consumers and enforces usage through the theming infrastructure, reducing the risk of accidental divergence in color usage. + +## Notes +- The field is private; external code cannot reference RosePineTheme directly. +- The field is readonly in reference, but its internal properties may be mutable depending on ThemeColors' mutability; if ThemeColors exposes setters, the palette could be modified after initialization. +- Static initialization order and potential side effects: If ThemeManager relies on RosePineTheme during application startup, ensure initialization order is correct. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatColors.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatColors.cs.md new file mode 100644 index 0000000..f7b343a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatColors.cs.md @@ -0,0 +1,19 @@ +# ChatColors + +> **File:** `src/EchoHub.Client/UI/Chat/ChatColors.cs` +> **Kind:** class + +```csharp +public static partial class ChatColors +``` + + +Shared color attributes and a small parsing helper for chat rendering. Use this class when rendering chat UI elements (timestamps, system messages, mentions, channel references, embeds, attachments, etc.) so all parts of the UI use a consistent set of Attribute values. Call SplitMentions when you need to break a message into colored segments so mentions (@user) and channel references (#channel) can be rendered with their accent colors while non-special text uses a supplied default. + +## Remarks +ChatColors centralizes the visual styling for chat components and includes a utility to split text into ChatSegment pieces that carry color information. SplitMentions performs a two-pass parse: first it finds @mentions (avoiding emails by requiring no preceding word character) and marks them with MentionTextAttr; then it examines the remaining, non-mention segments to find #channel references (the regex requires at least one letter to avoid matching hex colors or numeric issue references) and marks those with ChannelRefAttr. All Attribute instances are readonly and intended as shared, immutable style tokens that renderers can reuse. + +## Notes +- The mention regex uses a negative lookbehind (? **Source:** `src/EchoHub.Client/UI/Chat/ChatLine.cs` + +## Contents + +- [ChatLine](#chatline) +- [AttachmentActionSpan](#attachmentactionspan) +- [AttachmentAction](#attachmentaction) + +--- + +## ChatLine +> **File:** `src/EchoHub.Client/UI/Chat/ChatLine.cs` +> **Kind:** class + +```csharp +public partial class ChatLine +``` + + +Represents a single rendered chat line made up of colored ChatSegment pieces and associated display metadata. Use ChatLine when preparing or manipulating a line for rendering in the chat view (layout, wrapping, attachment actions, separators, mention/highlight state) rather than working with raw strings or segments directly. + +## Remarks +ChatLine is the view-level unit for a message or a rule separator: it aggregates ChatSegment instances (text + color), stores metadata such as MessageId, sender, attachment info and clickable action spans, and exposes logic to break the line into multiple display lines that fit a viewport width. It centralizes presentation concerns (continuation indentation, colored continuation prefixes, non-wrapping rule lines, and unread-marker behavior) so the chat rendering layer can ask a ChatLine to produce the wrapped pieces it needs rather than implementing wrapping and metadata handling itself. + +## Example +```csharp +// Construct from plain text +var line = new ChatLine("Hello, world!"); +// Optional metadata +line.MessageId = Guid.NewGuid(); +line.SenderUsername = "alice"; + +// Wrap to a viewport width of 40 columns, with a 4-space continuation indent +var wrapped = line.Wrap(40, continuationIndent: 4); + +// Construct from explicit segments (preserves per-segment color attributes) +var segments = new List +{ + new ChatSegment("[alice] ", ChatColors.RailAttr), + new ChatSegment("This is a message", null) +}; +var coloredLine = new ChatLine(segments); +``` + +## Notes +- RuleLabel makes the line a separator rule; such lines are not word-wrapped and are regenerated to the viewport width by the view. +- If ContinuationPrefixSegments is set, it overrides ContinuationIndent: continuation lines use the prefix segments' column width instead of plain-space indentation. +- ActionSpans (when present) are column positions relative to the unwrapped line; only the first wrapped line preserves those spans — subsequent wrapped continuation lines do not. +- Wrapping respects grapheme clusters and column widths (uses GetGraphemes and GetColumns), so wide characters and combining sequences are handled when measuring width. If width <= 0 or the line already fits, Wrap returns the original line in a single-element list. + +--- + +## AttachmentActionSpan +> **File:** `src/EchoHub.Client/UI/Chat/ChatLine.cs` +> **Kind:** record + +```csharp +public readonly record struct AttachmentActionSpan(int StartCol, int EndCol, AttachmentAction Action) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `StartCol` | `int` | — | +| `EndCol` | `int` | — | +| `Action` | `AttachmentAction` | — | + + +It encodes an inclusive horizontal span on a chat line that maps to an AttachmentAction when clicked. This readonly record struct pairs StartCol and EndCol (both inclusive) with an Action to designate a specific clickable region that triggers an attachment operation. + +## Remarks +Because it's a value type with immutable fields, AttachmentActionSpan is cheap to copy and compare, which helps with hit-testing and rendering across frames. It expresses the intent of interactive regions alongside their coordinates and associated action, keeping the UI layer decoupled from how actions are executed. This symbol complements other line-rendering data structures that describe clickable spans, enabling straightforward collection, filtering, and application during rendering. + +## Notes +- EndCol is inclusive; ensure range checks treat EndCol as inclusive to avoid off-by-one errors. +- Overlapping spans may require careful resolution logic at render or hit-test time to determine which action should fire. + +--- + +## AttachmentAction +> **File:** `src/EchoHub.Client/UI/Chat/ChatLine.cs` +> **Kind:** enum + +```csharp +public enum AttachmentAction +{ + OpenImage, + SaveImage, +} +``` + + +An enum that represents the action a click on an attachment line can trigger in the chat UI. It lets the click handler distinguish between opening the image for viewing and saving the image to disk, promoting explicit, testable logic rather than ad-hoc behavior. + +## Remarks +By codifying the possible outcomes as an enum, AttachmentAction defines a clear contract for how attachment clicks should be handled. It decouples the UI event from the concrete actions, making it easy to extend with new options (for example, ShareImage) without changing call sites. This abstraction supports consistent behavior across different chat lines and simplifies testing by allowing mocks or verifications based on the enum value. + +## Example +```csharp +AttachmentAction action = /* determined by UI context */; +switch (action) +{ + case AttachmentAction.OpenImage: + // Open the image in a viewer + break; + case AttachmentAction.SaveImage: + // Persist the image to disk + break; +} +``` + +## Notes +- If you later add actions to the enum, remember to handle them in all switch expressions and tests. +- Prefer explicit enum-based logic over string-based representations to avoid misinterpretation. +- Ensure UI-to-action mappings are consistent across chat lines to prevent user confusion. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatListSource.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatListSource.cs.md new file mode 100644 index 0000000..dbc48ae --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatListSource.cs.md @@ -0,0 +1,19 @@ +# ChatListSource + +> **File:** `src/EchoHub.Client/UI/Chat/ChatListSource.cs` +> **Kind:** class + +```csharp +public class ChatListSource : IListDataSource +``` + + +A list-backed data source for chat messages that implements IListDataSource and performs grapheme-aware rendering with per-segment coloring, mention-background highlighting, and a focus-based full-row highlight. Use this when supplying chat messages to a ListView-like control that expects the data source to manage items, raise collection-change notifications, and draw each row with segment-level attributes and correct column clipping. + +## Remarks +ChatListSource maintains an internal `List`, tracks the longest item via MaxItemLength, and raises a CollectionChanged (Reset) event whenever the collection is modified unless SuspendCollectionChangedEvent is set. Its Render implementation is grapheme-aware (uses GraphemeHelper.GetGraphemes and each grapheme's column width) and applies attributes per ChatSegment: a Focus attribute (when the row is selected and the list has focus) or the segment's color with fallbacks for missing backgrounds. If a ChatLine.IsMention is true the renderer uses ChatColors.MentionHighlightAttr.Background to override segment backgrounds and to fill the remainder of the row. + +## Notes +- GetLine returns null for out-of-range indices; callers should validate the index first. +- IsMarked/SetMark are intentionally no-ops in this implementation and Dispose is a no-op — no per-item mark state or unmanaged cleanup is performed. +- MaxItemLength is updated only when lines are added/inserted; mutating a ChatLine.TextLength after insertion will not update MaxItemLength automatically. Use SuspendCollectionChangedEvent to batch updates and suppress the Reset event during bulk changes. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md new file mode 100644 index 0000000..d3d35b7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatMessageManager.cs.md @@ -0,0 +1,1215 @@ +# ChatMessageManager.cs + +> **Source:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` + +## Contents + +- [ChatMessageManager](#chatmessagemanager) + - [CurrentChannel](#currentchannel) + - [CurrentUser](#currentuser) + - [LastReadIds](#lastreadids) + - [MentionChannels](#mentionchannels) + - [ActionHeaderSegments](#actionheadersegments) + - [AddMessage](#addmessage) + - [AddStatusMessage](#addstatusmessage) + - [AddSystemMessage](#addsystemmessage) + - [AttachmentActionLine](#attachmentactionline) + - [ClearAll](#clearall) + - [ClearChannelMessages](#clearchannelmessages) + - [ClearUnread](#clearunread) + - [DateRule](#daterule) + - [DateRuleLabel](#daterulelabel) + - [FormatEmbed](#formatembed) + - [FormatFileSize](#formatfilesize) + - [FormatMessage](#formatmessage) + - [FormatTime](#formattime) + - [FormatWithDateRules](#formatwithdaterules) + - [GetMessages](#getmessages) + - [GetUnreadCount](#getunreadcount) + - [GetUnreadCounts](#getunreadcounts) + - [HeaderSegments](#headersegments) + - [ImageActionLine](#imageactionline) + - [LoadHistory](#loadhistory) + - [MarkRead](#markread) + - [PadNick](#padnick) + - [PrependHistory](#prependhistory) + - [RailPrefix](#railprefix) + - [RemoveMessage](#removemessage) + - [RemoveUnreadMarker](#removeunreadmarker) + - [ReplyQuoteLine](#replyquoteline) + - [SeedUnreadFromHistory](#seedunreadfromhistory) + - [SetChatWidth](#setchatwidth) + - [SetCurrentUser](#setcurrentuser) + - [SystemHeaderSegments](#systemheadersegments) + - [UnreadMarkerRule](#unreadmarkerrule) + - [WordWrap](#wordwrap) + - [NickColWidth](#nickcolwidth) +- [ContentIndentCols](#contentindentcols) + +--- + +## ChatMessageManager +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** class + +```csharp +public sealed class ChatMessageManager +``` + + +Manages in-memory chat message storage, formatting and mutation for per-channel chat views. Use this when you need a single place to append formatted ChatLine objects, track per-channel unread counts and mention state, and notify the UI layer of any message-list changes via the MessagesChanged event. + +## Remarks +ChatMessageManager is the authoritative owner of channel message lists and the policies around unread/mention tracking and visual markers. It centralizes: formatting incoming MessageDto values into ChatLine instances (including insertion of day-boundary/date rules and continuation indentation), per-channel unread counters and "new messages" anchors, mention detection for the configured CurrentUser, and a persisted LastReadIds map that an external orchestrator can seed or store. The MessagesChanged event is fired with the channel name after any mutation so the UI can refresh only the affected view. + +## Notes +- Changing CurrentChannel has side effects: leaving a channel consumes its "new messages" marker and marks messages visible up to that point as read (this mirrors irssi-like behavior). Subscribe to MessagesChanged to react to those updates. +- SetCurrentUser and SetChatWidth should be populated by the host before relying on mention highlighting or line wrapping/continuation; the manager uses the current user and the configured width when formatting lines. +- LastReadIds is exposed as a read-only dictionary but is expected to be persisted/seeded externally (the manager exposes per-channel last-read message IDs so the orchestrator can restore unread/mention state across restarts). + +--- + +### CurrentChannel +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** property + +```csharp +public string CurrentChannel +``` + + +CurrentChannel exposes the actively selected chat channel and drives the UI-facing unread and mention-detection logic. When you switch channels, the setter clears the unread marker and marks the previous channel as read before updating the active channel reference, ensuring the old channel is considered read and the new channel becomes the current focus. + +## Remarks +This property centralizes the channel-switch lifecycle, ensuring consistent unread-state handling and mention detection as users move between channels. By containing the transition effects (clearing unread markers and marking read) within the setter, it reduces the risk of scattered state mutations elsewhere in the codebase and clarifies the responsibilities of channel state management. + +## Notes +- Switching channels clears unread markers for the old channel and marks it as read; the new channel's unread state remains unchanged until you leave it, which can be surprising if you expect an immediate clear on entry. +- Setting CurrentChannel to the same value is a no-op; no side effects run in that case. +- If _currentChannel is null (e.g., before any channel is selected), RemoveUnreadMarker(null) and MarkRead(null) will be invoked; depending on the implementations of those methods, this may be a no-op or require null handling. + + +--- + +### CurrentUser +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** property + +```csharp +public string CurrentUser => _currentUser +``` + + +Exposes the name of the user currently associated with the chat message manager as a read-only string. It simply returns the value of the private backing field _currentUser, providing a lightweight way to display or log the current user's identity without altering state. Use this property when you need to show who is sending a message, tag messages in the UI, or include the user in diagnostics; since it is backed by a field, there is no additional computation beyond a simple getter. + +## Remarks +CurrentUser acts as a thin surface over the internal state representing the active user. By exposing it as a property, the class avoids leaking the backing field while still providing an ergonomic, strongly-typed access point for consumer code. This is useful for displaying the current user in the chat header or tagging messages; changes to _currentUser will be immediately visible through CurrentUser because the getter reads the field value at access time. Keep in mind that if _currentUser is null, CurrentUser will be null as well, so downstream code should handle nulls accordingly. + +## Notes +- No public setter is provided; updates must occur by updating the backing field _currentUser within the class. +- The value can be null if _currentUser hasn't been assigned yet. +- There is no explicit thread-safety guarantee for this getter; if _currentUser may be updated from other threads, callers should ensure visibility. + +--- + +### LastReadIds +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** property + +```csharp +public IReadOnlyDictionary LastReadIds => _lastRead +``` + + +LastReadIds exposes, for each channel, the ID of the last message the user has read, as maintained by the orchestrator and persisted across connections. Use it to determine which messages are new and to seed unread/mention state when the client reconnects. + +## Remarks +Conceptually, this property decouples read-tracking from the UI, centralizing per-channel state in a durable dictionary that survives restarts. It relies on the orchestrator to persist history so unread markers and mentions align with the user's activity after reconnecting. + +## Example +```csharp +if (chat.LastReadIds.TryGetValue(channelId, out var lastReadId)) +{ + // lastReadId is the ID of the last message the user has read in this channel + // Use lastReadId to identify messages that are newer and should be highlighted as unread. +} +``` + +## Notes +- The dictionary is exposed as a read-only view; internal logic updates the underlying data. Do not attempt to mutate the collection from consumer code. +- If a channel isn't present in the dictionary, TryGetValue will return false; treat that as 'no stored last read' and consider all messages as potentially unread. + +--- + +### MentionChannels +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** property + +```csharp +public IReadOnlySet MentionChannels => _mentionChannels +``` + + +Exposes the set of chat channels that currently have unread mentions of the current user. The value is returned as an `IReadOnlySet` and is backed by the internal _mentionChannels field. Callers typically rely on MentionChannels to drive UI indicators (such as per-channel badges or highlights) showing which channels require the user's attention. The unread-mention state is cleared when ClearUnread is invoked. + +## Remarks + +Represents a read-only view into the manager's internal tracking of unread mentions. By returning an IReadOnlySet, it prevents accidental mutation from consumer code while still letting the UI reflect up-to-date state. Updates to the set occur through internal logic; ClearUnread resets the collection to an empty state, removing all current unread mentions. + +## Notes + +- This property is a live view of internal state; external code cannot mutate it directly. If the internal collection is updated, the new contents will be visible on subsequent enumeration. + +--- + +### ActionHeaderSegments +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List ActionHeaderSegments(string time) => + [ + new($"{time} ", ChatColors.TimestampAttr), + new(PadNick("*"), ChatColors.TimestampAttr), + new(" │ ", ChatColors.RailAttr), + ] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `time` | `string` | — | + +**Returns:** `List` + + +ActionHeaderSegments builds the header used when rendering /me action messages in the chat UI. It returns a `List` consisting of three parts: a timestamp segment created from the provided time string, a star-prefixed nickname segment produced by PadNick("*"), and a small rail separator. This header is meant to precede the actual action content, producing a visual like a timestamp, a leading "*" in the nick column, and a divider before the action text. The method relies on ChatColors.TimestampAttr for the time and star segments, and RailAttr for the separator, ensuring the header follows the established chat theming. + +## Remarks +ActionHeaderSegments encapsulates the specific visuals for /me action headers, ensuring all such headers are rendered consistently across the UI. By composing the header from three standardized ChatSegment pieces and delegating nickname rendering to PadNick, it centralizes styling concerns and reduces duplication in the rendering path. The dependency on ChatColors and PadNick ties this header closely to the existing color theming and nickname formatting used elsewhere in the chat system. + +## Notes +- This method is private and static, serving as an internal helper for header construction during message rendering. External code cannot call it directly. +- The time parameter must be a pre-formatted display string; the method does not perform formatting or validation of the time value. +- If the visual design for action headers changes (e.g., a different marker or separator), this single method should be updated to preserve consistency across all /me action headers. + +--- + +### AddMessage +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void AddMessage(MessageDto message) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `message` | [`MessageDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** `void` + + +Formats and stores a received message by first formatting it into display lines and then persisting those lines under the message’s ChannelName. It enforces a day-boundary rule by inserting a DateRule when the local date of the new message differs from the previous one, and it updates the latest message ID and, if applicable, the current-read pointer for the active channel. For inactive channels, it adds a one-time New Messages marker anchored to this message so a history reload can re-place it, and it increments the per-channel unread count while noting any mentions for later highlighting. Finally, it raises the MessagesChanged event to notify observers that the channel’s messages have updated. + +## Remarks + +This method centralizes all per-message mutations for the chat UI, ensuring consistent channel-state updates when new data arrives. It relies on the message.SentAt timestamp (converted to local time) to decide day boundaries and uses internal dictionaries (e.g., _channelMessages, _channelUnread, _markedChannels) to keep unread counts, markers, and last-read state in sync across channels. By anchoring an unread marker to the first unread message in inactive channels, it enables reliable re-placement on history reloads, while emitting MessagesChanged keeps the UI responsive to changes. + +## Notes + +- The method assumes message.ChannelName is non-null; otherwise an exception could be thrown when using dictionary keys. +- It uses ToLocalTime; time zone implications depend on the runtime environment and MessageDto's SentAt value. +- The internal state mutations are not protected by synchronization; callers should ensure serial access or add locking if called from multiple threads. + +--- + +### AddStatusMessage +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void AddStatusMessage(string channelName, string username, string status) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `username` | `string` | — | +| `status` | `string` | — | + +**Returns:** `void` + + +Adds a status change message to a channel with colored styling. It captures a timestamp via FormatTime(DateTimeOffset.Now), constructs header segments with SystemHeaderSegments, appends a segment describing the status change in the username’s color via ChatColors.SystemAttr, ensures the channel entry exists in the internal _channelMessages store, appends a new ChatLine built from the assembled segments (including a ContinuationPrefixSegments from RailPrefix), and, if the updated channel is the currently viewed one, fires the MessagesChanged event to refresh the UI. + +## Remarks + +This method centralizes the presentation of user status updates as timestamped, system-colored messages within a per-channel chat history. By encapsulating the formatting (time header, system-colored status text) and the mutation of the channel’s message list, it promotes consistent visual styling across channels and keeps UI updates synchronized with data changes. + +## Notes + +- Be mindful of thread-safety: _channelMessages is mutated without explicit synchronization, so concurrent calls could race in a multi-threaded context. +- Time formatting depends on the system clock; for deterministic tests, consider controlling FormatTime/DateTimeOffset.Now or abstracting time retrieval. + + +--- + +### AddSystemMessage +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void AddSystemMessage(string channelName, string text) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `text` | `string` | — | + +**Returns:** `void` + + +Adds a system/informational message to a channel with colored styling. When invoked, it ensures the channel's message list exists, formats the current time, splits multi-line text so the first line appears in the header and subsequent lines are added as separate lines with a rail-style continuation prefix; if the target channel is the currently visible one, it triggers a UI refresh via MessagesChanged. + +## Remarks +System messages are rendered with a header line that includes a timestamp, followed by body segments styled with SystemAttr. This method centralizes the formatting of such messages, so callers don't need to assemble headers or manage continuation prefixes themselves. It relies on ChatLine, ChatColors, and RailPrefix to produce a consistent visual treatment across channels. + +## Notes +- Potential lack of thread-safety if called from multiple threads; the internal _channelMessages dictionary is mutated without locking. +- Only the UI refresh is raised when posting to the currently active channel (otherwise the message is updated silently). +- Lines after the first are treated as separate ChatLine entries with their own continuation prefix; blank lines are ignored. + +--- + +### AttachmentActionLine +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static ChatLine AttachmentActionLine(string text, Attribute color, AttachmentDto attachment) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `text` | `string` | — | +| `color` | `Attribute` | — | +| `attachment` | [`AttachmentDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** [`ChatLine`](ChatLine.cs.md) + + +The AttachmentActionLine method constructs a ChatLine that renders as a clickable attachment action within the chat list. It prefixes the display text with a standardized rail segment, colors the text using the provided color attribute, and attaches the underlying attachment metadata (URL, file name, and kind) so the UI can route activation to the correct behavior (play audio, download, or save the original image). + +## Remarks +AttachmentActionLine centralizes how attachment-based actions are presented in the chat. By bundling the styling prefix, action text, and attachment metadata in a single factory, it keeps rendering and activation logic cohesive and easier to maintain. The method relies on RailPrefix to ensure consistent visual grouping and populates ChatLine's attachment properties so downstream UI and activation code can locate the URL, file name, and kind without reassembling them. + +## Notes +- The method is private and static, so it is only callable within its containing type and from a known, fixed entry point. +- It sets ContinuationPrefixSegments to RailPrefix(), ensuring continuation lines align with the same action prefix; altering RailPrefix behavior might affect line wrapping or click target consistency. + +--- + +### ClearAll +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void ClearAll() +``` + +**Returns:** `void` + + +Clears all internal message state maintained by the chat message manager. This method empties all per-channel data stores and resets the current context, providing a clean slate when disconnecting or reinitializing the chat UI. It is used during disconnect sequences to prevent stale data from persisting across sessions. + +## Remarks +By encapsulating reset logic here, the class guarantees a consistent baseline state after disconnection. It reduces the risk of partially cleared state being left behind when disconnects occur in various code paths, and it centralizes lifecycle management for chat state. + +## Notes +- Not inherently thread-safe: callers should ensure synchronization if the ChatMessageManager is accessed concurrently during disconnect. +- After invocation, there is no active channel or user until reinitialization occurs; _currentChannel and _currentUser are set to empty strings. +- This method only clears in-memory state; any external resources or persisted data are unaffected. + +--- + +### ClearChannelMessages +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void ClearChannelMessages(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Clears all messages for a specific channel from the client-side chat state. If the channel exists in the internal message map, it empties that channel's message list and removes the per-channel metadata: the last date, marked channels, and marker anchor for that channel. If the channel being cleared is currently active, it raises the MessagesChanged event to notify the UI to refresh for that channel. If the channel does not exist in the map, this method is a no-op. The operation affects only in-memory state and does not touch persistent storage or other channels. + +## Remarks +This method centralizes the cleanup of per-channel UI state, ensuring that clearing a channel leaves the rest of the UI in a consistent state. By clearing the per-channel dictionaries and lists alongside the messages, it prevents stale metadata from lingering after a channel's history is purged. The MessagesChanged event invocation for the current channel decouples UI refresh logic from the data update, allowing subscribers to re-render the channel view as needed. + +## Notes +- No persistence: only in-memory state is cleared. +- Safe-to-call-no-op: if the channel is missing from _channelMessages, the method returns without side effects. +- Assumes non-null per-channel message list: a null collection would cause a NullReferenceException on Clear, so callers should ensure the data is initialized. +- If multiple components listen for MessagesChanged, the event will fire only when the cleared channel is the current channel; other channels won't trigger an automatic refresh from this call. + +--- + +### ClearUnread +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void ClearUnread(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Clears the unread state for the specified channel by resetting its unread count, removing mention highlights, and marking the channel as read. This is typically invoked when the user opens or explicitly reads a channel, ensuring the UI and internal state reflect that there are no remaining unread messages for that channel. + +## Remarks + +Clears three facets of unread state in a single operation: it updates the internal unread counter for the channel, removes the channel from the active mention-tracking collection, and delegates to MarkRead to apply the persisted read-state. This centralizes the read-clearing behavior so the rest of the UI can rely on a single, consistent method rather than duplicating logic at multiple call sites. The exact effects depend on the implementations of _channelUnread, _mentionChannels, and MarkRead; for example, if the channel is not yet present, the first assignment will create an entry with 0 unread, and Remove will be a no-op if the channel is not in _mentionChannels. + +## Example + +```csharp +// Assuming 'manager' is an instance of ChatMessageManager +manager.ClearUnread("general"); +``` + +## Notes +- If ClearUnread is invoked for a channel that did not previously exist in the internal structures, the first line will create or overwrite an entry with a value of 0. +- The behavior of MarkRead is relied upon to finalize the read-state side effects; if MarkRead triggers additional side effects (e.g., persistence or events), those will occur as part of this call. + + +--- + +### DateRule +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static ChatLine DateRule(DateTime date) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `date` | `DateTime` | — | + +**Returns:** [`ChatLine`](ChatLine.cs.md) + + +DateRule constructs a stylized date separator line for a given date within the chat UI. It derives a label from DateRuleLabel(date) and returns a ChatLine containing a single segment that renders as "── {label} ──" using ChatColors.DateRuleAttr. The returned ChatLine also has its RuleLabel set to the label and its RuleAttr set to the same color attribute. Use this helper whenever you need a consistent, date-bounded visual divider between messages rather than composing lines manually. + +## Remarks +By encapsulating the creation of the date rule, DateRule provides a single point of change for how date separators look and behave. It coordinates the label generation with the chat coloring to ensure separators match other UI rule lines and follow the project's styling conventions for date-related cues. This abstraction sits alongside ChatLine and ChatColors, reinforcing a uniform approach to rendering non-message chrome in the chat. + +## Notes +- Changes to DateRuleLabel or the decorative glyphs will affect every date separator; tests that assert exact separator text should be updated if the label generation changes. +- DateRule is private static, so its reuse is limited to the containing class; if external customization is needed, consider elevating the helper to a more accessible API or adjusting the color attribute usage in ChatColors.DateRuleAttr. + +--- + +### DateRuleLabel +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +internal static string DateRuleLabel(DateTime date) => date.ToString("ddd, MMM d yyyy") +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `date` | `DateTime` | — | + +**Returns:** `string` + + +Converts a DateTime to a short, human-friendly label using the pattern 'ddd, MMM d yyyy'. This helper returns a string such as 'Tue, Jul 23 2024' and is used by the chat UI to display date labels consistently instead of formatting dates ad-hoc at each call site. + +## Remarks +This method centralizes the exact format used across the chat components, ensuring consistent date labels. It is declared internal and static, indicating it's intended for internal use within the ChatMessageManager's UI rendering flow rather than as part of the public API. + +## Notes +- This formatting respects the current culture; for stable, culture-independent output, supply a culture-invariant format (e.g., date.ToString("ddd, MMM d yyyy", CultureInfo.InvariantCulture)) and add a using System.Globalization. + +--- + +### FormatEmbed +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List FormatEmbed(EmbedDto embed, int chatWidth) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `embed` | [`EmbedDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | +| `chatWidth` | `int` | — | + +**Returns:** `List` + + +Formats an embed into a vertical sequence of chat lines with a left rail and colored text, suitable for rendering inside the chat UI. It accepts an EmbedDto and the current chat width, computes the available text area, and assembles lines that begin with a fixed border segment colored by the embed border color, followed by the actual text colored per section (title or description). If present, SiteName is emitted first using the border color; Title is wrapped to the computed text width and emitted with EmbedTitleAttr; Description is wrapped similarly with EmbedDescAttr. The method returns a `List` that can be rendered as part of a larger message. + +## Remarks +FormatEmbed centralizes the formatting decisions for embeds in the chat UI, ensuring a consistent look by deriving the border color from the embed ThemeColor or falling back to a default border color, and by applying distinct styling to the title and description. It relies on shared utilities (WordWrap and RailPrefix) to wrap text to the computed width and to align lines with a left rail, respectively. Because this is a private helper, its usage is confined to the containing class, which helps encapsulate embed rendering and prevents drift from the surrounding chat presentation. + +## Notes +- If embed.ThemeColor is an invalid hex string, the border color falls back to ChatColors.EmbedBorderAttr. +- The text width is computed from the provided chatWidth and is clamped to a minimum of 20 columns; very small chat widths may lead to tighter wrapping and more lines. + + +--- + +### FormatFileSize +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +internal static string FormatFileSize(long? bytes) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `bytes` | `long?` | — | + +**Returns:** `string` + + +Formats a nullable file size into a concise, human-readable string. If the input is null or zero, it returns a single question mark to indicate an unknown or unavailable size. For any non-null value, it chooses the most appropriate unit among bytes (B), kilobytes (KB), megabytes (MB), and gigabytes (GB) and formats the result with a single decimal place for all units except bytes. The thresholds use binary units (1024 multipliers), producing strings like '512 B', '1.5 KB', '3.2 MB', or '1.2 GB'. + +## Remarks +Consolidates the formatting logic so callers don’t duplicate range checks or string formatting, ensuring consistent display across the UI. The function intentionally treats null or zero as unknown ("?") rather than returning a numeric zero, which is useful when the size may not be known at the point of rendering. + +## Notes +- Null or zero input yields "?" per the early guard. +- Uses binary thresholds: 1024 B for KB, 1024^2 B for MB, and 1024^3 B for GB. +- Non-byte units are shown with one decimal place (e.g., 1.5 KB, 3.2 MB, 1.2 GB); boundary values exactly at 1024, 1024^2, etc., switch units accordingly (e.g., 1024 B becomes 1.0 KB). + + +--- + +### FormatMessage +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private List FormatMessage(MessageDto message) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `message` | [`MessageDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** `List` + + +Formats a MessageDto into a list of ChatLine entries suitable for rendering in the chat UI. It resolves the timestamp via FormatTime, chooses a representative display name (SenderDisplayName when available, otherwise SenderUsername), and derives a nickname color using HexColorHelper or NickColorHelper. The method then builds a header line or a summarized header for attachments, handles reply quotes by inserting a preceding quote line, and supports CTCP-style /me actions by rendering a header that shows the action followed by additional lines. When content exists, the content is emoji-normalized and split into lines with mention highlighting; when there is no text, a compact header summarizes attachments. Each line receives a RailPrefix so subsequent content lines and per-attachment blocks align with the nick rail, and attachments produce their own blocks hanging off that rail (e.g., image previews). + +--- + +### FormatTime +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static string FormatTime(DateTimeOffset timestamp) => + timestamp.ToLocalTime().ToString("HH:mm") +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `timestamp` | `DateTimeOffset` | — | + +**Returns:** `string` + + +Formats a DateTimeOffset timestamp into the user's local time and renders it as a compact 24-hour time string (HH:mm). By converting to local time before formatting, the method ensures that times align with the local calendar day rules, so messages near midnight are associated with the correct day in the UI. This helper is used wherever a concise, time-only indicator is needed for chat messages (for example, timestamps next to messages). + +## Remarks +By centralizing locale-aware time formatting in a private helper, the code avoids duplicating ToLocalTime calls across the UI and guarantees a consistent display of chat timestamps. It is designed for presentation concerns rather than time arithmetic. + +## Notes +- Relies on the system's local time zone via ToLocalTime; DST and locale settings affect the result. +- Only the time portion is produced (HH:mm); date and potential day-boundaries are resolved at a higher level in the UI. +- As a private method, its usage is confined to the containing class; if cross-cutting formatting is needed, consider extracting to a shared utility. + +--- + +### FormatWithDateRules +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private List FormatWithDateRules(List messages, out DateTime? lastDate) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messages` | `List` | — | +| `lastDate` | `DateTime?` | — | + +**Returns:** `List` + + +Formats a chronological batch of messages into a list of ChatLine objects, inserting a date rule before the first message and whenever the day changes. The method converts each message's SentAt to local time to determine day boundaries, delegates per-message formatting to FormatMessage, and returns the assembled lines while outputting the last processed local date via lastDate. + +## Remarks +Day separators help users scan conversations by calendar date, providing clear visual breaks between days. By isolating the boundary logic in this function and delegating rendering to DateRule and FormatMessage, the code remains reusable and consistent across different chat views. + +## Example +```csharp +// Example: format a batch of messages into chat lines with day separators +DateTime? lastDate; +List lines = FormatWithDateRules(batchMessages, out lastDate); +``` + +## Notes +- No null-check on the input list; passing null for messages will throw. +- lastDate is null if there are no messages; callers should account for a possible null value. + +--- + +### GetMessages +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public List? GetMessages(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `List?` + + +Retrieves the current list of ChatLine entries for a specific channel by name from the internal message store. It returns the existing `List` for the channel, or null if the channel has no messages. This is a lightweight accessor around the underlying storage and does not create a new list or clone data. + +## Remarks +This method exposes the internal `List` instance associated with the given channel. Callers should be aware that mutations to the returned list (adding/removing items) will affect the stored messages for that channel. If an immutable snapshot is required, consider copying the list before enumeration or modification. The method hides the details of how messages are stored, providing a single entry point that can be swapped out without changing call sites. + +## Example +```csharp +var messages = chatMessageManager.GetMessages("general"); +if (messages != null) +{ + Console.WriteLine($"General channel has {messages.Count} messages."); +} +``` + +## Notes +- Returning null indicates the channel has no messages or does not exist in the store; always null-check before accessing properties like Count. +- The returned `List` is not cloned; modifications to it affect the internal store unless an external copy is created. + +--- + +### GetUnreadCount +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public int GetUnreadCount(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `int` + + +Returns the unread message count for the specified channel by querying the internal _channelUnread mapping. If the channel has no recorded count, it returns 0. This read-only helper encapsulates access to the underlying data and is typically used by the UI to display per-channel unread badges without exposing the dictionary directly. + +## Remarks + +Acts as a minimal abstraction over the unread-tracking store, hiding direct dictionary access and ensuring a zero default when a channel has no entry. The caller should understand that the value comes from the shared _channelUnread structure, so updates to unread counts elsewhere will be visible on subsequent calls; if the underlying storage is not thread-safe, callers must ensure proper synchronization. + +## Notes + +- Passing null as channelName will throw an ArgumentNullException from TryGetValue. + +--- + +### GetUnreadCounts +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +internal Dictionary GetUnreadCounts() => _channelUnread +``` + +**Returns:** `Dictionary` + + +Returns the internal per-channel unread counts as a mutable dictionary backed by the _channelUnread field. Use this accessor when you need to read or react to per-channel unread tallies without recomputing them, noting that the returned dictionary is the live internal collection. + +## Remarks +This accessor is intended as a lightweight bridge between the internal unread-count store and UI or coordination code that needs to display or react to those counts. It avoids copying data for performance and maintains synchronization with internal updates. However, because it returns the actual dictionary, external callers can mutate the collection, potentially breaking invariants or introducing subtle bugs. If you require a read-only view, consider returning `IReadOnlyDictionary` or a defensive copy, and adjust the signature accordingly. + +## Notes +- Mutability risk: Changes to the returned dictionary affect internal state. +- Thread-safety: Concurrent updates to _channelUnread may race with external mutations; consider synchronization. +- Initialization: Ensure _channelUnread is initialized before first access to avoid NullReferenceException. + +--- + +### HeaderSegments +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List HeaderSegments(string time, string nick, Attribute? nickColor) => + [ + new($"{time} ", ChatColors.TimestampAttr), + new(PadNick(nick), nickColor), + new(" │ ", ChatColors.RailAttr), + ] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `time` | `string` | — | +| `nick` | `string` | — | +| `nickColor` | `Attribute?` | — | + +**Returns:** `List` + + +HeaderSegments constructs the three leading pieces of a message header line: a dim timestamp, the (optionally) colored, padded nickname, and a fixed rail separator. It returns these as a `List` so the caller can render the header independently from the message body. The first segment renders the provided time string with the Timestamp attribute, the second applies a padded nickname using the supplied nickColor, and the third renders a static rail string with the Rail attribute. This centralized assembly ensures consistent header formatting across messages and keeps layout/color decisions isolated from the rest of the rendering logic. The header segments precede the actual message text, which begins after ContentIndentCols. + +## Remarks +By encapsulating header composition, this method enforces consistent alignment and styling for all message headers. It isolates colorization and spacing concerns from the message content, making it easier to adjust the header's appearance in one place without touching rendering logic elsewhere. + +## Example +```csharp +// Example usage within the same class context +var segments = HeaderSegments("12:34", "Alice", ChatColors.SystemAttr); +``` + +## Notes +- The method is private, so it cannot be called from outside its declaring type. If header construction is needed elsewhere, provide a public wrapper or move the logic to a shared utility. +- The nick color parameter is nullable, allowing callers to omit explicit coloring when desired; the rendering path should handle a null color accordingly. + +--- + +### ImageActionLine +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static ChatLine ImageActionLine(AttachmentDto attachment) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `attachment` | [`AttachmentDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** [`ChatLine`](ChatLine.cs.md) + + +Builds the action line displayed under an image preview, showing [open] and [↓ save original] as clickable actions and appending the file name with its size. Each bracketed label becomes an AttachmentActionSpan so the UI can map clicks to the corresponding action, while Enter triggers the default (open). + +## Remarks +This symbol centralizes the rendering of image-related actions in chat messages, ensuring consistent spacing and interactivity across messages. It constructs the action regions by measuring segment widths from RailPrefix() and updating a running column index; the resulting ChatLine carries ActionSpans and attachment metadata for downstream rendering. + +## Notes +- The clickable targets cover only the bracketed portions; the trailing file name and size text is not interactive. +- If you change the action labels or formatting, adjust the width calculation logic accordingly, since spans are derived from the label text width. + +--- + +### LoadHistory +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void LoadHistory(string channelName, List messages, Guid? lastReadId = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `messages` | `List` | — | +| `lastReadId` | `Guid?` | `null` | + +**Returns:** `void` + + +Loads historical messages into a channel, replacing any existing messages. When lastReadId is supplied (persisted from a previous session), the messages after that identifier are seeded into the unread count, @mention highlighting, and the `new messages` marker, ensuring activity from when the user was offline is surfaced when history is loaded. + +## Remarks + +This method is the central entry point for bringing a channel's history into the UI. It formats incoming messages, updates per-channel caches (such as the latest message id, the list of messages, and the last date), and raises the MessagesChanged event to refresh the view. A key concern it addresses is surfacing unread backlog: if the channel is not currently marked, and a lastReadId is provided, the code seeds unread state from the provided history so the user sees what they missed. If the channel is marked, the code attempts to preserve the unread marker by inserting UnreadMarkerRule() at a known anchor position; if the anchor cannot be located within the fetched batch, the marker is dropped and the anchor tracking for that channel is cleared. + +The method keeps the display coherent across history loads by either re-anchoring the marker or seeding unread state, and it updates the channel's last date when available. This coordination helps maintain a stable user experience as history is navigated. + +## Notes + +- Marker anchor handling may drop the unread marker if the anchor falls outside the fetched history window; in that case the channel's marker tracking is cleared. +- When lastReadId is provided and there is history, unread state is seeded from history only if the channel is not currently marked with an anchor. +- There are internal caches being updated (_channelMessages, _channelNewestId, _channelLastDate, etc.) and a UI notification is raised via MessagesChanged; callers should ensure thread-safety or call this from a suitable thread to avoid races. + +--- + +### MarkRead +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private void MarkRead(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Updates the internal read-tracking state for a chat channel by setting the last-read marker to the channel's newest known message ID, if available. It is a small internal helper used when the user has effectively read up to the latest message in the specified channel. + +## Remarks +This method serves as a concise read-tracking primitive within ChatMessageManager. It relies on two internal structures—_channelNewestId (the newest known message ID per channel) and _lastRead (the last-read position per channel)—to advance the read marker without exposing the internal collections to external callers. By performing a safe fetch and updating only when a newest ID exists, it provides a robust, side-effect-limited mechanism for synchronizing UI read state with the channel's latest activity. + +## Notes +- No-op if channelName is null or empty, or if there is no entry for the channel in _channelNewestId; in these cases, no exception is thrown and the state remains unchanged. + + +--- + +### PadNick +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +internal static string PadNick(string nick) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `nick` | `string` | — | + +**Returns:** `string` + + +Right-aligns a nickname into the fixed nickname column, truncating nicknames that exceed the available width with an ellipsis, while respecting grapheme boundaries and display column widths. This ensures consistent, visually aligned nicknames in the chat UI regardless of complex characters. + +## Remarks +Right-aligns a nickname within a fixed-width column and centralizes the logic for width-aware truncation. By counting display columns per grapheme and never splitting a grapheme cluster, it preserves user-visible completeness (including emoji and combining characters) while maintaining a stable layout. The ellipsis is appended when truncation is necessary, and the result is padded on the left to exactly fill NickColWidth columns. + +## Notes +- The truncation reserves one column for the ellipsis (NickColWidth - 1) to preserve the final width. +- Each grapheme's display width is obtained via g.GetColumns(), with a minimum of 1 column to avoid stalls on zero-width elements. +- NickColWidth should be a positive, reasonable value to ensure the UI remains legible; extreme values may produce unexpected padding. + +--- + +### PrependHistory +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void PrependHistory(string channelName, List olderMessages) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `olderMessages` | `List` | — | + +**Returns:** `void` + + +PrependHistory prepends older messages to the front of a channel’s in-memory buffer, skipping any that are already present. It filters olderMessages to those not already in the buffer by MessageId, formats the new messages into display lines (respecting the channel’s date-rule conventions), and inserts them at the beginning of the buffer. If the channel isn’t tracked, or if no new lines are produced, the method returns without side effects. When the update targets the currently displayed channel, it raises the HistoryPrepended event to signal the UI to reflect the new history. + +## Remarks +Conceptually, this method isolates the concerns of history retrieval, formatting, and UI notification from higher-level chat flow. It relies on MessageId to detect duplicates and on date-rule formatting to ensure the inserted lines align with existing visual rules. By conditionally removing a redundant leading date line when the batch ends on the same day as the current first line, it avoids duplicating date indicators at the top of the buffer. + +## Notes +- The method mutates the in-memory channel buffer in place and may affect the UI; callers should be aware of in-memory state changes. +- Deduplication uses MessageId; messages without an Id will be treated as new and could be inserted if not already present. +- HistoryPrepended is raised only when the target channel is the currently active channel (_currentChannel); otherwise, no event is fired. + +--- + +### RailPrefix +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List RailPrefix() => + [ + new(new string(' ', 6 + NickColWidth + 1), null), + new("│ ", ChatColors.RailAttr), + ] +``` + +**Returns:** `List` + + +RailPrefix produces the indentation prefix used for lines that continue or attach to a chat message. It builds two ChatSegment entries: a leading blank-space block sized to accommodate the nickname column plus padding, and a rail segment rendering the vertical continuation rail. A fresh mutable `List` is returned on every call so callers can compose per-line prefixes without mutating shared state. + +## Remarks +RailPrefix encapsulates the alignment rule used for multi-line messages, ensuring that continuation lines align consistently with the main message regardless of nickname width or color settings. The first segment accounts for the nickname column width (NickColWidth) plus a small padding, while the second segment draws the rail using ChatColors.RailAttr, producing a visually distinct vertical guide. Returning a new list on each call avoids cross-call mutations and keeps prefix construction side-effect free. + +## Notes +- Changing NickColWidth or RailAttr will affect the resulting prefix, so coordinate styling changes to avoid misalignment. +- The method returns a new `List` that callers are free to mutate; it does not mutate any shared state. + +--- + +### RemoveMessage +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void RemoveMessage(string channelName, Guid messageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `messageId` | `Guid` | — | + +**Returns:** `void` + + +Removes all lines associated with a specific message ID from the client's in-memory per-channel message collection. It locates the list for the given channelName, eliminates any entries whose MessageId matches the provided messageId, and, if the updated channel is the current one, raises the MessagesChanged event to trigger a UI refresh. This method is useful when you need to purge a message from the local view (for example after a retraction or client-side filtering) without affecting server-side state. + +## Remarks +By centralizing the removal logic, this symbol ensures consistent mutation of the per-channel message lists and a single notification point for UI updates. The operation is scoped to a single channel, and the UI will only refresh when the target channel is currently active. Because the method operates purely on the client-side in-memory structure, there is no server communication performed by this call. + +## Notes +- Not thread-safe as written; ensure marshaling to UI thread or proper synchronization when accessing _channelMessages or the channel's message list. +- Assumes MessageId uniquely identifies a line; if duplicates exist, all matching lines are removed. + + +--- + +### RemoveUnreadMarker +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private void RemoveUnreadMarker(string channel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channel` | `string` | — | + +**Returns:** `void` + + +Removes the unread marker for a given chat channel by validating the input, clearing the channel from the marked set, detaching its UI marker anchor, and purging any unread-marker flags from the channel’s messages. + +## Remarks +As a private helper, it centralizes the unread-marker lifecycle in ChatMessageManager, coordinating _markedChannels, _markerAnchor, and _channelMessages to keep UI state and data in sync. The early return guards prevent unnecessary work when the channel is invalid or already cleared. The removal of IsUnreadMarker flags happens only after the channel is removed from the marked set, ensuring a consistent, single source of truth for whether a channel shows an unread indicator. + +## Notes +- This method is private; external callers should not rely on its behavior. +- There is no synchronization visible in the snippet, so concurrent invocations may require external synchronization. +- If there are unread indicators outside the IsUnreadMarker flags, they will not be cleared by this method. + +--- + +### ReplyQuoteLine +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static ChatLine ReplyQuoteLine(ReplyRefDto replyTo) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `replyTo` | [`ReplyRefDto`](../../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** [`ChatLine`](ChatLine.cs.md) + + +Constructs a compact, rail-prefixed quote line for an incoming reply. It carries the original message id (JumpToMessageId) so selecting the quote navigates to the source, and it truncates the displayed snippet to fit the UI width. The snippet is sanitized by replacing newline characters with spaces, optionally converted to an action-style prefix if a known action is detected, and transformed with emoji glyph replacement. The result is a ChatLine composed of three segments: a rail prefix, the sender's username (colored), and the snippet (system-colored). The line also exposes JumpToMessageId for navigation and ContinuationPrefixSegments to align any continued lines of the rail. + +--- + +### SeedUnreadFromHistory +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private void SeedUnreadFromHistory(string channelName, List messages, + List formatted, Guid lastReadId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `messages` | `List` | — | +| `formatted` | `List` | — | +| `lastReadId` | `Guid` | — | + +**Returns:** `void` + + +Reconstructs unread state from a persisted last-read message id for a channel by inserting an unread marker before the first unread message in the current fetch window and, for inactive channels, seeding the unread count and @mention highlight. If the last-read id is no longer present in the fetched window, the entire window is treated as unread. + +## Remarks +This symbol centralizes how persisted read positions are translated into the UI's unread indicators. It updates internal trackers (_markedChannels, _markerAnchor, _channelUnread, and _mentionChannels) and mutates the formatted message list to place the visual cue that new messages are available. Because it only applies the badge/mention behavior to background channels, the active channel remains visually unaffected beyond the standard read state. + +## Notes +- If the computed anchor line cannot be found in the current formatted list, no marker is inserted and the method returns. +- When lastReadId is not found in messages, firstUnread becomes 0, so the marker targets the very first message in the window. +- Mentions are evaluated only for non-active channels; active channels do not receive mention highlights from this method. + +--- + +### SetChatWidth +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void SetChatWidth(int width) => _chatWidth = width +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `width` | `int` | — | + +**Returns:** `void` + + +Sets the internal chat width used by the chat rendering logic. This method is a concise mutator that assigns the provided width to the private _chatWidth field. Use it when you need to programmatically adjust the chat area width, such as in response to layout changes or user actions that resize the chat panel. + +## Remarks + +Centralizes width mutations behind a single API, preserving encapsulation of layout state. It also paves the way for future side effects (for example, triggering a layout refresh or validating the value) without changing call sites. Keeping this logic in one place reduces duplication and makes behavior easier to evolve. + +## Notes + +- No validation on the input width; callers should ensure the value is non-negative and within reasonable bounds to avoid render glitches. + +--- + +### SetCurrentUser +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +public void SetCurrentUser(string username) => _currentUser = username +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `void` + + +Sets the internal _currentUser field to the provided username, updating the chat subsystem's notion of who is the current user. This method should be used whenever the active user changes (for example, after a user logs in or switches accounts) so that subsequent messages can be attributed to the correct user in the UI. + +## Remarks +Centralizes mutation of the current user state within ChatMessageManager, making it easier to add side effects (such as updating UI elements, tagging messages, or enforcing user-specific behavior) without changing call sites. By routing changes through SetCurrentUser, the class can evolve to perform validation, trigger events, or refresh displays in a single place. + +## Notes +- No input validation or normalization is performed; the value is assigned directly to _currentUser. Passes such as null or empty strings may lead to an invalid or inconsistent state unless the caller ensures proper validation. + +--- + +### SystemHeaderSegments +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List SystemHeaderSegments(string time) => + [ + new($"{time} ", ChatColors.TimestampAttr), + new(PadNick("--"), ChatColors.TimestampAttr), + new(" │ ", ChatColors.RailAttr), + ] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `time` | `string` | — | + +**Returns:** `List` + + +This private helper constructs the header segments for a system/status line. When given a formatted time string, it returns a three-segment header (ChatSegment list) that renders: the time, a padded system nickname placeholder, and a leading rail separator, all styled with the project's chat color attributes. The header segments correspond to the three elements in the returned list: the time string followed by a space colored with TimestampAttr, the PadNick(\"--\") value colored with TimestampAttr, and the literal rail \" │ \" colored with RailAttr. This utility is used by the chat header rendering logic to produce a consistent appearance for system messages. + +## Remarks +This private method encapsulates the three-part system header used for status lines, anchoring time, nickname placeholder, and the rail separator in one place. It relies on PadNick for the nickname placeholder width and on ChatColors attributes to keep the look aligned with the rest of the chat chrome. + +## Notes +- The time argument should already be formatted for display; the method does not parse or reformat it. +- The header relies on PadNick to produce a fixed-width nickname; changes to PadNick's output or width could affect alignment. + +--- + +### UnreadMarkerRule +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static ChatLine UnreadMarkerRule() => + new([new("── new messages ──", ChatColors.UnreadMarkerAttr)]) +``` + +**Returns:** [`ChatLine`](ChatLine.cs.md) + + +Creates a ChatLine that renders the '── new messages ──' unread marker using the UnreadMarker color attribute. This private helper is used when building the chat line sequence to visually indicate that there are unread messages in the conversation. + +## Remarks +To centralize the styling and labeling of the unread marker, this helper bundles the label ('new messages'), the color attribute (ChatColors.UnreadMarkerAttr), and the unread-marker flag (IsUnreadMarker = true). It keeps the construction logic in one place so changes to the marker's text or color propagate consistently across callers. The private visibility signals that this is an internal construction detail of the chat rendering pipeline. + +## Notes +- This symbol is private; it cannot be called from outside its containing class. If you need to render unread markers elsewhere, consider exposing a public API or refactoring the helper into a shared utility. +- The returned ChatLine is explicitly marked as an unread marker; consumers should treat it as a UI cue rather than a regular chat message. + +--- + +### WordWrap +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** method + +```csharp +private static List WordWrap(string text, int maxCols) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `text` | `string` | — | +| `maxCols` | `int` | — | + +**Returns:** `List` + + +WordWrap is a private utility that converts a single string into a list of lines whose display width does not exceed a specified maxCols. It's designed for UI scenarios (for example, chat messages) where wrapping must be deterministic and centralized. If maxCols <= 0, the method returns a single-element list containing the original text. + +Otherwise, it splits the input on spaces (collapsing multiple spaces) and greedily builds lines by appending words until adding the next word would exceed maxCols as measured by GetColumns. When a word would overflow the current line, the line is committed and a new one starts with that word. The final line is added after processing all words. The resulting lines use single spaces between words. + +Note that a single word longer than maxCols will be placed on its own line and may exceed the requested width. + +--- + +### NickColWidth +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** field + +```csharp +public const int NickColWidth = 12 +``` + + +NickColWidth defines the fixed width of the nickname column in the chat UI, reserving 12 characters on the right to align nicknames in a WeeChat-style layout. It is used by the chat rendering logic in ChatMessageManager to keep nickname alignment consistent across messages. + +## Remarks +Centralizes the presentation detail of the nickname column, avoiding scattered magic numbers across rendering code. By exposing this as a single public constant, it’s straightforward to tweak the overall alignment of the chat UI while keeping the rest of the layout logic unchanged. It also communicates intent clearly to future contributors who are adjusting how usernames appear in chat rows. + +## Notes +- As a public compile-time constant, changing NickColWidth requires recompiling dependents to pick up the new value. +- Prefer referencing NickColWidth in formatting/layout code rather than using hard-coded numeric literals to maintain consistent alignment. + +--- + +## ContentIndentCols +> **File:** `src/EchoHub.Client/UI/Chat/ChatMessageManager.cs` +> **Kind:** field + +```csharp +public const int ContentIndentCols = 6 + NickColWidth + 3 +``` + + +ContentIndentCols represents the total number of character columns that precede the actual message text in a chat line. It is computed as 6 (the length of the "HH:mm " timestamp prefix) plus NickColWidth (the width of the nickname column) plus 3 (the " │ " separator). Use ContentIndentCols when you need to align or wrap the message body so that it starts at a consistent column after the header. + +## Remarks +This abstraction ties the content start position to the header region, ensuring consistent alignment across messages even if nickname width or the time prefix changes. By centralizing the indentation budget behind a single public constant, rendering code avoids scattered magic numbers and remains coherent when layout assumptions evolve. + +## Example +```csharp +// Example: build an indented content line for a chat message +string line = new string(' ', ContentIndentCols) + body; +``` + +## Notes +- The constant is a compile-time value (public const int). If you need dynamic indentation per message or per theme, compute it at runtime instead of using ContentIndentCols. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatSegment.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatSegment.cs.md new file mode 100644 index 0000000..21f2acd --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/ChatSegment.cs.md @@ -0,0 +1,26 @@ +# ChatSegment + +> **File:** `src/EchoHub.Client/UI/Chat/ChatSegment.cs` +> **Kind:** record + +```csharp +public record ChatSegment(string Text, Attribute? Color) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Text` | `string` | — | +| `Color` | `Attribute?` | — | + + +ChatSegment represents a colored fragment of text within a chat line. It pairs the displayed text with an optional color attribute, enabling the UI to render parts of a message with varying styling without altering the textual content. As a record, ChatSegment is immutable and supports value-based equality, making it convenient to compose a full line by aggregating multiple segments in a deterministic way. + +## Remarks +ChatSegment exists to separate content from presentation. By modeling a line as a sequence of segments, the rendering layer can apply different colors or styles to each piece while preserving the original order. The record-like semantics also ease comparisons, caching, and deduplication of segments across messages. + +## Notes +- Color is stored as a nullable Attribute; a null Color means no special styling is requested for this segment. +- `Attribute` is a general metadata type; downstream renderers interpret it to apply styling. The exact meaning of the Color value depends on the consuming UI. +- Because ChatSegment is a two-property record, equality includes both Text and Color; changes to either produce a distinct segment, which is important when deduplicating or comparing segments. diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/RenderHelpers.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/RenderHelpers.cs.md new file mode 100644 index 0000000..db4d20b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/RenderHelpers.cs.md @@ -0,0 +1,11 @@ +# RenderHelpers + +> **File:** `src/EchoHub.Client/UI/Chat/RenderHelpers.cs` +> **Kind:** class + +```csharp +static class RenderHelpers +``` + + +RenderHelpers is a small, shared utility for rendering IListDataSource content. Its WriteText method writes text to a ListView grapheme-by-grapheme while respecting a maximum width, returning the updated count of drawn columns. It iterates over grapheme clusters obtained from GraphemeHelper.GetGraphemes(text); for each grapheme, it computes the display width with GetColumns() (falling back to 1 if necessary). If adding the grapheme would exceed maxWidth, rendering stops. Otherwise, it appends the grapheme to the ListView via lv.AddStr(grapheme) and increments the drawn count. This centralizes grapheme-aware rendering logic so multiple IListDataSource implementations share consistent width handling and avoid duplicating rendering concerns. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/WelcomeBanner.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/WelcomeBanner.cs.md new file mode 100644 index 0000000..9c32c8c --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Chat/WelcomeBanner.cs.md @@ -0,0 +1,24 @@ +# WelcomeBanner + +> **File:** `src/EchoHub.Client/UI/Chat/WelcomeBanner.cs` +> **Kind:** class + +```csharp +internal static class WelcomeBanner +``` + + +Renders a MOTD-style splash in the chat pane when no channel is selected — a gold-gradient ASCII logo accompanied by a version tagline and quick usage hints, evoking classic IRC greetings. Use WelcomeBanner.Build to generate the banner lines for a given viewport width and version string, then feed those lines into the chat UI. + +## Remarks +WelcomeBanner encapsulates the presentation of the welcome banner: centering, padding, colorization, and the two-logo strategy are all handled here so the rest of the chat UI can simply render a sequence of lines. It selects between a full-width BigLogo and a compact SmallLogo based on the viewport width, scales the gradient across the chosen logo, and appends a version tagline plus a set of user hints. This keeps branding consistent across sizes and isolates banner-specific formatting from the broader rendering pipeline. + +## Example +```csharp +var lines = WelcomeBanner.Build(80, "1.2.3"); +// integrate 'lines' into the chat pane +``` + +## Notes +- The logo variant is chosen based on the provided width; very small panes will display SmallLogo to preserve legibility. +- The color attributes (Attributes on ChatSegment) require UI support in the chat renderer; without color support the banner falls back to plain text. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs.md new file mode 100644 index 0000000..51ada2a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs.md @@ -0,0 +1,23 @@ +# AudioPlayerDialog + +> **File:** `src/EchoHub.Client/UI/Dialogs/AudioPlayerDialog.cs` +> **Kind:** class + +```csharp +public sealed class AudioPlayerDialog +``` + + +AudioPlayerDialog is a sealed class that presents a modal Audio Player UI within the application's terminal UI. It assembles a compact layout with the current file name, a wave-like block visualization, playback status, and simple volume and playback controls, all exposed via a single Show method that binds an IApplication and an AudioPlaybackService to the dialog's lifecycle. + +## Remarks +By encapsulating layout, colors, and animation in one place, it provides a reusable, cohesive UX for audio playback that can be dropped into different screens without duplicating UI code. The class relies on themed attributes (e.g. WaveActiveAttr, WaveIdleAttr, FileNameAttr, Status*Attr) to ensure consistent appearance, and uses a timer-driven animation loop to render the wave pattern while playback is active. + +## Example +```csharp +AudioPlayerDialog.Show(app, audioService, "/path/to/song.mp3", "song.mp3"); +``` + +## Notes +- The waveform visualization uses Unicode block characters; ensure your terminal font supports these glyphs for correct rendering. +- The dialog starts a background animation timer; dispose the dialog or stop the timer to avoid leaks when closing. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs.md new file mode 100644 index 0000000..72cc64a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs.md @@ -0,0 +1,23 @@ +# ChannelPasswordDialog + +> **File:** `src/EchoHub.Client/UI/Dialogs/ChannelPasswordDialog.cs` +> **Kind:** class + +```csharp +public sealed class ChannelPasswordDialog +``` + + +Prompts for a channel password when joining a protected channel and returns the entered password, or null if the user cancels. Use this helper whenever you need a consistent, modal password prompt instead of duplicating dialog boilerplate across join flows. + +## Remarks +This class centralizes the user flow for joining password-protected channels. It presents a modal dialog titled Join #, collects the password, and returns it to the caller, ensuring a single, predictable contract. The UI avoids displaying the actual password text by using a redacted caption and automatically focusing the password field, while the dialog lifecycle is orchestrated through the application (app.Run and app.RequestStop). + +## Example +```csharp +string? password = ChannelPasswordDialog.Show(app, "mychannel", "Enter password to join #mychannel."); +``` + +## Notes +- The method is synchronous and modal; it blocks the caller until the user completes the interaction. +- A null return value indicates the user canceled the operation. If the user submits an empty password, a brief error dialog is shown and the prompt remains active until a non-empty password is provided. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md new file mode 100644 index 0000000..2786e8b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md @@ -0,0 +1,80 @@ +# ConnectDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs` + +## Contents + +- [ConnectDialog](#connectdialog) +- [ConnectDialogResult](#connectdialogresult) + +--- + +## ConnectDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs` +> **Kind:** class + +```csharp +public sealed class ConnectDialog +``` + + +ConnectDialog is a Terminal.Gui-based dialog that collects server connection details and authentication information for the application. When shown, it can display a list of SavedServer entries at the top if any saved servers are provided; in that case a Saved Servers section is rendered with a ListView of display names that indicate whether a session exists (the code appends a [session] marker when a RefreshToken is present). Below (or in place of it, when there are no saved servers), the dialog presents manual entry fields for Server URL (default http://localhost:5000), Username, and Password, along with UI hints such as a hidden password placeholder and a Remember me option. Additional fields include Display Name and, when relevant, an Invite Code for invite-gated registrations. The static Show method returns a ConnectDialogResult when the user completes the dialog, or null if the dialog is cancelled; the dialog height is adjusted depending on whether saved servers are shown. + +--- + +## ConnectDialogResult +> **File:** `src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs` +> **Kind:** record + +```csharp +public record ConnectDialogResult( + string ServerUrl, string Username, string Password, + bool IsRegister, bool RememberMe, string? SavedRefreshToken, + string? DisplayName = null, string? InviteCode = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ServerUrl` | `string` | — | +| `Username` | `string` | — | +| `Password` | `string` | — | +| `IsRegister` | `bool` | — | +| `RememberMe` | `bool` | — | +| `SavedRefreshToken` | `string?` | — | +| `DisplayName` | `string?` | `null` | +| [`InviteCode`](../../../EchoHub.Core/Models/InviteCode.cs.md) | `string?` | `null` | + + +ConnectDialogResult encapsulates all user input gathered from the connect dialog as a single, immutable value. It is produced when the dialog completes and is consumed by the rest of the application to initiate a connection flow, passing the server URL, credentials, and onboarding flags as a single, strongly-typed package. + +## Remarks + +By collecting all related fields into a single record, this abstraction reduces coupling between the UI layer and the connection logic. It clearly expresses the intent of the user's action (login vs register) and whether credentials should be remembered, while allowing optional data (DisplayName, InviteCode) to participate in specialized flows without forcing callers to thread every field separately. + +## Example + +```csharp +// Common usage: construct a result from values collected in UI +var result = new ConnectDialogResult( + ServerUrl: "https://example.server/api", + Username: "alice", + Password: "P@ssw0rd", + IsRegister: false, + RememberMe: true, + SavedRefreshToken: null, + DisplayName: "Alice", + InviteCode: "INVITE-2024-ABCD" +); +``` + +## Notes + +- DisplayName and InviteCode are nullable; omit them or pass null if not applicable. +- Password should be treated as sensitive data: avoid logging it or persisting it longer than necessary, and ensure proper disposal or clearing after use. +- SavedRefreshToken may be null; handle accordingly in login/refresh flows. +- This record is intended for in-memory transfer between UI and authentication/connection logic; when persisting or transmitting, apply appropriate security measures and avoid leaking confidential fields. + + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md new file mode 100644 index 0000000..5c5d48d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs.md @@ -0,0 +1,74 @@ +# CreateChannelDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs` + +## Contents + +- [CreateChannelDialog](#createchanneldialog) +- [CreateChannelResult](#createchannelresult) + +--- + +## CreateChannelDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs` +> **Kind:** class + +```csharp +public sealed class CreateChannelDialog +``` + + +Displays a modal Create Channel dialog that collects the details needed to create a new channel: a name, an optional topic, a password, and a public visibility setting. The name is trimmed and normalized to lower case; if it is empty, the dialog reports an error and stays open. On Create, it builds a CreateChannelResult containing the name, topic (nullable), isPublic, and the password; on Cancel it returns null. The dialog runs via the provided IApplication instance and returns after the user makes a choice. + +## Remarks +Encapsulates all UI logic for channel creation into a single entry point, enabling consistent behavior across the app and isolating rendering from business logic. The class acts as a small, self-contained UX widget that constructs the result object, ensuring callers need only handle the CreateChannelResult or null. + +## Notes +- Name validation is minimal in code: the name is trimmed and lowercased, and non-empty; there is no explicit enforcement of length or allowed character patterns at runtime beyond what the UI hints suggest. +- Password handling appears behind-the-scenes (the UI labels redact the password, yet the password value is captured and returned as part of the result); ensure secure handling and minimize exposure of the plaintext password. +- The snippet references passwordField and publicCheckbox, which must exist in the full class scope; if you modify the UI composition, ensure these controls are present and wired consistently with the password retrieval and public visibility logic. + +--- + +## CreateChannelResult +> **File:** `src/EchoHub.Client/UI/Dialogs/CreateChannelDialog.cs` +> **Kind:** record + +```csharp +public record CreateChannelResult(string Name, string? Topic, bool IsPublic, string? Password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Name` | `string` | — | +| `Topic` | `string?` | — | +| `IsPublic` | `bool` | — | +| `Password` | `string?` | — | + + +CreateChannelResult is an immutable data carrier that represents the outcome of creating a channel in the EchoHub client UI. It carries the channel's Name, an optional Topic, a flag IsPublic indicating whether the channel is public, and an optional Password. + +## Remarks +As a record, CreateChannelResult participates in value-based equality, making comparisons straightforward without manual field checks. The positional constructor provides a concise, immutable payload that is easy to pass through layers (UI, services, or view models). You can deconstruct a result into its components, or derive a modified copy with a with-expression if you need a slightly different result without mutating the original. This type is intended to be produced by the channel-creation flow and consumed by UI code and downstream components. + +## Example +```csharp +// Common case: create a public channel with a topic and password +var result = new CreateChannelResult("General", "Team discussions", true, "s3cr3t"); + +// Access fields +string name = result.Name; +string? topic = result.Topic; +bool isPublic = result.IsPublic; +string? password = result.Password; + +// Deconstruct for convenience +var (n, t, pub, pwd) = result; + +// Create a modified copy +var updated = result with { Topic = "New topic" }; +``` + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md new file mode 100644 index 0000000..bc438d4 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs.md @@ -0,0 +1,64 @@ +# ProfileEditDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs` + +## Contents + +- [ProfileEditDialog](#profileeditdialog) +- [ProfileEditResult](#profileeditresult) + +--- + +## ProfileEditDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs` +> **Kind:** class + +```csharp +public sealed class ProfileEditDialog +``` + + +ProfileEditDialog provides a Terminal.Gui dialog for editing the user's profile. Its Show method presents a modal dialog titled "Edit Profile" with fields for Display Name, Bio, Nickname Color (with a hex input and a live color preview) and Avatar selection, plus notification preferences, returning a ProfileEditResult when the user accepts or null if cancelled. + +## Remarks +ProfileEditDialog centralizes profile-edit UI in one reusable component, ensuring a consistent look and behavior whenever the user updates their profile. It wires up real-time color previews by updating the color swatch whenever the hex input changes, and it delegates color parsing to HexColorHelper to translate user input into a Color value. The Avatar field demonstrates integration with a file picker (OpenDialog) within a Terminal.Gui workflow, keeping file selection cohesive with the rest of the dialog. + +## Notes +- The Show method accepts optional parameters for notificationSoundEnabled and notificationVolume, defaulting to false and 30 respectively. +- If no avatar is selected, avatarField.Text remains empty. +- The return type is ProfileEditResult?; callers should handle null to cover the cancel path. +- This implementation relies on Terminal.Gui primitives (Label, TextField, Button, CheckBox, OpenDialog) and collaborator types (ProfileEditResult, HexColorHelper); ensure these types are available in the consuming project. + +--- + +## ProfileEditResult +> **File:** `src/EchoHub.Client/UI/Dialogs/ProfileEditDialog.cs` +> **Kind:** record + +```csharp +public record ProfileEditResult(string? DisplayName, string? Bio, string? NicknameColor, string? AvatarPath, bool? NotificationSoundEnabled, byte? NotificationVolume) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `DisplayName` | `string?` | — | +| `Bio` | `string?` | — | +| `NicknameColor` | `string?` | — | +| `AvatarPath` | `string?` | — | +| `NotificationSoundEnabled` | `bool?` | — | +| `NotificationVolume` | `byte?` | — | + + +Represents the data returned from the profile edit dialog. It encapsulates the user\'s optional inputs for DisplayName, Bio, NicknameColor, AvatarPath, NotificationSoundEnabled, and NotificationVolume so the caller can apply changes in a single operation. Each property is nullable: a null value means no change for that field; a non-null value provides a new value to persist. + +## Remarks +ProfileEditResult is an immutable value object used as the dialog\'s return type. Its nullable fields express a delta: non-null values indicate updates, while null indicates no change. As a record, it benefits from value-based equality, making comparisons and tests straightforward, and it cleanly separates UI input from downstream update logic. + +## Notes +- Null values indicate no change; apply only non-null fields when updating the profile. +- The type is immutable; to derive modifications, use a with-expression to create a new instance. + + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md new file mode 100644 index 0000000..4b793ec --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs.md @@ -0,0 +1,51 @@ +# ProfileViewDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs` + +## Contents + +- [ProfileViewDialog](#profileviewdialog) +- [ProfileAction](#profileaction) + +--- + +## ProfileViewDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs` +> **Kind:** class + +```csharp +public sealed class ProfileViewDialog +``` + + +ProfileViewDialog renders a dialog to view a user's server profile; when showing the current user's profile it also exposes action buttons (Edit Profile / Set Status) and returns the chosen ProfileAction, while viewing another user yields a read-only presentation. + +## Remarks +ProfileViewDialog encapsulates all the layout and formatting decisions for a user profile in a single place. It dynamically switches between a read-only view and an ownership-aware view that surfaces actions, and it applies color theming to the status and nickname fields. By centralizing this UI behavior, the dialog remains consistent across the application and reduces duplication by isolating profile presentation from business logic. The component gracefully handles a missing profile by showing an error message and returning a Close action, which defines a clear contract for callers. + +## Notes +- If invoked with a null profile, the dialog shows an error and returns ProfileAction.Close; callers should guard against null input or handle the Close result accordingly. +- The dialog title differentiates ownership with "My Profile" for the current user and "Profile — {username}" for others, and it uses color-coding helpers to reflect status and nickname color for quick visual cues. + +--- + +## ProfileAction +> **File:** `src/EchoHub.Client/UI/Dialogs/ProfileViewDialog.cs` +> **Kind:** enum + +```csharp +public enum ProfileAction +{ + Close, + EditProfile, + SetStatus +} +``` + + +ProfileAction defines the set of actions a user can select from their profile dialog: Close, EditProfile, and SetStatus. It provides a typed representation of user intent that downstream UI logic can handle in a deterministic way, rather than relying on magic strings or numeric codes. + +## Remarks +ProfileAction represents the user’s chosen action from the profile dialog, allowing the UI layer to dispatch the appropriate workflow in a type-safe way. By enumerating possible intents, the code can exhaustively handle all cases in a switch or pattern-match, reducing errors from invalid values. The Close action also clarifies that the action is about dialog lifecycle control as opposed to in-dialog tasks such as editing or setting status. If new actions are required in the future, they should be added here with clear naming that maps to corresponding UI behaviors. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md new file mode 100644 index 0000000..1e62513 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/SearchDialog.cs.md @@ -0,0 +1,94 @@ +# SearchDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` + +## Contents + +- [SearchDialog](#searchdialog) +- [SearchResult](#searchresult) +- [SearchResultType](#searchresulttype) + +--- + +## SearchDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +> **Kind:** class + +```csharp +public static class SearchDialog +``` + + +SearchDialog is a command-palette style search dialog used to quickly navigate channels and trigger common app actions from a single, keyboard-driven interface. Use it when you want fast, non-mouse access to channels and actions by filtering a combined list and selecting with Enter. + +## Remarks +SearchDialog composes a modal dialog that presents both channel names and a predefined set of actions, merged into a single searchable list via a SearchListSource. It returns the selected SearchResult and signals completion to the hosting application by invoking RequestStop on IApplication, keeping the dialog logic decoupled from the rest of the UI. This abstraction enables a reusable, consistent navigation surface across different parts of the app. + +## Example +```csharp +// Example +IApplication app = /* obtain your app instance */; +IReadOnlyList channels = new[] { "general", "engineering" }; +var result = SearchDialog.Show(app, channels); +if (result != null) +{ + // Handle the selected item (channel or action) here. +} +``` + +## Notes +- The dialog includes a hint, a text field for filtering, a list of results, and a Cancel button; selection is returned as a SearchResult, or null if cancelled. +- Ctrl+K handling in both the dialog and the search field cancels the operation by requesting stop from the application, so be aware that this combo acts as a cancel gesture rather than an open/search trigger. +- When items exist, the first item is pre-selected; filtering updates the source and may reset the selection. + + +--- + +## SearchResult +> **File:** `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +> **Kind:** record + +```csharp +public record SearchResult(SearchResultType Type, string Key, string Label) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Type` | `SearchResultType` | — | +| `Key` | `string` | — | +| `Label` | `string` | — | + + +Represents a single entry in search results, encapsulating the result's category (Type), a key (Key), and a user-facing label (Label). As a positional-record, it is immutable and compared by value, which makes it convenient to pass around and render in the search UI. + +## Remarks +Use SearchResult to model a single outcome returned by the search feature. Type communicates the kind of item (as defined by SearchResultType), Key is the stable identifier for navigation or lookup, and Label is the display text shown in the results list. Because it is a deconstructible record, you can conveniently extract its fields with deconstruction or pattern matching, and equality checks are based on the content rather than the instance identity. + +## Notes +- Immutability: SearchResult uses a primary constructor; properties are read-only and a modified instance must be created with a with-expression or a new constructor. +- Deconstruction: The positional constructor enables deconstruction: var (t, k, l) = result; or access via result.Type, result.Key, result.Label. +- Type relies on the SearchResultType enum; when consuming code, prefer switching on Type rather than comparing display strings. + +--- + +## SearchResultType +> **File:** `src/EchoHub.Client/UI/Dialogs/SearchDialog.cs` +> **Kind:** enum + +```csharp +public enum SearchResultType +{ + Channel, + Action +} +``` + + +Represents the category of a search result in the EchoHub client UI, distinguishing Channel results from Action results. Developers reach for this enum to branch rendering or navigation logic based on the result type, instead of using boolean flags or string comparisons. + +## Remarks +Because it is a small discriminant, SearchResultType is typically consumed alongside a broader SearchResult structure. It enables simple pattern matching in switch expressions or if statements, guiding UI decisions such as which view to open or which icon to display when a user selects a result. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md new file mode 100644 index 0000000..944d92a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/StatusDialog.cs.md @@ -0,0 +1,69 @@ +# StatusDialog.cs + +> **Source:** `src/EchoHub.Client/UI/Dialogs/StatusDialog.cs` + +## Contents + +- [StatusDialog](#statusdialog) +- [StatusDialogResult](#statusdialogresult) + +--- + +## StatusDialog +> **File:** `src/EchoHub.Client/UI/Dialogs/StatusDialog.cs` +> **Kind:** class + +```csharp +public sealed class StatusDialog +``` + + +StatusDialog is a terminal-based UI component that presents a compact dialog for updating the current user's status and an optional status message. Its Show method renders the dialog initialized with the provided current status and message, and returns a StatusDialogResult when the user saves, or null if the user cancels. + +The dialog consists of a title 'Set Status', a status option selector pre-populated with the current status, a text field for the status message, and Save/Cancel actions. On Save, the selected status is captured (defaulting to Online if nothing is selected) and the message is trimmed; an empty message becomes null. The method returns a new StatusDialogResult with those values and stops the application loop via app.RequestStop(); Cancel returns null and stops the loop. + +Callers use the returned result to apply the updated status and message; otherwise, no changes are made. + +## Remarks +StatusDialog encapsulates the presentation logic for updating user status, isolating UI concerns from business logic. It is a small, reusable piece that orchestrates Terminal.Gui controls (Dialog, Label, OptionSelector, TextField, Button) and relies on IApplication to drive the modal flow. The use of a default Online and trimming of the message ensures sane behavior even when fields are left blank. + +## Example +```csharp +var result = StatusDialog.Show(app, currentStatus, currentMessage); +if (result != null) +{ + // Apply updates to the user's status and message + currentStatus = result.Status; + currentMessage = result.Message; +} +``` + +## Notes +- A null result indicates the user cancelled the dialog; callers should guard against applying changes in this case. +- If the user leaves the Message field blank or whitespace, the message is stored as null. +- The Save action is wired as the default action (IsDefault = true), and both Save and Cancel terminate the modal interaction by invoking app.RequestStop(). + +--- + +## StatusDialogResult +> **File:** `src/EchoHub.Client/UI/Dialogs/StatusDialog.cs` +> **Kind:** record + +```csharp +public record StatusDialogResult(UserStatus Status, string? StatusMessage) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Status` | [`UserStatus`](../../../EchoHub.Core/Models/UserStatus.cs.md) | — | +| `StatusMessage` | `string?` | — | + + +StatusDialogResult is a minimal, immutable data carrier returned when the status dialog completes. It groups the chosen user status (Status) with an optional message (StatusMessage) into a single value that downstream logic can consume without inspecting the dialog UI directly. As a C# record, it benefits from value-based equality and straightforward deconstruction. + +## Remarks +StatusDialogResult encapsulates the outcome of a UI interaction into a single semantic unit that can be passed through the application flow or stored for auditing. It separates presentation concerns from business logic: callers reason about the user's status and optional message rather than UI details. The nullable StatusMessage signals that extra context is optional; consumer code should handle the absence gracefully, typically by pattern matching on Status and checking for a non-null message. The record type also supports structural equality, making tests and comparisons concise. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs.md new file mode 100644 index 0000000..e4e4dc6 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs.md @@ -0,0 +1,14 @@ +# UpdateConfirmDialog + +> **File:** `src/EchoHub.Client/UI/Dialogs/UpdateConfirmDialog.cs` +> **Kind:** class + +```csharp +public sealed class UpdateConfirmDialog +``` + + +UpdateConfirmDialog is a sealed utility with a single static Show method that prompts the user to confirm an available update. It builds a small modal dialog titled “Update Available” showing the current and latest versions and offers two actions: Update (default) and Cancel; it returns true if the user chooses Update and false otherwise. The method runs the provided IApplication until the user makes a choice, using RequestStop to close the dialog and return the result. + +## Remarks +It encapsulates the update-confirmation interaction as a reusable, modal prompt that coordinates with the host application's event loop, avoiding duplication of dialog boilerplate across the codebase. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs.md new file mode 100644 index 0000000..5208c38 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs.md @@ -0,0 +1,28 @@ +# DroppedFileParser + +> **File:** `src/EchoHub.Client/UI/Helpers/DroppedFileParser.cs` +> **Kind:** class + +```csharp +public static class DroppedFileParser +``` + + +DroppedFileParser is a small utility that interprets terminal-dropped input as potential file paths and resolves them to existing files. Use it when you need to convert user-typed or pasted text into concrete file paths without scattering filesystem checks across callers. + +## Remarks +This abstraction centralizes the logic for recognizing path-like input and for extracting one or more existing file paths from either a single path or a space-separated list of paths. It exposes a fast pre-check (LooksLikePath) to avoid expensive filesystem calls for clearly non-path input, and a test-friendly parser (TryGetFiles) that can inject a custom file existence predicate. The design favors explicit handling of both Windows (drive letters and UNC) and POSIX-style absolute paths, including quoted components and spaces. + +## Example +```csharp +var input = "\"C:\\Temp\\report.pdf\" C:\\Data\\log.txt"; +if (DroppedFileParser.TryGetFiles(input, out var files)) +{ + // files contains: ["C:\\Temp\\report.pdf", "C:\\Data\\log.txt"] +} +``` + +## Notes +- LookSLikePath may return true for strings that resemble paths (e.g., starting with a quote, a slash, UNC prefix, or a drive letter), so TryGetFiles should be used to confirm actual file existence. +- TryGetFiles enforces that all tokens are fully-qualified paths and that each path exists (via the injectable fileExists predicate, which defaults to File.Exists). This reduces accidental assumptions about the input. +- The tokenization logic respects quoted segments so that spaces within a single path do not split tokens unintentionally. diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/EmojiHelper.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/EmojiHelper.cs.md new file mode 100644 index 0000000..8c286fd --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/EmojiHelper.cs.md @@ -0,0 +1,19 @@ +# EmojiHelper + +> **File:** `src/EchoHub.Client/UI/Helpers/EmojiHelper.cs` +> **Kind:** class + +```csharp +public static class EmojiHelper +``` + + +EmojiHelper converts emoji grapheme clusters to text shortcodes for safe TUI rendering. It replaces emoji with fixed-width ASCII shortcodes when available, falling back to a generic [emoji] placeholder for unknown symbols; non-emoji text passes through unchanged. + +## Remarks + +This utility uses grapheme-aware processing to handle complex emoji sequences (including ZWJ-joined glyphs and modifier-bearing emojis) by iterating over text elements rather than individual code points. It first attempts a full-grapheme shortcode lookup, then falls back to the base emoji (the first rune of the grapheme) if necessary, and finally uses the [emoji] placeholder when no mapping exists. An initial pass quickly determines whether any emoji exist in the input to avoid unnecessary work. The implementation relies on StringBuilder for efficient string construction, StringInfo for grapheme segmentation, and the EmojiShortcodes mapping as the source of truth for replacements. + +## Notes + +- Unknown or unmapped emoji are replaced with [emoji], which can reduce expressiveness if the shortcode dictionary is incomplete. Ensure EmojiShortcodes covers the emoji you expect to render in your UI. diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/HexColorHelper.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/HexColorHelper.cs.md new file mode 100644 index 0000000..f79d7a8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/HexColorHelper.cs.md @@ -0,0 +1,18 @@ +# HexColorHelper + +> **File:** `src/EchoHub.Client/UI/Helpers/HexColorHelper.cs` +> **Kind:** class + +```csharp +public static class HexColorHelper +``` + + +HexColorHelper is a small utility that converts hex color strings into Terminal.Gui coloring primitives. Use ParseHexColor to obtain an Attribute suitable for styling a control's foreground, and ParseHexToColor when you need a Color value with a safe fallback for invalid input. + +## Remarks +By centralizing hex parsing, HexColorHelper avoids duplicating color-conversion logic and provides predictable fallbacks for malformed input. It interprets a hex string as an RGB triplet and applies it as the foreground color (with no explicit background). This keeps styling decisions consistent across the UI while keeping the parsing logic isolated in one place. + +## Notes +- Invalid input yields null (for ParseHexColor) or the provided fallback (for ParseHexToColor); no exceptions are thrown. +- A 6-digit hex value is required after an optional leading '#'. Non-hex characters or incorrect length return fallback/null. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/NickColorHelper.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/NickColorHelper.cs.md new file mode 100644 index 0000000..dcbf733 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/Helpers/NickColorHelper.cs.md @@ -0,0 +1,25 @@ +# NickColorHelper + +> **File:** `src/EchoHub.Client/UI/Helpers/NickColorHelper.cs` +> **Kind:** class + +```csharp +public static class NickColorHelper +``` + + +NickColorHelper deterministically assigns a stable color to every nickname, ensuring the same nick always maps to the same palette entry. This mirrors classic IRC behavior and lets busy channels stay readable without per-user configuration. + +## Remarks +NickColorHelper isolates color selection from rendering logic by exposing a pure function GetPaletteIndex and GetAttribute. The palette itself is a fixed sequence of medium-saturation colors designed for legibility on both dark and light backgrounds; changing the palette order would re-color every nick and break visual consistency across sessions. + +## Example +```csharp +var color = NickColorHelper.GetAttribute("Alice"); +// Use `color` when rendering Alice's username in the UI +``` + +## Notes +- Null nick will throw; ensure non-null before calling GetPaletteIndex. +- The palette order is fixed; reordering or removing entries changes every nickname's color. +- The mapping uses a case-insensitive FNV-1a hash; changing the hash or its normalization will alter which nick gets which color. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/ChannelListSource.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/ChannelListSource.cs.md new file mode 100644 index 0000000..3aaa4ec --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/ChannelListSource.cs.md @@ -0,0 +1,21 @@ +# ChannelListSource + +> **File:** `src/EchoHub.Client/UI/ListSources/ChannelListSource.cs` +> **Kind:** class + +```csharp +public class ChannelListSource : IListDataSource +``` + + +A colored, list-backed IListDataSource that presents channel names with visual affordances: an active-channel indicator, unread count badges, and markers for protected, private and system channels. Use this when you need a ListView-compatible data source that maintains channel ordering, per-channel unread counts and simple visual state (active, mention, protected/private, system) instead of hand-rendering each row. + +## Remarks +ChannelListSource centralizes the channel-list state required by a ListView: the ordered channel names, a per-channel unread count map and several role sets (protected, mention, private and system). It exposes a single Update method that replaces the in-memory collections in one operation and (unless suspended) raises a Reset collection-changed event so consumers can re-layout or refresh. The class also provides MaxItemLength to help the host compute layout and ToList to produce a display-friendly list of channel strings (each prefixed with '#'). Rendering is delegated to the ListView via the Render method; the class supplies attributes (ActiveAttr, UnreadAttr, NormalAttr, BadgeAttr, MentionAttr, SystemAttr) and simple prefix/marker rules so the view paints active items, unread badges and visual separation for system channels. + +## Notes +- Update clears and replaces all internal collections; call it with the full desired state rather than trying to patch individual entries. +- The Count/MaxItemLength values are derived from the current channel list. MaxItemLength computes name.Length + 6 (reserved space for prefixes/badges), so layout logic should consider that padding when sizing the list column. +- CollectionChanged will be invoked with a NotifyCollectionChangedAction.Reset at the end of Update unless SuspendCollectionChangedEvent is true. SuspendCollectionChangedEvent is a simple in-memory flag — using it prevents the Reset event from being raised during an Update. +- IsMarked and SetMark are intentionally inert (IsMarked always returns false and SetMark is a no-op), so callers should not rely on marking support from this source. +- Render moves the ListView cursor using Math.Max(col - viewportX, 0) to account for horizontal scrolling (viewportX). Hosts should provide correct viewportX and width values so rendering and clipping behave as intended. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md new file mode 100644 index 0000000..c41bb89 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/SearchListSource.cs.md @@ -0,0 +1,22 @@ +# SearchListSource + +> **File:** `src/EchoHub.Client/UI/ListSources/SearchListSource.cs` +> **Kind:** class + +```csharp +public class SearchListSource(List items) : IListDataSource +``` + + +List data source that feeds a search dialog's ListView: it maintains an original item list, supports case-insensitive filtering by label or key, raises a Reset collection-changed notification when the filter changes (unless suspended), and renders each row with color-coding depending on the SearchResultType. + +## Remarks +This class combines two responsibilities commonly needed by a search dialog: fast, in-memory filtering of a fixed set of SearchResult records and rendering of those results into a ListView with per-type coloring. Consumers attach to CollectionChanged to refresh the UI when Filter(string) updates the visible set. Render uses RenderHelpers.WriteText to draw the label and then fills the remainder of the column; it chooses a highlight (selected) attribute from the ListView or a per-result attribute (channel/action) and preserves the list's background when a per-result attribute leaves the background as Color.None. + +## Notes +- Filter is case-insensitive and matches either SearchResult.Label or SearchResult.Key. +- When Filter receives a null/whitespace query the visible list is reset to all items and a Reset event is raised (unless SuspendCollectionChangedEvent is true). +- IsMarked and SetMark are no-ops; this data source does not track per-item marks. +- Dispose is a no-op; there are no unmanaged resources to release. +- MaxItemLength returns 0 when there are no filtered items. +- This class does not provide internal synchronization; callers should ensure thread-safety when mutating the source list or calling Filter from multiple threads. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/UserListSource.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/UserListSource.cs.md new file mode 100644 index 0000000..a42c501 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/ListSources/UserListSource.cs.md @@ -0,0 +1,21 @@ +# UserListSource + +> **File:** `src/EchoHub.Client/UI/ListSources/UserListSource.cs` +> **Kind:** class + +```csharp +public class UserListSource : IListDataSource +``` + + +A data source implementation for a list view that presents online users with per-user nickname colors. Use this when you need a ready-made IListDataSource that holds tuples of display text, an optional nickname color (Attribute), and the username; it supplies item count, a maximal item width, batch updates via Update, and a Render implementation that paints a status/prefix in the normal role and the username portion in the configured nickname color while respecting selection and a fixed column width. + +## Remarks +UserListSource is a UI-focused data source: it couples a small in-memory collection of user display tuples with a Render method tailored for a ListView consumer. It delegates grapheme-aware splitting to GraphemeHelper so prefix characters (status icon and optional role badge) are drawn in the list's normal attribute while the visible username text is drawn in the per-user nickname color unless the item is selected (selection forces the normal/Focus attribute). MaxItemLength is maintained as a convenience for layout calculations and is updated by Update. + +## Notes +- Update replaces the entire contents; after calling Update the class raises NotifyCollectionChangedAction.Reset unless SuspendCollectionChangedEvent is true. If you set SuspendCollectionChangedEvent to batch multiple updates you are responsible for raising/triggering an appropriate collection changed notification afterward. +- MaxItemLength is computed using each entry's Text.GetColumns(), so wide characters and grapheme clusters affect reported width — MaxItemLength is a column/terminal-width measure, not a character count. +- Rendering is grapheme-aware and respects the provided width: text drawing stops when the accumulated column width reaches the requested width. This prevents partial grapheme rendering but means long names will be truncated to fit. +- Several IListDataSource members are intentionally trivial: IsMarked and SetMark are no-ops, ToList returns the visible Text values as objects, and Dispose is a no-op. Callers should not rely on any persistent marking or disposal behavior from this class. +- The implementation contains no internal synchronization; it is not inherently thread-safe. Ensure all access (especially Update and Render) is serialized by the caller when used from multiple threads. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Client/UI/MainWindow.cs.md b/docs/auriondocs/Code/src/EchoHub.Client/UI/MainWindow.cs.md new file mode 100644 index 0000000..3da952b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Client/UI/MainWindow.cs.md @@ -0,0 +1,2080 @@ +# MainWindow.cs + +> **Source:** `src/EchoHub.Client/UI/MainWindow.cs` + +## Contents + +- [MainWindow](#mainwindow) + - [MainWindow (constructor)](#mainwindow-constructor) + - [CurrentChannel](#currentchannel) + - [HasPendingReplyIndicator](#haspendingreplyindicator) + - [IsCurrentChannelReadOnly](#iscurrentchannelreadonly) + - [IsTransitionalStatus](#istransitionalstatus) + - [ApplyColorSchemes](#applycolorschemes) + - [BuildMenuBar](#buildmenubar) + - [ClearAll](#clearall) + - [ConfirmDeleteMessage](#confirmdeletemessage) + - [CopyToClipboard](#copytoclipboard) + - [EnsureChannelInList](#ensurechannelinlist) + - [ExpandRule](#expandrule) + - [FocusInput](#focusinput) + - [FocusMessageList](#focusmessagelist) + - [GetChannelNames](#getchannelnames) + - [GuardedClipboardAction](#guardedclipboardaction) + - [MentionUser](#mentionuser) + - [OnChannelListSelectionChanged](#onchannellistselectionchanged) + - [OnChatViewportChanged](#onchatviewportchanged) + - [OnHistoryPrepended](#onhistoryprepended) + - [OnInputContentsChanged](#oninputcontentschanged) + - [OnInputKeyDown](#oninputkeydown) + - [OnMessageListAccepting](#onmessagelistaccepting) + - [OnMessageListKeyDown](#onmessagelistkeydown) + - [OnMessageListMouseEvent](#onmessagelistmouseevent) + - [OnMessageListVerticalScrollBarScrolled](#onmessagelistverticalscrollbarscrolled) + - [OnMessagesChanged](#onmessageschanged) + - [OnStatusBarDrawContent](#onstatusbardrawcontent) + - [OnUsersListAccepting](#onuserslistaccepting) + - [OnWindowKeyDown](#onwindowkeydown) + - [RefreshChannelList](#refreshchannellist) + - [RefreshMenuBar](#refreshmenubar) + - [RefreshMessages](#refreshmessages) + - [RemoveChannel](#removechannel) + - [ScrollToMessage](#scrolltomessage) + - [SetChannelTopic](#setchanneltopic) + - [SetChannels](#setchannels) + - [SetCurrentUser](#setcurrentuser) + - [SetReplyingTo](#setreplyingto) + - [SetStagedAttachments](#setstagedattachments) + - [ShowError](#showerror) + - [ShowMessageContextMenu](#showmessagecontextmenu) + - [ShowSearchDialog](#showsearchdialog) + - [StageFiles](#stagefiles) + - [SwitchToChannel](#switchtochannel) + - [ToggleUsersPanel](#toggleuserspanel) + - [TryAutocompleteCommand](#tryautocompletecommand) + - [UpdateInputReadOnly](#updateinputreadonly) + - [UpdateInputTitle](#updateinputtitle) + - [UpdateLayout](#updatelayout) + - [UpdateOnlineUsers](#updateonlineusers) + - [UpdateSpinner](#updatespinner) + - [UpdateStatusBar](#updatestatusbar) + - [UpdateTopicBar](#updatetopicbar) + - [AltQKey](#altqkey) + - [CtrlCKey](#ctrlckey) + - [CtrlVKey](#ctrlvkey) + - [CtrlXKey](#ctrlxkey) + - [CtrlYKey](#ctrlykey) + - [EnterKey](#enterkey) + - [F2Key](#f2key) + - [SlashCommands](#slashcommands) + - [SpinnerFrames](#spinnerframes) + - [StatusActivityAttr](#statusactivityattr) + - [StatusBrandAttr](#statusbrandattr) + - [StatusConnectedAttr](#statusconnectedattr) + - [StatusDisconnectedAttr](#statusdisconnectedattr) + - [StatusMentionAttr](#statusmentionattr) + - [StatusTransitionalAttr](#statustransitionalattr) + - [TabKey](#tabkey) + - [UsersPanelWidth](#userspanelwidth) +- [ClickChannelRegex](#clickchannelregex) +- [ClickMentionRegex](#clickmentionregex) +- [AppVersion](#appversion) +- [CtrlKKey](#ctrlkkey) +- [DefaultInputTitle](#defaultinputtitle) +- [F6Key](#f6key) +- [NewlineKey](#newlinekey) + +--- + +## MainWindow +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** class + +```csharp +public sealed partial class MainWindow : Runnable +``` + + +Main Terminal.Gui window for the EchoHub chat client: composes channel list, message list, input field, status/topic labels, users panel and menu bar, and exposes events used by the application to react to user actions (channel selection, message submit, file/image paste, connect requests). Reach for this class when you need a ready-made, full-featured chat UI that integrates with an application orchestrator rather than building the UI pieces and event plumbing yourself. + +## Remarks +MainWindow encapsulates the Terminal.Gui controls and client-facing UI state for the chat client and acts as the bridge between user interactions and the application logic. It keeps local collections of channels, topics and metadata, hosts a ChatMessageManager for message lifecycle, and exposes a small set of events (OnChannelSelected, OnMessageSubmitted, OnFilesStaged, OnImagePasted, OnConnectRequested) so the rest of the app can respond to user actions without reaching into control internals. Key bindings are represented as KeyCode constants to allow straightforward switch/case handling of raw key codes. + +## Notes +- Key bindings are defined as raw KeyCode constants (e.g. EnterKey, CtrlKKey, F6Key). The code compares KeyCode values directly so handlers should compare against those constants rather than relying on Key.Equals semantics. +- The users panel defaults to visible and has a fixed width (UsersPanelWidth = 22). Toggle/resize behavior is managed internally by the window layout. +- SlashCommands contains the list of available client-side slash commands used for Tab autocomplete; update DefaultInputTitle if you change key bindings or common hints. +- File and image events convey concrete payloads: OnFilesStaged provides the channel plus absolute paths of existing files; OnImagePasted provides the channel plus PNG-encoded image bytes. Consumers should validate and process those payloads appropriately. + +--- + +### MainWindow (constructor) +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** constructor + +```csharp +public MainWindow(IApplication app, ChatMessageManager messageManager) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `app` | `IApplication` | — | +| `messageManager` | `ChatMessageManager` | — | + + +Initializes the main application window and assembles EchoHub’s client UI: a four-panel layout with a top menu bar, a left channels pane, a center chat area, a bottom input region, and a right online-users pane. It wires data sources to their views, subscribes to message and history events, binds selection and input handlers so the UI stays in sync with channel changes, and includes a small UX safeguard by rebinding Ctrl+W to delete-word-left to avoid clipboard exceptions. + +## Remarks +Serves as the UI composition root for the EchoHub client, carefully placing panels with fixed coordinates and dimensions to provide a stable, predictable layout across interactions. It connects ChannelListSource, ChatListSource, and UserListSource to their respective ListView controls, enabling efficient incremental rendering and per-item styling. Event wiring ensures the view updates reflect incoming messages, channel changes, and user activity without polluting business logic. The Ctrl+W rebound is a pragmatic, user-facing compatibility tweak that prevents clipboard-related crashes during text editing. + +## Notes +- Be mindful of unsubscribing event handlers if this window is ever disposed to avoid memory leaks. +- Layout relies on fixed panel dimensions; changing UsersPanelWidth or Y offsets could disrupt alignment. + +--- + +### CurrentChannel +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** property + +```csharp +public string CurrentChannel => _messageManager.CurrentChannel +``` + + +Get the name of the currently active channel by delegating to the underlying message manager via _messageManager.CurrentChannel. This read-only property provides a convenient, UI-friendly way to display or react to the active channel without coupling callers to the message manager. + +## Remarks +This property serves as a small abstraction that decouples the UI from the messaging subsystem. It simply forwards to the message manager, so changes in how the active channel is determined won't require changes at call sites. If the active channel can change over time, retrieve it as needed (e.g., for bindings or status displays) rather than caching the value. + +## Notes +- Read-only property; to change the channel, use the message manager's API rather than assigning to this property. If the channel value can be null, callers should handle null values appropriately. + +--- + +### HasPendingReplyIndicator +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** property + +```csharp +public bool HasPendingReplyIndicator => _replyTitleFragment is not null +``` + + +Indicates whether there is a pending reply by evaluating whether the private field `_replyTitleFragment` is non-null. Use this property when the UI or business logic needs to know if a reply is currently being prepared, without directly touching private fields. + +## Remarks + +By exposing the condition as a public property, callers express intent clearly—whether a reply is pending—without relying on the internal field’s exact name or lifecycle. It also centralizes the decision, so changes to the internal representation (for example, signaling a pending state with a different fragment) require updates only to this property. + +## Notes + +- The value reflects the internal condition at the moment of access; it may not guarantee that a UI indicator has already been rendered if the underlying state changes without notification. +- If `_replyTitleFragment` is updated from a background thread, ensure changes to the UI that depend on this property are observed on the appropriate UI thread to avoid threading issues. + +--- + +### IsCurrentChannelReadOnly +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** property + +```csharp +private bool IsCurrentChannelReadOnly => _systemChannels.Contains(_messageManager.CurrentChannel) +``` + + +IsCurrentChannelReadOnly is a read-only computed property that indicates whether the active channel is a system channel and should be treated as read-only in the UI. +It returns true when _systemChannels.Contains(_messageManager.CurrentChannel), and false otherwise, enabling UI logic to gate actions like message composition accordingly. + +## Remarks +IsCurrentChannelReadOnly centralizes the concept of a read-only channel, preventing scattered checks throughout the UI logic. It ties together the system-channel collection and the current channel reported by the message manager, ensuring consistent behavior whenever the active channel changes. + +## Notes +- The property is evaluated on access; callers should react to state changes (e.g., by refreshing the UI) to avoid presenting stale read-only state. + +--- + +### IsTransitionalStatus +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** property + +```csharp +private bool IsTransitionalStatus => _connectionStatus is not ("Connected" or "Disconnected") +``` + + +IsTransitionalStatus is a private boolean property that indicates whether the current internal connection status is not one of the stable terminal states 'Connected' or 'Disconnected'. It evaluates the underlying _connectionStatus and yields true for any other value, signaling a transitional or in-progress state (for example 'Connecting', 'Reconnecting', or similar custom statuses). + +## Remarks +By encapsulating this check, the class centralizes the notion of a transitional connection state and avoids repeating string comparisons across the UI logic. The predicate relies on the internal _connectionStatus field, so changes to how statuses are named or stored can be addressed in one place. This abstraction clarifies intent—code that reads IsTransitionalStatus expresses 'we are in flux' without caring about the exact status value. + +## Notes +- Null or unexpected _connectionStatus yields true; ensure initialization or guard against null. +- It uses exact string literals ('Connected' and 'Disconnected'); if localization or status naming changes, update accordingly. +- It is private; external components cannot rely on it. If you need external access, consider exposing a public wrapper or moving the logic to a shared utility. + +--- + +### ApplyColorSchemes +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void ApplyColorSchemes() +``` + +**Returns:** `void` + + +Applies the currently registered color schemes to all views and updates the UI to reflect the active theme. Call this after changing themes to refresh colors across the interface, ensuring base, menu, and border colors are propagated to the appropriate controls. + +## Remarks +Centralizes theming so color changes are applied consistently through a single call. It applies the base scheme to most subviews and intentionally excludes the menu bar and a few chrome labels that have their own styling. Border colors come from a separate border scheme if available, allowing borders to be tinted independently from text, while the menu-related chrome receives the menu scheme. + +## Notes +- Requires a non-null Base scheme to perform theming; otherwise the method performs no action. +- Border color updates occur only if a FrameView is encountered and a non-null border scheme is available; otherwise borders are left unchanged. +- Some subviews are excluded from the base scheme (the menu bar, status label, and topic label) and are updated via the menu scheme instead. + +--- + +### BuildMenuBar +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private MenuBar BuildMenuBar() +``` + +**Returns:** `MenuBar` + + +BuildMenuBar constructs the top-level MenuBar for EchoHub’s main window by assembling the File, Server, and User menus and a dynamic Theme submenu derived from ThemeManager. It wires user actions to corresponding events, conditionally includes a Rollback option when a backup exists, and always exposes update and quit actions; the returned bar is positioned at the origin and stretched to fill width, with a small mouse-handling workaround to ensure clicks target the menu items themselves. + +## Remarks + +It centralizes the composition of the app’s menu, guaranteeing a consistent structure and separator placement between groups. By drawing the theme options from ThemeManager.GetAvailableThemes and conditionally showing a backup rollback, the menu reflects runtime state without scattering logic across call sites. Each action is wired to an event or callback (OnThemeSelected, OnProfileRequested, OnCheckForUpdatesRequested, OnConnectRequested, etc.), making the symbol a single integration point for user interactions. The post-creation mouse-transparency hack fixes input handling in the CommandView so user clicks reliably hit the intended MenuBarItem. + +## Notes + +- The theme list is built from ThemeManager.GetAvailableThemes(); if it returns an empty collection, the Theme submenu will be effectively empty aside from any inserted separators. +- Actions like OnThemeSelected are invoked via null-conditional operators; ensure callers subscribe to handle the events. +- The mouse transparency workaround relies on internal subview types (MenuBarItem and CommandView) and may require adjustment if the UI framework changes. + +--- + +### ClearAll +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void ClearAll() +``` + +**Returns:** `void` + + +Clears all chat state and UI elements when disconnecting. It resets channel and topic collections, clears the message data, clears and rebinds the channel and user lists to empty sources, restores default frame titles, hides the topic label, and refreshes the message view to reflect an empty chat. + +## Remarks +Centralizes disconnect cleanup into a single method to guarantee a clean, predictable UI state between sessions. It coordinates multiple UI components and data stores (channel names, topics, channel groups, and the chat/users panes) so no stale data remains. Because it mutates UI elements, callers should ensure it runs on the UI thread to avoid cross-thread exceptions. + +## Notes +- This method mutates several UI elements and internal lists; call it only on disconnect to avoid partial state resets if used mid-session. + +--- + +### ConfirmDeleteMessage +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void ConfirmDeleteMessage(Guid messageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messageId` | `Guid` | — | + +**Returns:** `void` + + +This private helper displays a confirmation prompt when the user attempts to delete a message. It presents a dialog titled "Delete Message" with the prompt "Delete this message?" and two actions: a "Delete" button and a "Cancel" button. If the user confirms (the dialog returns 0), it raises the OnDeleteMessageRequested event, passing the provided messageId so the actual deletion logic can be executed by subscribers elsewhere. + +## Remarks +This method serves as the UI-facing contract for message deletion: it asks for user confirmation and, only upon explicit consent, notifies the rest of the system via OnDeleteMessageRequested. By delegating the actual deletion to subscribers, it remains agnostic of how messages are stored or removed, enabling different layers to handle the operation (e.g., in-memory vs. remote deletion) without duplicating the confirmation prompt. The method is private, indicating it is an internal implementation detail of the MainWindow and not part of the public API. + +## Notes +- The deletion work runs on the UI thread; long-running handlers should dispatch work to the background to avoid UI freezes. +- If there are no subscribers to OnDeleteMessageRequested, the delete operation will not run; ensure you subscribe to handle the deletion. + +--- + +### CopyToClipboard +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void CopyToClipboard(string text) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `text` | `string` | — | + +**Returns:** `void` + + +Copies the provided text to the application's clipboard by delegating to the clipboard interface when available. It calls TrySetClipboardData(text) on _app.Clipboard and swallows any exceptions, logging a warning instead of propagating errors to the caller. This makes clipboard operations a best-effort UI nicety that won't disrupt the user experience if the clipboard is unavailable or causes an exception. + +## Remarks + +This helper centralizes clipboard access and shields callers from clipboard-related failures. The use of the null-conditional operator on Clipboard prevents a hard failure when the clipboard is not present, and the surrounding try-catch ensures UI responsiveness by converting errors into lightweight warnings. In short, it provides a robust, non-blocking way to attempt copying text. + +## Notes + +- This method is best-effort: it never throws to callers; a failure is recorded in logs instead. +- If the application clipboard is unavailable (null or unsupported), the call simply does nothing. + +--- + +### EnsureChannelInList +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void EnsureChannelInList(string channelName, bool? isPublic = null, bool? isProtected = null, + bool? isSystem = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `isPublic` | `bool?` | `null` | +| `isProtected` | `bool?` | `null` | +| `isSystem` | `bool?` | `null` | + +**Returns:** `void` + + +Ensures a channel is present in the left-hand channel list, coordinating several internal collections that track channel visibility and categorization. This helper is typically used after joining a private channel (e.g., via /join) to guarantee the UI reflects the channel’s existence and attributes. By accepting nullable flags for isPublic, isProtected, and isSystem, callers can apply or adjust metadata without touching unrelated state; provided values are written to the corresponding in-memory structures and the UI is refreshed as needed. + +If the channel already exists, changes to isProtected or isSystem trigger a refresh of the channel list; if the channel is new, it is added to the list and the UI is refreshed. Note that updates to isPublic alone may modify internal mappings without causing a refresh in the existing-channel path. + +## Remarks +Centralizes the logic that coordinates multiple internal data structures: _channelNames, _channelPublic, _channelProtected, and _systemChannels. This reduces the risk of inconsistencies between the stored channel attributes and their presentation in the UI, especially for channels surfaced by /join. It also provides a single point of truth for how the left panel should react when a channel’s category or visibility changes. + +## Notes +- Only updates to isProtected or isSystem on an existing channel trigger a UI refresh; updates to isPublic alone may not refresh in that code path. +- This method mutates internal state and calls RefreshChannelList; call on the UI thread to avoid threading issues. +- Nullable flags allow partial updates; pass null to skip updating a given attribute. + +--- + +### ExpandRule +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private static ChatLine ExpandRule(ChatLine line, int width) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `line` | [`ChatLine`](Chat/ChatLine.cs.md) | — | +| `width` | `int` | — | + +**Returns:** [`ChatLine`](Chat/ChatLine.cs.md) + + +Re-generates a separator rule (date change / unread marker) to span the current viewport width: "── label ────────…". It builds a new ChatLine containing a single ChatSegment whose text is composed from a fixed decorative prefix, the rule label, and a tail of dashes whose length adapts to the provided width, then applies the line's color attribute (falling back to the default date rule color) and preserves the IsUnreadMarker flag from the source. + +## Remarks +This function centralizes the layout logic for date/unread separators in the chat UI, ensuring consistent visuals as the viewport changes. By deriving the tail length from the width and the label’s width, it maintains a balanced appearance that scales with available space and avoids clipping. Because it derives its color from the source line (or a sensible default), it remains visually cohesive with surrounding UI rules and respects the line’s unread state. + +## Example +```csharp +// Example usage: adapt a rule line to the current viewport width +// 'line' represents a ChatLine configured as a date/unread separator elsewhere in the codebase +ChatLine expanded = ExpandRule(line, 120); +``` + +## Notes +- The method assumes line.RuleLabel is non-null (the code uses line.RuleLabel!); if RuleLabel is null, a exception may be thrown at runtime. +- tailLen is clamped to a minimum of 2 to ensure a visible tail even on narrow widths. +- The returned ChatLine is a new instance; the input line is not mutated, preserving functional purity for rendering. + +--- + +### FocusInput +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void FocusInput() +``` + +**Returns:** `void` + + +FocusInput moves keyboard focus to the primary input field by delegating to the underlying input control's SetFocus method. Use this when you want to programmatically place the typing cursor into the main input, such as after the window is shown or after an action that should prepare for typing. + +## Remarks +This method centralizes focus behavior for the main window's input area, providing a single, discoverable point to direct user input. It abstracts away the details of how focus is delegated to the input control, making future UI changes easier to apply. Naming it FocusInput conveys intent clearly, improving readability wherever the UI needs to programmatically direct typing. + +--- + +### FocusMessageList +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void FocusMessageList() +``` + +**Returns:** `void` + + +Moves focus to the message list so keyboard users can navigate with arrow keys and delete messages with Delete. If nothing is selected, or if the current selection is out of range, the most recent message is selected. If the channel has no messages, this method is a no-op. After adjusting the selection, it focuses the list and requests a redraw to reflect the change. + +## Remarks +Centralizes the focus logic for the chat message list, ensuring predictable keyboard navigation and a consistent starting point for message management. It relies on the underlying ChatListSource's Count and the _messageList control to guard against invalid selections and to trigger a UI refresh. + +## Notes +- Intended to run on the UI thread since it manipulates UI controls. +- This is a private helper; external callers should not depend on its behavior beyond what the class exposes. + +--- + +### GetChannelNames +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public IReadOnlyList GetChannelNames() => _channelNames.AsReadOnly() +``` + +**Returns:** `IReadOnlyList` + + +Returns an `IReadOnlyList` containing the names of all channels that have message buffers, which are used to broadcast status changes. This method is typically used when a caller needs to enumerate the channels to notify about status updates without taking ownership of or mutating the internal collection. + +## Remarks +By wrapping the internal list with AsReadOnly, this method preserves encapsulation: callers can observe which channels exist without gaining permission to modify the collection. It also centralizes how channel names are exposed, so changes to the underlying storage need only be updated here. If the set of channels changes over time, the returned view will reflect those changes; if a stable, unchanging snapshot is required, consider copying the values to a new list. + +## Notes +- The returned view is not a deep freeze; it's a live wrapper over the internal list. For a stable snapshot, copy to a new list. + +--- + +### GuardedClipboardAction +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private static void GuardedClipboardAction(Action action, string operation) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `action` | `Action` | — | +| `operation` | `string` | — | + +**Returns:** `void` + + +GuardedClipboardAction executes the supplied edit action and swallows transient clipboard failures by catching all exceptions and logging a warning that the clipboard operation failed, including the operation name. Use it when performing clipboard-related edits to prevent OS clipboard contention from propagating to the input loop, keeping the application responsive even if the clipboard is momentarily unavailable. + +## Remarks +GuardedClipboardAction encapsulates the resilience policy for clipboard interactions, separating error handling from the business logic that mutates the clipboard. By treating clipboard failures as non-fatal, it reduces boilerplate at call sites and provides a consistent user experience when the clipboard is busy or locked by another process. + +## Notes +- It catches all exceptions, potentially hiding bugs if used in contexts where failures should propagate. +- No retry logic is performed; if a retry is desired, implement it at the call site or extend this helper. +- Logs a warning with the operation name to aid debugging without interrupting the user flow. + +--- + +### MentionUser +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void MentionUser(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `void` + + +MentionUser inserts a user mention into the chat composer by placing "@{username} " at the current cursor position and then returning focus to the input field. Use it when the UI needs to prefill a mention (for example after the user selects a contact) so the user can continue typing immediately with a properly formatted mention. + +## Remarks +By centralizing the mention formatting (leading '@' and trailing space) and focus restoration, this method ensures all mentions are inserted consistently across the chat UI. It depends on the _inputField control, so it should be invoked on the UI thread where that control exists. + +## Example +```csharp +// When a user is selected for a mention +MentionUser("alice"); +``` + +## Notes +- No validation or escaping is performed; the value is inserted as-is after '@'. +- Should be called on the UI thread when the input field is accessible; otherwise UI interactions may fail. +- Assumes _inputField is non-null; if not, it may throw. + +--- + +### OnChannelListSelectionChanged +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnChannelListSelectionChanged(object? sender, ValueChangedEventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `ValueChangedEventArgs` | — | + +**Returns:** `void` + + +Handles the channel list selection change by reading the new index from the event args, validating that it points to a valid channel, and switching to that channel only if it's not already the current channel. It then raises OnChannelSelected with the chosen channel name to propagate the change. + +## Remarks +Serves as the UI-to-state bridge for channel navigation. It centralizes the validation of the selection index and guards against unnecessary channel switches, ensuring the application only changes channels when asked by the user. It relies on the _channelNames collection as the authoritative mapping from list indices to channel identifiers, and on _messageManager.CurrentChannel to determine whether a switch is needed. By publishing the new channel through OnChannelSelected, other components can react (e.g., updating status, logging, or triggering related UI updates) without directly coupling to the list control. + +## Notes +- Ensure _channelNames stays in sync with the channels presented in the UI; a mismatch can lead to incorrect mappings or no operation. +- The method assumes _messageManager.CurrentChannel reflects the current channel state; if not, behavior may not switch as expected. +- The OnChannelSelected event is invoked using the null-conditional operator, so there may be zero subscribers without causing a crash. + +--- + +### OnChatViewportChanged +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnChatViewportChanged() +``` + +**Returns:** `void` + + +The method reacts to changes in the chat viewport width by reading the current width from the chat list’s viewport. If the width is positive and differs from the last recorded width, it updates the cached value, propagates the new width to the message manager, and refreshes the messages to align the display with the new size. + +## Remarks + +This is a focused resize handler that isolates width-change logic from general rendering. By guarding against no-ops (width <= 0 or unchanged width) it avoids unnecessary layout work and keeps the chat display in sync with the viewport through the message manager and a refresh cycle. It relies on the UI-related components (_messageList, _messageManager, and RefreshMessages) and should be invoked within the appropriate UI thread context. + +## Example + +```csharp +// Common case: the chat viewport has been resized to a new positive width +OnChatViewportChanged(); +``` + +## Notes + +- The method only acts when newWidth > 0 and newWidth != _lastChatWidth, preventing redundant work on unchanged sizes. +- It updates internal state before triggering a layout refresh, ensuring subsequent calls see the updated width. +- Since it touches UI-related components, ensure invocation occurs on the UI thread to avoid cross-thread access issues. + +--- + +### OnHistoryPrepended +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnHistoryPrepended(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Maintains the user's reading position when historical messages are prepended to the current channel's message list. If the incoming channel matches the currently displayed channel, it loads the channel's messages, records how many items were visible before the refresh, refreshes the list, computes how many items were prepended, and, if any, selects the item at that offset to keep the view from jumping to the top. This behavior helps the user remain oriented while older messages are loaded above the current view. + +## Remarks + +This method exists to decouple the UI from the underlying data refresh when history is added to the top of the chat. By capturing the pre-refresh count and re-selecting based on the number of newly prepended items, it preserves the visual position in the list and avoids a disruptive jump to the beginning. It relies on the current channel check, the ChatListSource.Count, and the SelectedItem property to compute and apply the offset during the refresh cycle. + +## Notes + +- Guard clauses ensure the method is a no-op when the channelName is not the current channel or when there are no messages for the channel. +- The offset calculation assumes RefreshMessages updates the list by prepending items above the existing ones; if the underlying data source changes differently, the preserved position may be off by one or more items. +- This is an internal handler; external callers should not invoke it directly. + +--- + +### OnInputContentsChanged +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnInputContentsChanged(object? sender, ContentsChangedEventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `ContentsChangedEventArgs` | — | + +**Returns:** `void` + + +OnInputContentsChanged handles content changes in the main window's input field. It respects a guard (_suppressEmojiReplace) to avoid re-entrant edits caused by programmatic text changes. If the current input text appears to be a dropped file path and DroppedFileParser can resolve one or more files, and there is a non-empty _messageManager.CurrentChannel, it clears the input and stages the discovered files for sending instead of leaving the raw path text to be dispatched. Otherwise, it runs EmojiHelper.ReplaceEmoji to substitute emoji sequences. If no replacement occurs, the method returns. If replacements occur, it computes the delta in length, repositions the cursor to the corresponding column after the edit, and updates the input field accordingly, wrapping the change in a guard to re-enable emoji processing afterwards. + +--- + +### OnInputKeyDown +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnInputKeyDown(object? sender, Key e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `Key` | — | + +**Returns:** `void` + + +OnInputKeyDown is the keyboard shortcut handler for the chat message input area. It interprets specific keys to drive UI behaviors such as autocompletion, reply cancellation, message submission, and clipboard-based attachments, ensuring keyboard users can perform common actions without leaving the input context. + +Shortcuts supported include Tab for autocompletion; Esc to cancel a pending reply (when such a reply exists); Newline to insert a line break; Enter to submit the message when there is content or staged attachments and there is a valid channel; Alt+Q to quit; Ctrl+K to open the search dialog; F6 to focus the message list; Ctrl+V/Ctrl+Y to paste, with clipboard-aware behavior: paste files from the clipboard as attachments, paste PNG image data as an image, or fall back to a normal text paste; Ctrl+X to cut; Ctrl+C to copy. Unrecognized keys are ignored and the event is left unhandled. + +## Remarks +OnInputKeyDown centralizes input-related keyboard interactions for the main window, so the user experience remains consistent between typing, editing, and navigation. It delegates the actual actions to collaborators (the input field, the message manager, and the event publishers like OnMessageSubmitted and OnImagePasted), keeping key handling isolated from business logic. It also respects channel permissions by bypassing text-entry actions when the current channel is read-only, preventing invalid edits. + +## Notes +- Enter submission guard: the message is submitted only if there is text (after trimming) or there are staged attachments, and the current channel is non-empty. +- Clipboard behavior: Ctrl+V/Ctrl+Y first try to stage clipboard files as attachments; if none are files, they attempt to paste PNG image data from the clipboard; if neither applies, they fall back to a standard text paste via the input field. +- Read-only channels: text entry and attachment staging are skipped when the channel is read-only, ensuring the UI adheres to channel permissions. + + +--- + +### OnMessageListAccepting +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnMessageListAccepting(object? sender, CommandEventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `CommandEventArgs` | — | + +**Returns:** `void` + + +Activates the selected chat line in the message list, validating the source and index, then dispatching a context-appropriate action based on what the line represents. It first resolves quote targets for replies, then handles attachments (audio, file, or image), detects @mentions and #channels within the line text, and finally falls back to opening the sender's profile. Each path marks the event as handled to stop further processing. + +## Remarks +All user interactions for a list entry funnel through this method, providing a single, predictable entry point for keyboard or programmatic activation. It keeps UI concerns decoupled from the data model by routing actions through dedicated callbacks (OnAudioPlayRequested, OnFileDownloadRequested, OnImageOpenRequested, OnUserProfileRequested, OnChannelJoinRequested) and by inspecting ChatLine properties such as AttachmentKind, JumpToMessageId, and SenderUsername. This design minimizes scattered conditional logic across the UI layer and centralizes the decision-making about what happens when a line is activated. + +## Notes +- Early returns guard invalid state (null source, invalid index) and keep no-op paths contained. +- Attachment priority: if an attachment exists, media actions take precedence over textual interactions (mentions/channels). +- Fallback behavior: if no attachment, mention, channel, or sender username applies, the method completes without invoking any callbacks. + +--- + +### OnMessageListKeyDown +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnMessageListKeyDown(object? sender, Key e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `Key` | — | + +**Returns:** `void` + + +This event handler processes keyboard input for the chat message list. It provides two primary shortcuts: F6 moves focus back to the input box to enable quick replies, and Delete or Backspace initiates the deletion flow for the currently selected message. If F6 is pressed, focus is transferred to the input field and the event is marked as handled. If Delete or Backspace is pressed, the code first validates that the message list source is a ChatListSource, that a valid item is selected, and that the selected line exposes a MessageId. When these conditions are met, the handler invokes ConfirmDeleteMessage with the message's ID and marks the event as handled, delegating the actual permission check to the server. The server enforces real permissions (own message or Mod+ over a lower role); the client simply confirms intent and relies on the server to reject disallowed actions. + +--- + +### OnMessageListMouseEvent +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnMessageListMouseEvent(object? sender, Mouse e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `Mouse` | — | + +**Returns:** `void` + + +Handles mouse interactions for items in the chat message list. The method processes left- and right-clicks to either activate attachment actions on a line or present a context menu; if the click doesn't map to a known action, it returns without side effects. It determines the targeted line from the list's TopItem and the mouse position, validates bounds, and, for left-button clicks, dispatches OpenImage or SaveOriginal actions when the click occurs on a matching ActionSpan with a non-null AttachmentUrl and AttachmentFileName. It invokes OnImageOpenRequested(url, name) when the Action is OpenImage, otherwise OnImageSaveRequested(url, name). It then marks the event as handled and returns. For right-clicks, it selects the row, focuses the list, and shows the message context menu at the screen position. If none of these conditions apply, the method simply returns, leaving other listeners to handle the event as appropriate. + +## Remarks +By centralizing this logic in OnMessageListMouseEvent, the UI separates interaction details from the concrete actions (open/save). The event-based callbacks (OnImageOpenRequested, OnImageSaveRequested) enable the host to implement corresponding behavior without the control needing to know how to present or fetch attachments. It coordinates among the message list, its source lines, and the context menu, ensuring left-clicks only trigger attachment-related actions and right-clicks prepare the selection and menu. + +## Notes +- Left-click triggers only when the target line has both an AttachmentUrl and an AttachmentFileName and the click lies within an ActionSpan; otherwise the method returns without performing the action. +- When an action path is taken, OnImageOpenRequested or OnImageSaveRequested is invoked with the attachment's URL and file name, and e.Handled is set to true to suppress further processing. +- Right-click path selects the row, focuses the list, and shows the context menu; the event is marked as handled in those cases. + +--- + +### OnMessageListVerticalScrollBarScrolled +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnMessageListVerticalScrollBarScrolled(object? sender, EventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `EventArgs` | — | + +**Returns:** `void` + + +This private method serves as the Scroll event handler for the message list's vertical scrollbar. It detects when the scrollbar has been scrolled to the top (VerticalScrollBar.Value == 0) and, in that case, raises the OnLoadMoreRequested event to fetch older messages, if any subscriber is attached. + +## Remarks + +By centralizing the trigger for loading more messages behind a single, UI-focused event, this abstraction keeps the data-loading flow decoupled from the scrollbar mechanics. It relies on the scrollbar's Value to determine the top position, rather than on the event payload, making the behavior straightforward to test and reason about in isolation. This pattern enables incremental history loading without scattering load logic across the UI code. + +## Notes + +- The OnLoadMoreRequested invocation is guarded by the null-conditional operator, so no action occurs if there are no subscribers. +- Scrolling to the top may re-trigger loads if the user lingers at the top or repeatedly reaches it; consider adding a guard (e.g., a loading flag or debounce) in the handler or subscriber to prevent concurrent or duplicate fetches. + +--- + +### OnMessagesChanged +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnMessagesChanged(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Handles the event when the message set changes for a channel. If the changed channel matches the currently displayed channel, it refreshes the visible messages; otherwise, it refreshes the channel list. Finally, it marks the status bar for redraw to reflect background activity. + +## Remarks +This method acts as the UI glue between the message data and the main window. It centralizes the decision about what to refresh, reducing unnecessary work by only reloading the current channel’s messages when needed. The unconditional SetNeedsDraw ensures the status indicator is updated after any message activity. + +## Notes +- Assumes _messageManager and _statusLabel are initialized before invocation; otherwise a NullReferenceException could occur. +- The comparison channelName == _messageManager.CurrentChannel is a straightforward string equality check; if channel naming becomes more complex, consider normalization. +- This method is private and intended to be invoked by the class itself in response to message-change events, not by external callers. + +--- + +### OnStatusBarDrawContent +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnStatusBarDrawContent(object? sender, DrawEventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `DrawEventArgs` | — | + +**Returns:** `void` + + +OnStatusBarDrawContent renders the EchoHub status bar by composing branding, version, connection state (with an animated spinner for transitional states), the current user, channel details, and unread activity into the status label. It respects the available width by measuring grapheme columns and cancels the default drawing to ensure full control over layout and color. + +## Remarks +This method centralizes the visual composition of the status bar, ensuring consistent theming and typography through the various status attributes and color selectors. It reads live state from the application's managers (such as the current user, current channel, and unread activity) and adapts visuals (including a spinner for transitional connection states and color-coded channel/user indicators) to reflect real-time context. By isolating this logic, the UI remains cohesive even as underlying state sources evolve, and it guarantees a stable, width-aware rendering surface for the status line. + +## Notes +- The function early-exits if the status bar width is non-positive, so ensure the status bar has a meaningful width before rendering. +- It uses a Resolve step to substitute a None background with the normal background, preserving a consistent look across segments. +- The handler takes full control of drawing for the status bar (it may set e.Cancel = true and fill remaining space with spaces); callers should not rely on the default rendering path. + +--- + +### OnUsersListAccepting +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnUsersListAccepting(object? sender, CommandEventArgs e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `CommandEventArgs` | — | + +**Returns:** `void` + + +This private event handler responds to the user activating a selection in the users list. It first validates that there is a selected item within bounds, resolves the corresponding username from the list source, and if a username exists, raises the OnUserProfileRequested event with that username and marks the command as handled to prevent further processing. + +## Remarks +This method acts as the bridge between the UI interaction (selecting a user and accepting the action) and the navigation to that user’s profile. It encapsulates the guard logic for a valid selection and a non-null username, ensuring the rest of the UI remains robust against invalid state. By emitting OnUserProfileRequested, it decouples the act of selecting a user from the actual navigation/presentation of the profile, allowing subscribers to decide how to present the profile (e.g., in a panel, a new window, or a details view). The null-conditional invocation protects against the absence of subscribers without forcing a null check at every call site. + +## Notes +- The method returns early when there is no valid selection (null index, negative index, or index outside the source bounds). +- A username must be non-null to trigger navigation; otherwise, no event is raised and no handling is marked. +- e.Handled is set to true only when a username is successfully resolved and the profile request is emitted, indicating to the caller that the command was consumed. + +--- + +### OnWindowKeyDown +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void OnWindowKeyDown(object? sender, Key e) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `sender` | `object?` | — | +| `e` | `Key` | — | + +**Returns:** `void` + + +Handles the main window's KeyDown events and implements a small set of global keyboard shortcuts. When one of the predefined keys is pressed, it invokes the corresponding action (stop the application, toggle the users panel, or show the search dialog) and marks the event as handled to prevent further processing; for unrecognized keys, the method returns without taking action, allowing normal input behavior. + +## Remarks +By consolidating keyboard shortcuts in OnWindowKeyDown, the class centralizes input concerns for the window and makes it easier to adjust global hotkeys in one place. The handler relies on private members such as _app, ToggleUsersPanel, and ShowSearchDialog to perform the actions, which keeps the event handling decoupled from UI details. Marking the event as Handled ensures that no other key handlers react to these shortcuts, avoiding conflicting behavior. + +## Notes +- Only triggers for the specific KeyCode values (AltQKey, F2Key, CtrlKKey); other keys are passed through. +- Because it is a private method, wiring must happen in the same class (e.g., via the KeyDown event). +- Setting e.Handled = true happens only after a known shortcut is processed; if the handler returns early for unrecognized keys, Handled remains false. + + +--- + +### RefreshChannelList +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void RefreshChannelList() +``` + +**Returns:** `void` + + +RefreshChannelList refreshes the channel list in the UI, showing unread counts next to channel names. It pins system channels to the top, preserving the relative order of non-system channels, and then determines which channels are private (excluding system channels). The method updates the UI data source with the latest channel list, unread counts, current channel, privacy flags, and mentions, and finally restores the user's current channel selection. + +## Remarks +Centralizes the channel-list choreography: ordering, privacy flags, unread counts, and selection state are prepared here before binding to the UI. It relies on _channelNames as the source of truth for selection, uses a stable sort to preserve alphabetical order within system and non-system groups, and computes privateChannels by consulting both _systemChannels and _channelPublic. By separating data preparation from UI binding (_channelListSource.Update and _channelList.Source), the code remains easier to reason about and yields deterministic refresh behavior. + +## Notes +- The ordering is stable: system channels are pinned to the top, and non-system channels retain their original alphabetical order within their group. +- System channels are private by nature but do not receive the private glyph; they are explicitly excluded from the privateChannels set. +- The method mutates _channelNames in place; ensure it is invoked on the UI thread to avoid race conditions during updates. + + +--- + +### RefreshMenuBar +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void RefreshMenuBar() +``` + +**Returns:** `void` + + +RefreshMenuBar rebuilds and replaces the menu bar to reflect changes such as updated themes. Call it when theme lists or related UI chrome have changed to ensure the bar is rebuilt and redrawn, instead of trying to mutate the existing bar in place. + +## Remarks +This method centralizes the UI update required after theme changes, ensuring the menu bar is rebuilt from a fresh state and consistently themed. It delegates bar construction to BuildMenuBar() and handles the lifecycle: removing the old bar, inserting the new one, applying color schemes, and requesting a redraw. By encapsulating this sequence, the UI remains coherent even as themes and related styling evolve, reducing the risk of stale or inconsistent visuals. + +## Notes +- Potential UI flicker: the bar is removed and rebuilt; rapid theme changes could cause a brief visual flash. +- Must be called on the UI thread to safely manipulate UI controls; crossing threads can lead to exceptions. + +--- + +### RefreshMessages +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void RefreshMessages() +``` + +**Returns:** `void` + + +RefreshMessages updates the chat ListView by transforming the current channel’s messages into a renderable ChatListSource, wrapping lines to the available viewport width and expanding rules when needed; it then binds the source to the UI and places the selection on the latest item. It caches the last measured width (falling back to it when the viewport hasn’t been laid out yet) to avoid flicker on initial layout. If no channel is selected, it displays a welcome banner instead of messages. + +## Remarks +This method centralizes the layout-sensitive conversion from raw messages to UI presentation, isolating wrapping and rule-expansion logic from the ListView rendering code. It also guarantees the view shows the most recent content by selecting the last item after building the source, and it gracefully switches to a welcome banner when there is no active channel. + +## Notes +- If the viewport width is not yet reported (width <= 0) and there is no cached width, the method adds messages without wrapping, potentially producing non-wrapped lines until layout occurs. +- Requires access to UI elements (_messageList, _messageManager, WelcomeBanner); should be invoked from the UI thread to avoid threading issues. + +--- + +### RemoveChannel +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void RemoveChannel(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +Removes a channel from all internal channel collections and then refreshes the left panel. Use this when deleting a channel to ensure the in-memory state and the UI stay in sync, rather than mutating each collection separately. + +## Remarks +This method serves as a single, centralized deletion boundary for channel metadata. By encapsulating removal across multiple collections (_channelNames_, _channelTopics_, _channelPublic_, _channelProtected_, _systemChannels_), it guarantees consistent state and avoids partial leftovers, and it ensures the UI is refreshed to reflect the current channel set. + +## Notes +- Removal is best-effort; if a channel name isn't present in a given collection, that collection simply omits it without throwing. +- If called from a non-UI thread, ensure thread affinity when RefreshChannelList needs to update the UI. + +--- + +### ScrollToMessage +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void ScrollToMessage(Guid messageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `messageId` | `Guid` | — | + +**Returns:** `void` + + +Scrolls the message list to the first line of the specified message, a helper used by the reply-quote workflow to align quotes with the original content. If the message is not present in the currently loaded buffer, the method is a no-op and makes no UI changes. + +## Remarks +This method isolates a small but important piece of UI choreography: given a messageId, it locates the corresponding line in the ChatListSource, selects it, and adjusts the scroll so the line appears near the top of the view (with a three-line context). It avoids impacting other lines or quote lines by requiring JumpToMessageId to be null, ensuring we jump to the message's own line. Keeping this logic in one place simplifies the quote rendering flow and makes behavior consistent across different message states. + +## Notes +- Linear search through the current source; costs are proportional to the number of lines in view. +- No action if Source is not a ChatListSource or if no matching line is found. +- TopItem is set to Math.Max(0, i - 3) to preserve a little context above the target line. +- Mutates UI state (SelectedItem, TopItem, focus, and redraw) and should be invoked on the UI thread. + +--- + +### SetChannelTopic +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SetChannelTopic(string channelName, string? topic) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `topic` | `string?` | — | + +**Returns:** `void` + + +Updates the topic for a specific channel by assigning the provided topic to the channel's entry in the internal _channelTopics dictionary. If the channel being updated is the one currently displayed in the UI (as indicated by _messageManager.CurrentChannel), it also refreshes the topic display by calling UpdateTopicBar. + +## Remarks + +By centralizing topic mutations here, callers don’t need to manipulate UI state directly. The method ensures consistency between the channel topics data model and the user interface by triggering a UI update only when the changed channel is the active one. + +## Example + +```csharp +// Update the topic for the "general" channel; the UI will refresh if that channel is currently active +SetChannelTopic("general", "Welcome to the general discussion channel!"); +``` + +## Notes + +- If topic is null, the topic for the specified channel is cleared in the _channelTopics dictionary. The entry is created or overwritten as needed. +- Changes to topics for non-active channels do not immediately affect the UI; the topic bar updates only when the affected channel is the current/active channel. + + +--- + +### SetChannels +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SetChannels(List channels) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channels` | `List` | — | + +**Returns:** `void` + + +SetChannels takes a list of ChannelDto, clears the local channel state, fills in names, topics, and visibility, and marks protected and system channels, before refreshing the channel list UI. Use this when you receive a full snapshot of channels from the server and want the UI to reflect that snapshot in one operation rather than mutating individual channels. + +## Remarks +By converting the ChannelDto data into the UI state, this method isolates the UI from the raw DTOs and centralizes the mapping logic. It ensures a consistent representation of channel topics and visibility, while grouping channels by protected or system roles to simplify downstream behavior. + +## Notes +- Null input will cause an exception; callers should pass an empty list or validate before calling. +- Assumes channel names are unique identifiers; duplicate names will create duplicates in _channelNames and may overwrite entries in _channelTopics or misclassify in protected/system lists. + +--- + +### SetCurrentUser +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SetCurrentUser(string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `void` + + +Sets the current user name and delegates to the message manager for @mention detection. Use this when the active user changes (for example, after login or user switch) so that subsequent messages and mentions are evaluated against the correct user. + +## Remarks +This method is a thin wrapper around _messageManager.SetCurrentUser; it centralizes the UI's interaction with the messaging subsystem and keeps the rest of the UI agnostic about how mentions are detected. By routing the update through the message manager, changes to mention resolution are applied consistently across the system and encapsulated in a single component. In practice, the UI can continue to call SetCurrentUser without needing to know about the underlying messaging implementation. + +## Notes +- No input validation is performed here; ensure the provided username meets the expectations of the message manager and is non-null. +- As a pass-through, any validation or side effects originate from _messageManager; callers should be prepared to handle its behavior. + +--- + +### SetReplyingTo +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SetReplyingTo(string? label) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `label` | `string?` | — | + +**Returns:** `void` + + +Shows/clears the tiny contextual indicator in the input frame's title that reflects the current reply target. When you pass a non-null label, the title displays a fragment like "↩ Replying to {label} │ Esc=cancel" to provide context for the reply; passing null clears the indicator. After computing the fragment, the method calls UpdateInputTitle() to refresh the UI immediately so the change is visible to the user. + +## Remarks + +By centralizing this UI state, SetReplyingTo encapsulates the presentation detail of the reply workflow. It separates the action of initiating a reply from the mechanics of rendering the updated title, and ensures a consistent reply-indicator string is used across the input area. + +## Example + +```csharp +// Within the same class context +SetReplyingTo("Alice"); +SetReplyingTo(null); +``` + +## Notes + +- This method mutates UI-related state and should be invoked on the UI thread to avoid cross-thread access issues when updating the window chrome. + +--- + +### SetStagedAttachments +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SetStagedAttachments(IReadOnlyList fileNames, string asciiSizeLabel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `fileNames` | `IReadOnlyList` | — | +| `asciiSizeLabel` | `string` | — | + +**Returns:** `void` + + +Updates the attachment staging indicator shown on the input frame's title, including the current ASCII-art size for images. Passing an empty list restores the default hint. + +## Remarks +Centralizes attachment-state presentation in the input UI, so the title reflects what is staged without scattering formatting logic across callers. It updates a staged flag and builds a compact label that shows the count, a short preview of names, and the ASCII size label, then refreshes the title via UpdateInputTitle(). This makes it easy to adjust formatting (e.g., truncation length) in one place while keeping the input frame in sync. + +## Notes +- The method assumes fileNames is non-null; passing null will throw a NullReferenceException when accessing Count. + +--- + +### ShowError +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void ShowError(string message) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `message` | `string` | — | + +**Returns:** `void` + + +Shows an error message to the user by presenting a modal dialog with the title 'Error' and the provided message. It delegates to MessageBox.ErrorQuery to render the dialog, using the current application context (_app) to display the UI. This lightweight wrapper ensures a consistent, centralized way to surface user-facing errors across the EchoHub client UI. + +## Remarks +By consolidating error presentation here, callers don't need to know about the underlying message box details; the wrapper encapsulates the UI intent. This helps ensure a consistent dialog structure (title 'Error', an 'OK' button) while leaving room to enhance behavior later (e.g., localization, logging) without touching every call site. + +## Example +```csharp +ShowError("Unable to load user data."); +``` + +## Notes +- Ensure _app is non-null and this call runs on the UI thread. +- This method is synchronous and blocks until the user dismisses the dialog; avoid calling from long-running background tasks. + + +--- + +### ShowMessageContextMenu +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void ShowMessageContextMenu(ChatLine line, System.Drawing.Point screenPosition) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `line` | [`ChatLine`](Chat/ChatLine.cs.md) | — | +| `screenPosition` | `System.Drawing.Point` | — | + +**Returns:** `void` + + +It builds and shows a per-message right-click context menu for a chat line at a given screen position, combining attachment actions, reply/mention/profile options, copy operations, and a delete action subject to server-side permissions. Use it to provide a consistent, feature-rich set of line-specific actions when a user invokes the context menu on a message line (e.g., via right-click). + +## Remarks +This method centralizes the per-line action surface for chat messages, deriving available options directly from the message state. It conditionally adds actions based on the presence and type of attachments, existence of a sender, and whether the message can be replied to or deleted. By assembling a flat list of MenuItem actions and delegating to a PopoverMenu, it decouples the action presentation from the rest of the UI and ensures a uniform user experience across message kinds. The method also demonstrates how user interactions trigger higher-level callbacks (e.g., opening attachments, replying, mentioning, viewing profiles, copying text, or requesting deletion) while managing UI focus and popover lifecycle. + +## Notes +- The context menu is short-circuited if there are no actionable items, avoiding an empty popover. +- Reply content is derived by stripping the leading header from the line's textual representation; if the header pattern is absent, the full line is used. +- Delete actions route through ConfirmDeleteMessage, reflecting server-side permission checks rather than performing client-side deletion. +- Attachment-related actions are selected based on AttachmentKind, with sensible defaults for unknown kinds. + + +--- + +### ShowSearchDialog +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void ShowSearchDialog() +``` + +**Returns:** `void` + + +Signals the UI to display the search dialog by invoking OnSearchRequested, but only if there are subscribers. This private helper is called when a search action is requested, decoupling the action from the actual dialog presentation and allowing the UI to respond without the ShowSearchDialog method needing to know how the dialog is shown. + +## Remarks +This method acts as a small abstraction layer between the user action and the dialog presentation. By centralizing the emission of the OnSearchRequested event, the MainWindow class remains focused on orchestration rather than UI rendering specifics. Subscribers can provide or adjust the search behavior without modifying callers, aiding testability and future UI changes. + +## Notes +- The invocation is synchronous on the calling thread; a long-running event handler will block the caller unless it offloads work. +- The method does not itself create or show any UI; it merely signals interested parties via OnSearchRequested. + +--- + +### StageFiles +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void StageFiles(IReadOnlyList files) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `files` | `IReadOnlyList` | — | + +**Returns:** `void` + + +Stages the specified files as a single batch of attachments for the active channel. If there is no current channel, the method exits without staging. When a channel exists, it triggers the OnFilesStaged event to hand off the batch to the sending workflow; the next Enter press will transmit these attachments together with any caption the user has typed. + +## Remarks +StageFiles acts as a tiny adapter between the user action (dropping or pasting files) and the message-sending pipeline. By emitting OnFilesStaged instead of performing the send itself, it keeps the UI concerns separate from transport mechanics and allows multiple components to react to the staging event. The method relies on the presence of a current channel to decide whether staging is meaningful, embodying a guard that prevents accidental attachment uploads when not in a channel. + +## Notes +- If there is no active channel, this method is a no-op. +- OnFilesStaged is invoked only when there is a channel; if there are no subscribers, nothing happens. +- There is no in-method validation of file paths; validation is delegated to downstream handlers. + +--- + +### SwitchToChannel +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void SwitchToChannel(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `void` + + +SwitchToChannel switches the chat view to the specified channel. It updates the underlying message state to reflect the new current channel, updates the chat window title to show the channel (prefixed with a #), clears the unread count for that channel, and triggers a sequence of UI refreshes to keep the display in sync: the channel list, the displayed messages, the topic bar, and the input’s read-only state. It also marks the status area for redraw and, if the channel exists in the known list, selects it in the channel list to align the selection with the active channel. + +--- + +### ToggleUsersPanel +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void ToggleUsersPanel() +``` + +**Returns:** `void` + + +ToggleUsersPanel flips the panel visibility flag and then refreshes the layout to reflect the new state. This method is typically bound to the F2 keyboard shortcut, enabling users to quickly show or hide the online users panel without interacting with UI controls. + +## Remarks +Encapsulating the state change and the layout refresh in a single method keeps the UI logic cohesive and discoverable. Callers can rely on this method to perform the complete show/hide action, rather than mutating internal fields directly, which helps prevent inconsistent presentation. If the binding for F2 changes, the toggle behavior remains centralized here. + +## Notes +- Ensure calls occur on the UI thread; invoking from a background thread may require marshaling to the UI thread before touching UI state. + +--- + +### TryAutocompleteCommand +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void TryAutocompleteCommand() +``` + +**Returns:** `void` + + +Tab-complete slash commands in the input field. This method provides a lightweight command-entry UX by auto-completing a slash command when the user types a leading slash with no spaces, using the available SlashCommands list. If exactly one match exists, it completes to that command plus a trailing space; if multiple matches exist, it computes the longest common prefix among them and applies it when it extends beyond the current input. Finally, it moves the caret to the end of the input to prepare for continued typing. + +## Remarks +Provides an in-place UX enhancement for command entry; it reads from the in-memory SlashCommands collection and does not trigger any external calls. It treats matches case-insensitively and updates the input field accordingly, leaving the user to continue typing after the completion. + +## Notes +- Mutates only when the input begins with '/' and contains no spaces; otherwise it exits without changes. +- When multiple matches exist, the prefix calculation starts from the first match in the list; the resulting auto-prefix can depend on the list ordering. +- The caret is always moved to the end of the text, regardless of whether any text was changed. + +--- + +### UpdateInputReadOnly +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void UpdateInputReadOnly() +``` + +**Returns:** `void` + + +Disables the input for read-only (system) channels so nothing can be typed there, and reflects the state in the input frame title. It does this by setting the input field's ReadOnly flag based on IsCurrentChannelReadOnly and then calling UpdateInputTitle to synchronize the title with the current state. + +## Remarks +This small helper centralizes UI state synchronization: the input interactivity and the title reflect the channel's read-only status from a single source of truth (IsCurrentChannelReadOnly). By keeping UpdateInputReadOnly as the single place that applies this policy, changes to channel permissions automatically propagate to the input control and its label, ensuring consistent feedback to the user. + +## Notes +- Ensure this runs on the UI thread to avoid cross-thread access issues when manipulating UI controls. +- If IsCurrentChannelReadOnly changes, callers should ensure UpdateInputReadOnly is invoked so the input state and title stay in sync. + +--- + +### UpdateInputTitle +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void UpdateInputTitle() +``` + +**Returns:** `void` + + +Updates the input frame title to reflect the current editing state. When the current channel is read-only, the method forces the title to a fixed read-only message and requests a redraw; otherwise it derives the title from the reply and staged title fragments using a small switch expression: if both fragments are absent it uses the default title; if only one exists it uses that one; if both exist it concatenates them with a separator (" │ "). The method ends by signaling the input frame that it needs to redraw. + +## Remarks + +Centralizes the logic for how the input title is computed from the live fragments, ensuring consistent UI behavior in both read-only and writable channels. It prevents scattering of title-construction logic across the window code and makes it easier to adjust the title policy in one place. By honoring the read-only constraint at this point, it guarantees users always see an accurate, explicit hint about their ability to type. + +## Notes + +- The read-only branch takes precedence over any fragment values. +- SetNeedsDraw() is invoked after updating the title to refresh the UI; callers should not rely on drawing happening elsewhere. + +--- + +### UpdateLayout +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void UpdateLayout() +``` + +**Returns:** `void` + + +Reflows the main UI by resizing the chat, topic, and input frames based on whether the users panel is visible. It computes a right margin equal to the panel width when visible, applies Dim.Fill(rightMargin) to the relevant frames, toggles the users panel frame visibility, and then requests a redraw. + +## Remarks + +Centralizes the layout reflow logic so callers toggle _usersPanelVisible without duplicating width calculations. It coordinates the main content frames and the users panel visibility, ensuring the UI stays visually aligned whenever the panel appears or disappears. Because it's private, it's meant to be invoked by internal state changes rather than external consumers. + +## Example + +```csharp +// Example: toggle the Users panel and refresh layout +_usersPanelVisible = true; +UpdateLayout(); + +_usersPanelVisible = false; +UpdateLayout(); +``` + +## Notes + +- Must be called on the UI thread after changing _usersPanelVisible. +- Relies on UsersPanelWidth; ensure it is defined and non-negative when the panel is shown. +- Invoking SetNeedsDraw() schedules a redraw; avoid rapid, consecutive calls from non-UI threads. + +--- + +### UpdateOnlineUsers +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void UpdateOnlineUsers(List users) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `users` | `List` | — | + +**Returns:** `void` + + +UpdatesOnlineUsers updates the online users list display by transforming a `List` into the UI representation used by the user panel. For each user it computes a status icon from their UserStatus, selects a display name (DisplayName if present, otherwise Username), and applies a role tag derived from their ServerRole. If the user is connected through IRC, it appends a [irc] suffix to convey feature context. The name color is determined by first attempting to parse NicknameColor as a hex color; if that fails, it falls back to a deterministic per-nick color from NickColorHelper.GetAttribute, ensuring colors stay consistent with the user's chat messages. The resulting collection is written to the underlying _usersListSource and the frame title is updated to reflect the current number of online users. + + +--- + +### UpdateSpinner +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void UpdateSpinner() +``` + +**Returns:** `void` + + +Starts the spinner timer when entering a transitional connection state (Connecting, Reconnecting, …); the timer stops itself once the state settles. + +The method immediately returns if there is no transitional status or if a spinner timer is already running, ensuring only a single spinner animation is active at a time. When invoked in the proper state, it schedules a recurring callback via _app.AddTimeout with a 120-millisecond interval. Each tick first checks whether the status remains transitional; if it does not, the method clears the timer token and stops frequency updates. If the status is still transitional, it advances the spinner frame by one, wraps around using the length of SpinnerFrames, and requests a redraw of the status label. This creates a smooth, looping spinner animation that runs only as long as the transitional state persists. + +Dependencies: TimeSpan, SpinnerFrames + +Dependency APIs (verified signatures) + +- field SpinnerFrames (src/EchoHub.Client/UI/MainWindow.cs) + + +--- + +### UpdateStatusBar +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +public void UpdateStatusBar(string status) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `status` | `string` | — | + +**Returns:** `void` + + +Updates the connection status displayed in the status bar by updating the internal state, refreshing the spinner, and invalidating the status label for redraw. Call this method whenever the connection state changes (for example, during connecting, when connected, or on disconnection) to keep the status bar in sync with the actual connection status without duplicating UI update logic elsewhere. + +## Remarks +Centralizes the status bar update sequence in one place, ensuring the internal state and the visual feedback stay in sync. By encapsulating the setter of _connectionStatus, the spinner refresh, and the redraw trigger, callers avoid partially updated UI states and reduce the risk of stale visuals. + +## Example +```csharp +// Example: update the status bar to reflect a connected state +UpdateStatusBar("Connected"); +``` + +## Notes +- Should be invoked on the UI thread to safely update UI elements. +- Frequent updates will trigger spinner refreshes and redraws; consider batching rapid status changes. + +--- + +### UpdateTopicBar +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +private void UpdateTopicBar() +``` + +**Returns:** `void` + + +Show or hide the topic bar based on the current channel's topic. + +The UpdateTopicBar method reads the topic associated with the current channel from the _channelTopics collection and updates the topic label and chat layout accordingly. If a non-empty topic is found, it sets the label text to " Topic: {topic}", makes the label visible, and adjusts the chat frame position (Y = 2) to accommodate the topic bar. If there is no topic (or the topic is whitespace), it hides the topic label and resets the chat frame position (Y = 1). + +This method uses TryGetValue to avoid exceptions when a channel has no entry and relies on string.IsNullOrWhiteSpace to determine whether a topic should be shown. It encapsulates the small but important UI logic that bridges channel-topic data with the visual layout, ensuring a consistent presentation whenever the current channel or topic changes. + +--- + +### AltQKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode AltQKey = KeyCode.Q | KeyCode.AltMask +``` + + +AltQKey is a private constant KeyCode that encodes the keyboard shortcut Alt+Q by OR-ing KeyCode.Q with KeyCode.AltMask. It’s intended for input checks in the class, allowing a single, readable comparison (e.g., Input.GetKeyDown(AltQKey)) instead of reassembling the combination at every usage. + +## Remarks +This abstraction centralizes the Alt+Q shortcut so changes to the shortcut can be made in one place rather than scattered across the codebase. It also communicates intent more clearly than a scattered KeyCode.Q | KeyCode.AltMask in multiple checks. Because it’s a compile-time constant, it’s cheap to inline in input checks. + +## Notes +- The Alt+Q shortcut relies on the legacy input system’s KeyCode and AltMask semantics; if migrating to a different input system, this approach may need adjustment. +- Since AltQKey is private, it cannot be referenced from outside this class; expose a public/internal alias or a helper if cross-class usage is required. + +--- + +### CtrlCKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode CtrlCKey = KeyCode.C | KeyCode.CtrlMask +``` + + +CtrlCKey defines the keyboard shortcut Ctrl+C as a single KeyCode value by bitwise OR-ing the C key with the Ctrl modifier. Use this constant when your input handling needs to react to the Ctrl+C shortcut, instead of composing KeyCode.C and KeyCode.CtrlMask in every check. + +## Remarks +Centralizes the copy shortcut into a single, reusable symbol. It prevents duplicated magic-number logic across input checks and makes future changes to the shortcut trivial. Because the field is private const, it stays encapsulated within its containing class and provides a stable value for all internal listeners that rely on the same representation. This relies on KeyCode supporting modifier flags, enabling concise expression of keyboard shortcuts. + +--- + +### CtrlVKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode CtrlVKey = KeyCode.V | KeyCode.CtrlMask +``` + + +Represents the Ctrl+V keyboard shortcut used to trigger paste-like actions within the UI. Implemented as a private const KeyCode that combines KeyCode.V with KeyCode.CtrlMask into a single composite value. Use CtrlVKey in input handling within MainWindow to detect paste attempts instead of duplicating the key-check logic in multiple handlers. + +## Remarks +Centralizing the shortcut reduces duplication and keeps the paste-trigger logic consistent across the UI layer. The private visibility confines the behavior to the MainWindow class, supporting cohesive input handling without leaking implementation details. If cross-platform consistency is required, consider exposing a platform-aware abstraction (for example, mapping Cmd on macOS to Ctrl on Windows) to avoid surprising users. + +## Notes +- This is a compile-time constant; it cannot be reconfigured at runtime, so any need to support dynamic key bindings would require a different approach (e.g., a settings-backed binding). +- Relying on KeyCode.CtrlMask ties the value to the framework's modifier encoding; ensure it aligns with input handling elsewhere in the app to prevent mismatches. + +--- + +### CtrlXKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode CtrlXKey = KeyCode.X | KeyCode.CtrlMask +``` + + +CtrlXKey encodes the Ctrl+X keyboard shortcut as a single KeyCode value by performing a bitwise OR between KeyCode.X and KeyCode.CtrlMask. This provides a readable, centralized way for the main window's input handling to detect the Ctrl+X combination, avoiding scattered modifier checks throughout the code. + +## Remarks +Centralizes the shortcut definition to reduce duplication and make future changes easier. Keeping the constant private confines the shortcut to the UI input logic, preventing misuse from unrelated parts of the codebase. If the underlying input system evolves to treat modifiers separately from keys, this constant may need to be revisited to ensure Ctrl+X is still detected correctly. + +## Notes +- The approach relies on KeyCode being a flags-like enum so that combining X with the Ctrl modifier via a bitwise OR yields a meaningful single value. If the input API changes, CtrlXKey may no longer reflect the intended shortcut. +- Because CtrlXKey is private, always reference this constant within the class that handles keyboard input to avoid diverging shortcuts; duplicating the literal elsewhere risks inconsistency. + +--- + +### CtrlYKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode CtrlYKey = KeyCode.Y | KeyCode.CtrlMask +``` + + +Represents the Ctrl+Y keyboard shortcut as a single KeyCode value. Use this constant in the MainWindow's input handling to detect the Ctrl+Y combination without duplicating the modifier logic at each call site. + +## Remarks +Centralizes the hotkey for the main window, ensuring consistent behavior and making future changes easy to propagate. Keeping it private encapsulates the shortcut within the MainWindow class, reducing the risk of misuse and enabling compiler-level inlining for performance. + +## Notes +- Platform and input-system differences can affect how modifiers are interpreted; verify behavior on all target platforms. +- If other components need the same shortcut, avoid duplication by exposing a controlled API instead of re-declaring the same KeyCode combination. + +--- + +### EnterKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode EnterKey = KeyCode.Enter +``` + + +EnterKey is a private constant field of type KeyCode that represents the Enter key. It exposes KeyCode.Enter as a named value so input-handling code can compare against EnterKey directly, for example in switch statements, without relying on the raw KeyCode.Enter literal or invoking Key.Equals (which also accounts for a Handled state). This small alias keeps the Enter binding centralized and makes the code's intent clearer. + +## Remarks +Using EnterKey communicates intent and reduces the use of magic constants in input logic. Since it's private, only members within the containing type can reference it, keeping the binding decision encapsulated. If you later need to reuse the same binding from other types, consider exposing a non-private alias or extracting this pattern to a shared helper. + +## Notes +- Because it is const, its value is inlined at compile time; changing it requires recompilation of all assemblies that reference it. +- Encapsulation matters: private scope confines use to this type; expose it with a public/internal alias if cross-type reuse is required. +- The alias assumes the Enter key maps to KeyCode.Enter; if the underlying enum changes, update this constant accordingly. + +--- + +### F2Key +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode F2Key = KeyCode.F2 +``` + + +Defines a private, compile-time alias for the F2 keyboard key as a KeyCode value. Within the MainWindow class, this F2Key field is used instead of sprinkling KeyCode.F2 directly in input handling, improving readability and making future key-rebinding easier to manage in one place. + +## Remarks +This symbol centralizes the F2-key representation, reducing duplication and making the code intent clear when handling keyboard input. As a private const, it is inlined at all call sites and cannot be reassigned at runtime, preserving a stable mapping inside the class. It helps decouple the key's meaning from its concrete enum value, so refactoring the underlying KeyCode reference requires changing only this single declaration. + +## Notes +- Const fields are implicitly static and are inlined at compile time. If you need to support runtime reconfiguration of the key binding, convert this to a visible, non-const field or a configurable option. + +--- + +### SlashCommands +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly string[] SlashCommands = + [ + "/status", "/nick", "/color", "/theme", "/send", "/me", "/banner", + "/avatar", "/profile", "/servers", "/join", "/passwd", "/leave", "/clear", "/size", "/downloadpath", + "/topic", "/users", "/kick", "/ban", "/unban", + "/mute", "/unmute", "/role", "/invite", "/export", "/deleteaccount", + "/nuke", "/test-sound", "/quit", "/help" + ] +``` + + +SlashCommands is a private static readonly array of strings that enumerates the available slash commands used by the tab-autocomplete in the main window. The UI consults this list to offer command suggestions as the user types a leading slash. + +## Remarks +This centralized catalog ensures consistency across the autocomplete experience and acts as the single source of truth for which commands are supported. Its private scope keeps coupling tight to the UI implementation, and the readonly modifier prevents reassigning the array reference at runtime, preserving the integrity of the command set. The list includes commands like /status, /nick, /color, /theme, /send, /me, /banner, /avatar, /profile, /servers, /join, /passwd, /leave, /clear, /size, /downloadpath, /topic, /users, /kick, /ban, /unban, /mute, /unmute, /role, /invite, /export, /deleteaccount, /nuke, /test-sound, /quit, and /help. + +## Notes +- The initializer syntax shown in the snippet uses square brackets [], which is not valid in C# for an array initializer; the actual source should use a braces-based initializer such as: private static readonly string[] SlashCommands = new[] { "/status", "/nick", ... } or private static readonly string[] SlashCommands = { "/status", "/nick", ... }. + +--- + +### SpinnerFrames +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly string[] SpinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] +``` + + +SpinnerFrames defines the frames of the Braille spinner shown while the connection is in a transitional state. Use this sequence as the source of frames for a timer-driven animation in the UI when signaling a transitional connection state; external code should not rely on this private field directly. + +## Remarks +SpinnerFrames centralizes the frame sequence for the connection-status animation, enabling a single place to tweak the visual rhythm without touching animation logic in multiple places. Its private, static readonly nature encapsulates the detail of the glyphs from consumers and ensures consistency across any UI updates that rely on this spinner. The glyphs are Unicode braille patterns, chosen to render as a compact and legible motion, but their appearance depends on font support in the host UI. + +## Notes +- Because the field is readonly, you cannot reassign SpinnerFrames to a new array, but its contents can still be mutated if code within the class changes elements; to enforce true immutability consider exposing as `IReadOnlyList` or copying to an immutable collection. +- Braille glyph rendering depends on font support; ensure the UI uses a font that includes these characters, otherwise fallback glyphs will appear. + +--- + +### StatusActivityAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusActivityAttr = new(new Color(80, 200, 220), Color.None) +``` + + +StatusActivityAttr is a private static readonly field that holds a preconfigured Attribute instance used to style status-activity indicators in the UI. It is initialized with a Color(80, 200, 220) and a secondary color of Color.None, providing a consistent visual token that other UI components can apply without duplicating construction logic. + +## Remarks +It centralizes the styling token for status activity, ensuring a uniform look across the MainWindow's status displays. Because the field is static and readonly, the same Attribute instance is reused by all usages within its declaring type, reducing allocations and keeping styling decisions centralized. If the Attribute type is mutable, modifications to the instance would propagate to every consumer; prefer treating StatusActivityAttr as effectively immutable or clone it when variations are required. + +## Notes +- This field is private; it is intended for internal use within its containing type. +- Mutating the underlying Attribute would affect all referents of StatusActivityAttr if allowed. +- If you need a different color or variant, instantiate a new Attribute rather than adjusting this shared field. + +--- + +### StatusBrandAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusBrandAttr = new(new Color(218, 165, 32), Color.None) +``` + + +This private static readonly field holds a pre-constructed Attribute instance used to apply the application's status branding color in the UI. It centralizes the gold brand color (RGB 218,165,32) and uses Color.None for the secondary color, enabling consistent styling of status indicators across MainWindow without repeatedly allocating new Attribute objects. + +## Remarks +StatusBrandAttr serves as a small branding primitive: it encapsulates the branding color data in a single, shared value so UI rendering code can consistently decorate status indicators. As a private member, its usage is confined to the class, reducing risk of styling drift and making updates to the brand color straightforward. The static readonly pattern also avoids per-instance allocations, which helps keep the UI responsive during frequent status refreshes. + +## Notes +- This field is private; external code cannot access StatusBrandAttr. If you need external reuse, add an accessor or an API that exposes the color or attribute. +- Color.None is used as the secondary color; callers should not rely on a non-null accent color being provided through this attribute. +- Because it's static and initialized inline, the field is created once per AppDomain; changes to the initializer are global to the class consumers. + +--- + +### StatusConnectedAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusConnectedAttr = new(new Color(0, 200, 0), Color.None) +``` + + +StatusConnectedAttr is a private static readonly field that provides a prebuilt Attribute instance representing the UI styling for a connected status. It is constructed with a green primary color (0, 200, 0) and Color.None as the secondary color, and it is intended to be reused wherever a connected indicator is needed in the MainWindow UI. + +## Remarks +Centralizes the appearance of the connected-state styling to avoid duplicating color values across the UI. Being static readonly, it is allocated once and reused, which reduces allocations during frequent UI updates. As a private member, it keeps concerns localized to MainWindow, making it easy to swap or adjust the connected appearance in one place if the theme changes. + +--- + +### StatusDisconnectedAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusDisconnectedAttr = new(new Color(220, 50, 50), Color.None) +``` + + +StatusDisconnectedAttr is a private static readonly Attribute that encapsulates the UI styling used to communicate a disconnected state in MainWindow. It specifies a reddish foreground color (RGB 220, 50, 50) and no background, enabling a clear, consistent visual cue when the application loses its connection. + +## Remarks +This member centralizes the visual representation of the 'disconnected' state, ensuring all indicators share the same look. Its static readonly nature guarantees the attribute is created once and reused, promoting performance and consistency across the UI. Because the field is private, it is not directly reusable by other components; if cross-component reuse is needed, consider extracting the styling into a shared resource or exposing a controlled accessor. + +## Notes +- Not accessible outside the declaring type; if you need to reuse this styling elsewhere, factor it into a shared resource or provide a public accessor. + +--- + +### StatusMentionAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusMentionAttr = new(new Color(230, 140, 60), Color.None) +``` + + +StatusMentionAttr defines a shared, immutable Attribute instance used to render status mentions with a warm orange color in the UI. A developer would reference this field when they need a consistent highlight for status mentions instead of constructing a new Attribute each time. + +## Remarks +Centralizes the visual treatment for status mentions, ensuring consistent appearance across the UI and simplifying future theming. Because the field is static readonly, the color choice is determined at type initialization and cannot be changed at runtime, which prevents accidental mutation. Keeping the field private confines its usage to the containing type, making the intended styling an internal concern that can be adjusted without leaking implementation details. + +## Notes +- The field is private, so external consumers cannot reference it directly; reuse must occur within the declaring class or through a controlled API. +- The color is baked into the initialization; updates require recompilation, so plan color theming accordingly. + +--- + +### StatusTransitionalAttr +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private static readonly Attribute StatusTransitionalAttr = new(new Color(220, 180, 0), Color.None) +``` + + +StatusTransitionalAttr is a private static readonly Attribute that encapsulates the visual styling for elements representing a transitional state in the EchoHub client’s main window. It is initialized with an amber color (RGB 220, 180, 0) and a secondary color of Color.None, providing a single, reusable styling token to ensure consistent amber emphasis for in-progress or transitioning UI elements rather than sprinkling color literals throughout the code. + +## Remarks +By centralizing the transitional-state styling in a single field, the codebase gains a clear semantic signal for 'in-progress' statuses and can adapt to theme changes in one place. Because StatusTransitionalAttr is static and readonly, it acts as a stable styling token that can be applied wherever a transitional state needs highlighting without risking inconsistencies. The amber color choice communicates a cautionary or temporary state to users, and the absence of a secondary color keeps the emphasis on the primary transition cue. + +## Notes +- The field is private to MainWindow.cs; external code cannot reuse StatusTransitionalAttr directly. +- The second constructor argument is Color.None; its exact meaning depends on the Attribute API—consult its documentation if you need to extend this with a secondary color or outline. + +--- + +### TabKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode TabKey = KeyCode.Tab +``` + + +TabKey is a private constant alias for KeyCode.Tab used within the class to refer to the Tab key in a more readable and centralized way. It maps directly to the Tab key code and is typically used wherever the code needs to detect or respond to tab-navigation input without scattering KeyCode.Tab throughout the logic. + +## Remarks + +By providing a private const alias, this symbol communicates intent (tab-navigation handling) while keeping the public surface area uncluttered. It also ensures the tab key value is inlined at call sites for performance, without exposing the alias to consumers. + +## Notes + +- Const inlining: TabKey's value is baked into call sites; changing KeyCode.Tab in the framework requires recompilation to reflect the new value. +- Scope: TabKey is private; it's not accessible outside this class. If cross-class usage is needed, consider exposing it or using KeyCode.Tab directly. + +--- + +### UsersPanelWidth +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const int UsersPanelWidth = 22 +``` + + +Defines the fixed width of the Users panel in the main window UI. Use this constant when sizing or laying out the Users panel to ensure a consistent width without sprinkling magic numbers in the UI code; it is a private const within MainWindow.cs, so its value is inlined at compile time and encapsulated from external code. + +## Remarks +Centralizing this width as a private constant prevents magic numbers from scattering through layout logic and clarifies the intent behind the panel's sizing. It keeps the responsibility for the UI's sizing localized to MainWindow.cs, reducing cross-cutting dependencies. When design changes are needed, updating this single constant updates all layout paths that reference it, lowering the risk of inconsistent widths. It also communicates that this width is a design-time decision rather than a user-configurable setting. + +## Notes +- Because it's const, the value is baked into compiled code at each usage, so changing it requires recompilation of all assemblies that reference it. +- Being private, external classes cannot rely on this constant; if sharing is needed, consider making it internal or exposing it via a property. + +--- + +## ClickChannelRegex +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +[GeneratedRegex(@"(? **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** method + +```csharp +[GeneratedRegex(@"(? **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +internal static readonly string AppVersion = + typeof(MainWindow).Assembly.GetName().Version?.ToString(3) ?? "?" +``` + + +AppVersion is a read-only string that captures the application's version by reading the MainWindow assembly version and formatting it as major.minor.build. If the version isn’t available, it falls back to a single question mark. Because it is internal, static, and readonly, the value is computed once and can be consumed by UI code or logging without repeating assembly lookups. A developer would reach for it when displaying the application version (for example in an About dialog) or when including the version in diagnostic output. + +## Remarks +It serves as a centralized, read-only source of the app’s version for the UI layer, ensuring a single, consistent string is used across dialogs and logs rather than duplicating assembly-version lookups. + +--- + +## CtrlKKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode CtrlKKey = KeyCode.K | KeyCode.CtrlMask +``` + + +Represents the keyboard shortcut Ctrl+K as a KeyCode value by combining the K key with the Ctrl modifier. This private constant centralizes the hotkey used within MainWindow, enabling the code to detect or respond to Ctrl+K without scattering the modifier logic across methods. + +## Remarks + +By centralizing the shortcut into CtrlKKey, the codebase avoids duplicating the same key-combination logic and makes future changes straightforward (e.g., changing the shortcut would only require updating this single declaration). The naming makes intent clear: it is a Control-K hotkey, distinct from plain K or other modifiers. + +## Notes + +- Private scope means external code cannot rely on this constant; if external access is needed, expose a public API or event. +- The value depends on the KeyCode and CtrlMask semantics of the project's input system; confirm that CtrlMask is the intended modifier representation to avoid misdetections on other platforms. + +--- + +## DefaultInputTitle +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const string DefaultInputTitle = "Message │ Enter=send │ Tab=complete │ Ctrl+K=search │ F6=pick message" +``` + + +This private constant defines the default text shown for the message input title in the main window. It provides an on-screen cue about how to interact with the input, listing shortcuts such as Enter to send, Tab to complete, Ctrl+K to search, and F6 to pick a message, which helps users discover available actions without opening a help screen. + +## Remarks +Centralizing this label ensures consistent user guidance and avoids duplicating the hint in multiple places. Because the field is private and declared as a const, its value is baked into the assembly and cannot be changed at runtime or localized without refactoring to resources. If localization or runtime configurability is required, this should be moved to a resource string or a configuration mechanism and wired into the UI initialization. + +## Notes +- Hard-coded strings hinder localization; consider turning this into a resource string if multi-language support is needed. +- As a private const, the value is fixed at compile time; changing the default requires recompilation and re-deployment. + +--- + +## F6Key +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode F6Key = KeyCode.F6 +``` + + +F6Key is a private compile-time constant that represents the F6 keyboard key. Use F6Key in input-handling logic within MainWindow to detect the F6 press instead of sprinkling the literal KeyCode.F6 throughout the code. + +## Remarks +Centralizes the key mapping to avoid duplicating KeyCode.F6 and to express intent clearly within the class. Since it is private and const, its value is inlined at compile time and not exposed publicly, keeping the wiring internal to MainWindow. If the F6 binding ever needs to be shared or changed, you would introduce a more general configuration mechanism or expose a public abstraction rather than duplicating the literal in multiple places. + +## Example +```csharp +// Example: demonstrate using the F6Key constant in a simple comparison +KeyCode current = KeyCode.F6; +if (current == F6Key) +{ + // handle F6 action +} +``` + +## Notes +- As a const, the value is baked into the assembly; changing it requires recompilation. +- Because it's private, external code cannot rely on this constant; testing and usage should interact with the class's public surface that uses F6Key. + + +--- + +## NewlineKey +> **File:** `src/EchoHub.Client/UI/MainWindow.cs` +> **Kind:** field + +```csharp +private const KeyCode NewlineKey = KeyCode.N | KeyCode.CtrlMask +``` + + +NewlineKey is a private compile-time constant that represents the keyboard shortcut used to insert a newline in the UI. It encodes the N key combined with the Ctrl modifier by performing a bitwise OR between KeyCode.N and KeyCode.CtrlMask, allowing input handling to recognize the Ctrl+N shortcut as a single KeyCode value rather than separate checks for a key and a modifier. + +## Remarks +Centralizes the shortcut in a single symbol, reducing duplication and avoiding magic numbers in input logic. Being private, it remains an implementation detail of the MainWindow UI, so external code should not rely on it. The input-handling code likely compares the current KeyCode to NewlineKey to trigger newline insertion; using a named constant makes the intent explicit and easier to modify if the shortcut changes. + +## Notes +- The value is a compile-time constant; changing the shortcut requires modifying the code and recompiling. +- The combo uses KeyCode.CtrlMask; ensure consistency with other Ctrl-modified shortcuts in the same area. +- On platforms where modifier handling differs, verify that Ctrl+N is recognized as intended. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Constants/HubConstants.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Constants/HubConstants.cs.md new file mode 100644 index 0000000..16fd638 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Constants/HubConstants.cs.md @@ -0,0 +1,19 @@ +# HubConstants + +> **File:** `src/EchoHub.Core/Constants/HubConstants.cs` +> **Kind:** class + +```csharp +public static class HubConstants +``` + + +HubConstants is a static container for global constants used by the chat hub to configure limits, paths, and feature boundaries. It provides values such as the hub path, default channel, and various size and constraint limits, ensuring consistent behavior across components and avoiding scattered magic numbers. + +## Remarks +HubConstants centralizes cross-cutting, tunable values so changes propagate consistently across messaging validation, content embedding, and endpoint configuration. Because these are compile-time constants, they are not sourced from runtime configuration; if you need different behavior per deployment, introduce a separate configuration mechanism rather than altering these constants at runtime. + +## Notes +- The distinction between MaxMessageNewlines (30) and MaxConsecutiveNewlines (1) matters: the first limits overall newline usage, the second limits consecutive newline runs. +- Size limits are per-file (e.g., MaxImageSizeBytes, MaxAudioFileSizeBytes, MaxFileSizeBytes) and guide validation and storage decisions; never assume a single cap covers all attachment types. +- IrcConnectionIdPrefix is used by the presence tracker to distinguish IRC gateway connections from native SignalR clients; ensure prefix checks rather than simple contains checks to avoid misclassification. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Constants/MessageConventions.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Constants/MessageConventions.cs.md new file mode 100644 index 0000000..ab95b11 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Constants/MessageConventions.cs.md @@ -0,0 +1,30 @@ +# MessageConventions + +> **File:** `src/EchoHub.Core/Constants/MessageConventions.cs` +> **Kind:** class + +```csharp +public static class MessageConventions +``` + + +Cross-protocol message conventions are centralized in this static helper. It provides formatting and parsing for IRC CTCP ACTION-style messages, so /me-like actions render consistently across clients. Action messages are stored as the CTCP framing: 0x01 + "ACTION " + text + 0x01; MessageConventions.FormatAction(text) wraps a plain text string in that payload, and TryParseAction(content, out actionText) extracts the inner text when the content matches the framing. In end-to-end encrypted rooms the action marker travels with the text, preserving semantics. + +## Remarks +- This abstraction prevents scattering the CTCP ACTION framing constants across the codebase and offers a single source of truth for how action messages are stored and read. +- It isolates the low-level framing from higher-level message handling, making testing and future changes safer and easier. +- The parsing path uses ordinal string comparisons and explicitly requires both the proper prefix and suffix, plus non-empty inner text, to succeed. + +## Example +```csharp +var action = MessageConventions.FormatAction("waves"); +if (MessageConventions.TryParseAction(action, out var text)) +{ + // text == "waves" +} +``` + +## Notes +- TryParseAction(content, out actionText) returns true only if the content starts with ActionPrefix, ends with ActionSuffix, and the extracted inner text has length > 0; otherwise actionText is null and the method returns false. +- The behavior relies on ordinal comparisons to avoid culture-related differences in prefix/suffix checks. +- The inner action text can contain arbitrary characters; the method only enforces the framing and non-emptiness of the payload. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Constants/ValidationConstants.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Constants/ValidationConstants.cs.md new file mode 100644 index 0000000..b4a0fe8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Constants/ValidationConstants.cs.md @@ -0,0 +1,20 @@ +# ValidationConstants + +> **File:** `src/EchoHub.Core/Constants/ValidationConstants.cs` +> **Kind:** class + +```csharp +public static partial class ValidationConstants +``` + + +ValidationConstants is a centralized, static container for validation constraints used throughout the EchoHub.Core domain. It defines reusable patterns for usernames, channel names, and hex color codes, as well as a set of length limits governing passwords, display names, bios, statuses, channel topics, and chat history. The included GeneratedRegex methods expose precompiled Regex instances derived from those patterns, enabling fast, consistent validation without incurring per-call regex compilation. + +## Remarks +ValidationConstants provides a single source of truth for input validation. By offloading regex compilation to source generation, it avoids runtime overhead while keeping the validation rules easily discoverable and consistent across the codebase. + +The class is static and partial, so callers simply reference ValidationConstants.UsernameRegex(), ValidationConstants.ChannelNameRegex(), and ValidationConstants.HexColorRegex() to obtain ready-to-use Regex instances. + +## Notes +- GeneratedRegex provides compile-time-compiled Regex instances, which improves performance by avoiding repeated regex compilation at runtime. +- Updating any constraint here propagates the change to all validation sites, ensuring consistency; do not duplicate rules elsewhere. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChannelService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChannelService.cs.md new file mode 100644 index 0000000..19003f4 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChannelService.cs.md @@ -0,0 +1,121 @@ +# IChannelService.cs + +> **Source:** `src/EchoHub.Core/Contracts/IChannelService.cs` + +*Figure: How IChannelService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +IChannelService["IChannelService: entry"] +IChannelService -->|"GetChannelsAsync"| PaginatedResponse["PaginatedResponse"] +PaginatedResponse -->|"items"| ChannelDto["ChannelDto"] +IChannelService -->|"GetChannelByNameAsync"| ChannelDto +IChannelService -->|"CreateChannelAsync / UpdateTopicAsync / SetChannelPasswordAsync / RekeyChannelAsync / DeleteChannelAsync"| ChannelOperationResult["ChannelOperationResult"] +IChannelService -->|"GetChannelListAsync"| ChannelListItem["List"] +IChannelService -->|"GetChannelMetaAsync"| ChannelMetaDto["ChannelMetaDto"] +IChannelService -->|"GetChannelCryptoAsync / GetChannelKeyEnvelopeAsync"| ChannelCryptoDto["ChannelCryptoDto"] +IChannelService -->|"EnsureSystemChannelAsync"| Channel["Ensure or create server-managed Channel"] +Channel -->|"returns"| ChannelDto +``` + +## Contents + +- [IChannelService](#ichannelservice) +- [ChannelListItem](#channellistitem) + +--- + +## IChannelService +> **File:** `src/EchoHub.Core/Contracts/IChannelService.cs` +> **Kind:** interface + +```csharp +public interface IChannelService +``` + + +Provides an asynchronous API for creating, updating, deleting and querying chat channels, managing membership, and exposing channel encryption metadata. Implement this interface to centralize channel lifecycle, access control and crypto-envelope access rather than manipulating persistence or membership directly. + +## Remarks +The interface groups CRUD operations, read/query methods, membership checks, and crypto-related lookups so callers can depend on a single abstraction for channel business rules. Mutating methods return ChannelOperationResult (which carries IsSuccess and factory helpers) to make success/failure handling explicit; query methods return lightweight DTOs or tuples for simple lookups. EnsureSystemChannelAsync is a server-managed path that ensures required system channels exist and prevents server content from being written into user-owned rooms. + +## Example +```csharp +// Create a public channel and inspect the operation result +var createResult = await channelService.CreateChannelAsync(creatorUserId, "general", "General discussion", true); +if (createResult.IsSuccess) +{ + var created = createResult; // ChannelOperationResult.Success contains the created ChannelDto +} +else +{ + // handle failure +} + +// Ensure membership for a user (third parameter is the optional password/credential) +var membership = await channelService.EnsureChannelMembershipAsync(userId, "general", null); +if (membership.Success) +{ + // user is a member or was added +} +else if (membership.PasswordRequired) +{ + // prompt for password and retry +} +else +{ + // membership failed; membership.Error contains a message +} +``` + +## Notes +- Always check ChannelOperationResult.IsSuccess before assuming a mutating operation succeeded; use the provided factory helpers on ChannelOperationResult to construct success/failure values. +- Methods that return encryption metadata (encryption salt, wrapped room key) expose envelopes, not raw symmetric keys; treat any secrets derived from these values securely. +- The source contains redacted/truncated text in some method signatures (CreateChannelAsync and EnsureChannelMembershipAsync). Verify the real parameter names and optional overloads in the codebase before calling those methods. + + +--- + +## ChannelListItem +> **File:** `src/EchoHub.Core/Contracts/IChannelService.cs` +> **Kind:** record + +```csharp +public record ChannelListItem(string Name, string? Topic, int OnlineCount, bool IsPublic = true, bool IsProtected = false) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Name` | `string` | — | +| `Topic` | `string?` | — | +| `OnlineCount` | `int` | — | +| `IsPublic` | `bool` | `true` | +| `IsProtected` | `bool` | `false` | + + +ChannelListItem is an immutable value that represents a single entry in a channel list. It carries the core metadata needed to display or transport channel information: the channel Name, an optional Topic, the current OnlineCount, and two visibility flags (IsPublic and IsProtected) which default to true and false respectively. Use this type whenever you need a concise, stable descriptor of a channel for UI lists, payloads, or comparisons, rather than a mutable or richer domain model. + +## Remarks +ChannelListItem benefits from value-based equality inherent to records, so two items with identical fields compare as equal, which helps with list diffs, caching, and deduplication. The Topic is nullable to accommodate channels without a topic. Defaults (IsPublic = true, IsProtected = false) reflect common expectations for channels unless stated otherwise. Because this is a record, instances are immutable; to reflect changes (for example, a rising OnlineCount), create a new instance via a with-expression. + +## Example +```csharp +// Basic construction with defaults for visibility flags +var item = new ChannelListItem("general", "Public channel for announcements", 12); + +// Or using named arguments for clarity +var itemNamed = new ChannelListItem(Name: "general", Topic: "Public channel for announcements", OnlineCount: 12); + +// Immutability in action: create a modified copy with an updated OnlineCount +var updated = item with { OnlineCount = 13 }; +``` + +## Notes +- Topic is nullable; pass null if the channel has no topic. +- To reflect a change in OnlineCount or other fields, use the with-expression since ChannelListItem is immutable. + + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatBroadcaster.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatBroadcaster.cs.md new file mode 100644 index 0000000..995df3f --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatBroadcaster.cs.md @@ -0,0 +1,35 @@ +# IChatBroadcaster + +> **File:** `src/EchoHub.Core/Contracts/IChatBroadcaster.cs` +> **Kind:** interface + +```csharp +public interface IChatBroadcaster +``` + + +An abstraction for broadcasting chat-related events and notifications to connected clients. Implementations deliver channel messages, presence updates, moderation events and connection-specific errors or disconnects to the appropriate recipients; use this interface when you want hub/transport-agnostic broadcasting logic (for example to decouple business logic from SignalR or another realtime transport). + +## Remarks +This interface centralizes all outbound chat notifications the server emits: channel messages, user join/leave/presence events, channel lifecycle events (updated, deleted, nuked), moderation notifications (kicked, banned), message deletions, error messages to a particular connection, and forced disconnects. It exists to keep broadcasting responsibilities in one place so higher-level code can invoke intent ("send this message to the channel" or "force-disconnect these connections") without knowing how connections are routed or how the underlying transport addresses individual connections or groups. + +Implementations must honor the documented routing hints (for example, do not echo a message back to an excluded connection when excludeConnectionId is supplied). Use the channelName and connectionId parameters to determine recipients; SendErrorAsync targets a single connection, while ForceDisconnectUserAsync targets a set of connection ids. + +## Example +```csharp +// typical usage from server-side chat logic +// (messageDto and presenceDto are prepared elsewhere) +await broadcaster.SendMessageToChannelAsync("#general", messageDto, excludeConnectionId: currentConnectionId); +await broadcaster.SendUserJoinedAsync("#general", "alice", presenceDto, excludeConnectionId: currentConnectionId); + +// send an error to a single connection +await broadcaster.SendErrorAsync(connectionId, "You are not authorized to perform that action."); + +// force-disconnect multiple connections for a user session cleanup +await broadcaster.ForceDisconnectUserAsync(new List { connA, connB }, "Session revoked"); +``` + +## Notes +- excludeConnectionId is documented for SendMessageToChannelAsync to avoid echoing the origin connection; other methods that lack an exclude parameter (for example SendUserLeftAsync) will be delivered to all intended recipients unless an implementation-specific filter is applied. +- SendUserStatusChangedAsync accepts a list of channel names so presence updates can be routed only to relevant channels; callers should pass the minimal set of channels that need the update to reduce unnecessary traffic. +- Implementations should be asynchronous and non-blocking; broadcasting to many recipients may be best-effort and not transactional across multiple method calls. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatService.cs.md new file mode 100644 index 0000000..5255846 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IChatService.cs.md @@ -0,0 +1,11 @@ +# IChatService + +> **File:** `src/EchoHub.Core/Contracts/IChatService.cs` +> **Kind:** interface + +```csharp +public interface IChatService +``` + + +I have submitted the narrative documentation for IChatService and raised a critical flag about the malformed/redacted parameter in JoinChannelAsync. The documentation includes description, remarks, an example usage, and notes that point out the signature issue and nullable-return semantics for callers to verify against the concrete implementation. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md new file mode 100644 index 0000000..2fbbc96 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md @@ -0,0 +1,60 @@ +# IEchoHubClient + +> **File:** `src/EchoHub.Core/Contracts/IEchoHubClient.cs` +> **Kind:** interface + +```csharp +public interface IEchoHubClient +``` + + +Represents the set of callbacks the server can invoke on a connected client. Implement this interface on client-side code that subscribes to the server's real-time hub so the client can react to server-initiated events such as incoming messages, presence updates, channel changes, and administrative actions. + +## Remarks +This interface defines a stable, strongly-typed surface for server-to-client notifications. Each method corresponds to a distinct event the server may raise (message delivery, user presence changes, channel lifecycle events, errors, and forced disconnects). Implementations keep client-side handling decoupled from the transport layer and allow the server to call back into client logic without embedding client behavior in server code. + +## Example +```csharp +// Minimal client-side implementation that logs events; real handlers should avoid long-running work. +public class EchoClientHandler : IEchoHubClient +{ + public Task ReceiveMessage(MessageDto message) + { + Console.WriteLine($"Received message: {message}"); + return Task.CompletedTask; + } + + public Task UserJoined(string channelName, string username, UserPresenceDto? presence) + { + Console.WriteLine($"{username} joined {channelName}"); + return Task.CompletedTask; + } + + public Task UserLeft(string channelName, string username) + { + Console.WriteLine($"{username} left {channelName}"); + return Task.CompletedTask; + } + + // Other members can be implemented similarly; keep handlers quick and non-blocking. + public Task ChannelUpdated(ChannelDto channel) => Task.CompletedTask; + public Task UserStatusChanged(UserPresenceDto presence) => Task.CompletedTask; + public Task UserKicked(string channelName, string username, string? reason) => Task.CompletedTask; + public Task UserBanned(string username, string? reason) => Task.CompletedTask; + public Task MessageDeleted(string channelName, Guid messageId) => Task.CompletedTask; + public Task ChannelDeleted(string channelName) => Task.CompletedTask; + public Task ChannelNuked(string channelName) => Task.CompletedTask; + public Task ForceDisconnect(string reason) => Task.CompletedTask; + public Task Error(string message) + { + Console.Error.WriteLine(message); + return Task.CompletedTask; + } +} +``` + +## Notes +- Handlers are asynchronous (return Task): keep implementations short and non-blocking to avoid delaying the server's invocation path. +- Nullable parameters (e.g. UserPresenceDto? and string?) may be null; check before accessing members. +- Server-driven callbacks can occur concurrently; ensure any shared client state mutated by these methods is accessed in a thread-safe manner. +- Catch and handle exceptions inside handlers — unhandled exceptions may affect the connection or be observable by the server depending on the transport behavior. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md new file mode 100644 index 0000000..68bb85d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md @@ -0,0 +1,35 @@ +# IMessageEncryptionService + +> **File:** `src/EchoHub.Core/Contracts/IMessageEncryptionService.cs` +> **Kind:** interface + +```csharp +public interface IMessageEncryptionService +``` + + +IMessageEncryptionService defines a pluggable contract for encrypting and decrypting string data, using a distinctive prefix to mark encrypted content so callers can distinguish ciphertext from plain text and pass through non-encrypted values safely. It also exposes EncryptDatabaseEnabled to reflect the server setting for encrypting database content at rest, and provides nullable variants to handle optional fields without extra null checks. + +## Remarks +This interface acts as a thin abstraction that isolates encryption concerns from business logic, enabling swap-in of different algorithms or key-management strategies without touching call sites. The public CiphertextPrefix and the Decrypt pass-through behavior for non-encrypted values provide a simple, deterministic convention for distinguishing encrypted payloads. The nullable variants help preserve nullability semantics in data-transfer surfaces while still enabling encryption when a value is present. + +## Example +```csharp +// Given an IMessageEncryptionService implementation (injected or resolved via DI) +IMessageEncryptionService service = ...; + +string plain = "customer-secret"; +string cipher = service.Encrypt(plain); +string decrypted = service.Decrypt(cipher); // == plain + +string? nullablePlain = null; +string? nullableCipher = service.EncryptNullable(nullablePlain); // null +string? nullableDecrypted = service.DecryptNullable(nullableCipher); // null + +bool atRest = service.EncryptDatabaseEnabled; +``` + +## Notes +- Decrypt will pass through values that do not start with the CiphertextPrefix. +- EncryptNullable/DecryptNullable gracefully handle nulls by returning null. +- EncryptDatabaseEnabled indicates whether server-side encrypt-at-rest is active; use it to guide storage strategies. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IUserService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IUserService.cs.md new file mode 100644 index 0000000..624a30d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Contracts/IUserService.cs.md @@ -0,0 +1,37 @@ +# IUserService + +> **File:** `src/EchoHub.Core/Contracts/IUserService.cs` +> **Kind:** interface + +```csharp +public interface IUserService +``` + + +IUserService defines a contract for asynchronous user-management operations within EchoHub.Core. It exposes methods to register and authenticate users, retrieve profiles by username or by ID, update profile details, and set a user's avatar. Implementations of this interface serve as the single logical boundary for user lifecycle concerns, allowing REST endpoints and the IRC gateway to funnel through a consistent surface and enabling easier testing and swapping of storage or identity providers. The RegisterUserAsync method acknowledges server configuration: when Server:Registration is set to "invite", an inviteCode is required; when set to "closed", new accounts are rejected; all such flows funnel through this service. + +## Remarks +By centralizing these operations behind IUserService, the rest of the system depends on a stable, testable contract rather than concrete data stores or authentication mechanisms. It coordinates with the UserOperationResult wrapper to communicate success or failure and, for retrieval operations, to surface user data returned on success, keeping error handling consistent across the application. + +## Example +```csharp +// Example usage of the IUserService contract +var result = await userService.RegisterUserAsync("alice", "P@ssw0rd", displayName: "Alice", inviteCode: "INV-123"); +if (result.IsSuccess) +{ + // registration succeeded; you can proceed with login or profile fetch +} +``` + +```csharp +var profile = await userService.GetUserProfileAsync("alice"); +if (profile != null) +{ + // use profile data +} +``` + +## Notes +- If you call UpdateProfileAsync with all arguments as null, the operation may be a no-op; only pass the fields you intend to update. +- GetUserByIdAsync returns a UserProfileDto?; handle the null case when the user does not exist. +- For registration, ensure your server's registration policy (invite vs closed) is aligned with your inviteCode usage; otherwise registration may fail. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md new file mode 100644 index 0000000..a0e7746 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AccountDtos.cs.md @@ -0,0 +1,178 @@ +# AccountDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/AccountDtos.cs` + +## Contents + +- [DeleteAccountRequest](#deleteaccountrequest) +- [ExportedAttachmentDto](#exportedattachmentdto) +- [ExportedMessageDto](#exportedmessagedto) +- [UserDataExportDto](#userdataexportdto) + +--- + +## DeleteAccountRequest +> **File:** `src/EchoHub.Core/DTOs/AccountDtos.cs` +> **Kind:** record + +```csharp +public record DeleteAccountRequest(string Password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Password` | `string` | — | + + +This record models the password-confirmation payload required when a user initiates destructive self-service account actions (such as deleting their account). It captures the password as a single field to prove the user’s intent before the action is executed. + +## Remarks +DeleteAccountRequest encapsulates a sensitive credential within a lightweight boundary object to keep password handling explicit in the delete workflow. By isolating the password in a dedicated payload, the system can perform authentication checks, auditing, and policy enforcement at the appropriate boundary. The record is immutable and minimal (a single Password property), which simplifies model binding and reduces the surface area for accidental data exposure. + +## Example +```csharp +// When initiating a delete flow, supply the password for re-confirmation. +var request = new DeleteAccountRequest("P@ssw0rd!"); +``` + +## Notes +- Treat the Password as sensitive; avoid logging or exposing it in responses. +- Use this payload only in the delete flow; ensure that the password validation is performed server-side before performing the destructive action. + +--- + +## ExportedAttachmentDto +> **File:** `src/EchoHub.Core/DTOs/AccountDtos.cs` +> **Kind:** record + +```csharp +public record ExportedAttachmentDto( + string FileName, + string Url, + long FileSize, + string Kind, + string ChannelName, + DateTimeOffset SentAt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `FileName` | `string` | — | +| `Url` | `string` | — | +| `FileSize` | `long` | — | +| `Kind` | `string` | — | +| `ChannelName` | `string` | — | +| `SentAt` | `DateTimeOffset` | — | + + +Represents the metadata of an attachment that has been exported from a channel. It groups the file name, a URL to access the file, the file size in bytes, a textual kind descriptor, the originating channel name, and the timestamp when it was sent. Use this DTO when returning or transmitting export results to clients or cross-system boundaries to ensure a stable, serializable shape that is decoupled from internal domain models. + +## Remarks +- Being a record, instances are immutable and equality is value-based, making it ideal for transport across layers or for caching export results. It serves as a clean contract between the export process and API or consumer layers. +- It acts as a boundary object, decoupling presentation/API concerns from domain entities while preserving the essential attachment metadata needed by clients (name, access URL, size, kind, origin channel, and timestamp). + +## Example +```csharp +var attachment = new ExportedAttachmentDto( + FileName: "invoice.pdf", + Url: "https://cdn.example.com/exports/invoice.pdf", + FileSize: 254000, + Kind: "document", + ChannelName: "billing", + SentAt: DateTimeOffset.UtcNow +); +``` + +## Notes +- The Kind property is a free-form string; if there is a known finite set of kinds, consider introducing a dedicated enum later to avoid inconsistent values. +- FileSize is a long and should be non-negative; implement validation at boundaries if negative values could be produced by upstream systems. +- Ensure the Url is appropriate for client access (consider expiration, authentication, and CORS as needed) since this DTO surfaces a direct link to the exported attachment. + +--- + +## ExportedMessageDto +> **File:** `src/EchoHub.Core/DTOs/AccountDtos.cs` +> **Kind:** record + +```csharp +public record ExportedMessageDto( + Guid Id, + string ChannelName, + DateTimeOffset SentAt, + string Content, + Guid? ReplyToMessageId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `ChannelName` | `string` | — | +| `SentAt` | `DateTimeOffset` | — | +| `Content` | `string` | — | +| `ReplyToMessageId` | `Guid?` | — | + + +ExportedMessageDto is an immutable data transfer object that captures the essential details of a message exported from a channel: its identity (Id), the channel it came from (ChannelName), when it was sent (SentAt), the message content (Content), and an optional reference to the message it replies to (ReplyToMessageId). It serves as a serialization-friendly payload used by export or archival pipelines, decoupled from the in-memory domain model. + +## Remarks +ExportedMessageDto provides a stable contract for export pipelines by decoupling serialized data from the internal domain entities. Being a record, it benefits from value-based equality and immutability, which simplifies de-duplication and testing of exported payloads. The nullable ReplyToMessageId models the optional threading relationship: null means the message has no parent. Use ChannelName and SentAt as lightweight contextual metadata when reconstructing conversations in external systems. + +## Example +```csharp +var message = new ExportedMessageDto( + Id: Guid.NewGuid(), + ChannelName: "general", + SentAt: DateTimeOffset.UtcNow, + Content: "Hello world", + ReplyToMessageId: null +); +``` + +## Notes +- The ReplyToMessageId is nullable; null indicates no parent message. +- As a record, equality is based on all properties; two messages with identical data compare as equal. +- If you need to derive a modified copy without mutating the original, use the with-expression (e.g., var updated = message with { Content = "Updated" };). + +--- + +## UserDataExportDto +> **File:** `src/EchoHub.Core/DTOs/AccountDtos.cs` +> **Kind:** record + +```csharp +public record UserDataExportDto( + DateTimeOffset ExportedAt, + string ServerName, + UserProfileDto Profile, + List Messages, + List Attachments) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ExportedAt` | `DateTimeOffset` | — | +| [`ServerName`](../../EchoHub.Server.Irc/IrcCommandHandler.cs.md) | `string` | — | +| `Profile` | [`UserProfileDto`](ProfileDtos.cs.md) | — | +| `Messages` | `List` | — | +| `Attachments` | `List` | — | + + +Represents a persisted snapshot of a user's data as stored by the server, intended for data export or portability. It consolidates the export timestamp, the server identity, the user's profile, and the exported messages and attachments; in end-to-end encrypted rooms the message contents are ciphertext, since the server never has access to plaintext. + +## Remarks + +UserDataExportDto is an immutable data transfer object that anchors the export pipeline to the server's stored representation. By pairing profile, messages, and attachments into a single artifact, it simplifies serialization, auditing, and versioning while guarding the boundaries between storage concerns and export logic. + +## Notes + +- The Messages collection contains ciphertext for end-to-end encrypted rooms; do not decrypt on the server. Decryption and user presentation must happen client-side with proper keys. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md new file mode 100644 index 0000000..0646906 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md @@ -0,0 +1,168 @@ +# AuthDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/AuthDtos.cs` + +## Contents + +- [LoginRequest](#loginrequest) +- [LoginResponse](#loginresponse) +- [RefreshRequest](#refreshrequest) +- [RegisterRequest](#registerrequest) + +--- + +## LoginRequest +> **File:** `src/EchoHub.Core/DTOs/AuthDtos.cs` +> **Kind:** record + +```csharp +public record LoginRequest(string Username, string Password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Username` | `string` | — | +| `Password` | `string` | — | + + +Represents the credentials needed to log a user in. This immutable record carries a Username and Password and is intended to be used as a data transfer object when submitting login data to authentication endpoints. + +## Remarks + +As a positional record, LoginRequest provides value-based equality and deconstruction. It is immutable, with init-only properties, which helps prevent accidental mutation of credential data as it travels across system boundaries. Treat Password as sensitive data: avoid logging or displaying it, and ensure transport security when sending this DTO. + +## Example + +```csharp +var request = new LoginRequest("alice", "P@ssw0rd!"); +``` + +## Notes + +- Password is sensitive data; avoid logging or displaying it; mask when emitted in logs or error messages. +- This is a simple data-transfer object; it contains no business logic. + +--- + +## LoginResponse +> **File:** `src/EchoHub.Core/DTOs/AuthDtos.cs` +> **Kind:** record + +```csharp +public record LoginResponse( + string Token, + string RefreshToken, + DateTimeOffset ExpiresAt, + string Username, + string? DisplayName, + string? NicknameColor) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| [`Token`](../../EchoHub.Client/Services/ApiClient.cs.md) | `string` | — | +| `RefreshToken` | `string` | — | +| `ExpiresAt` | `DateTimeOffset` | — | +| `Username` | `string` | — | +| `DisplayName` | `string?` | — | +| `NicknameColor` | `string?` | — | + + +LoginResponse is a data transfer object that represents the server's response to a successful login. It bundles the authentication tokens (Token and RefreshToken), the token expiration moment (ExpiresAt), and the authenticated user's identity (Username), along with optional personalization fields (DisplayName and NicknameColor). This object is intended for consumption by clients to establish authenticated sessions, attach the access token to requests, refresh tokens when needed, and present user information in the UI. + +## Remarks +LoginResponse is an immutable value object (a record) whose identity is defined by its content. It cleanly separates transport concerns from domain logic, acting as a simple contract that different layers can rely on without side effects. The optional DisplayName and NicknameColor fields model user-facing personalization; callers must handle potential nulls when those fields are not provided. + +## Example +```csharp +var response = new LoginResponse( + Token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + RefreshToken: "def123-refresh", + ExpiresAt: DateTimeOffset.UtcNow.AddHours(1), + Username: "alex", + DisplayName: "Alex Doe", + NicknameColor: "#FF6A00" +); +``` + +## Notes +- DisplayName and NicknameColor may be null if the server omits them. +- Treat this type as data-only; avoid adding behavior such as validation or mutation. +- Token values are sensitive; avoid logging them and consider secure storage/handling in the client. + +--- + +## RefreshRequest +> **File:** `src/EchoHub.Core/DTOs/AuthDtos.cs` +> **Kind:** record + +```csharp +public record RefreshRequest(string RefreshToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `RefreshToken` | `string` | — | + + +RefreshRequest is a small, immutable data transfer object (a C# record) that carries a single value: the RefreshToken. It is used when a client requests a new access token from the authentication service, typically by posting this payload to the refresh endpoint. + +## Remarks +By representing the refresh payload as a dedicated type, the API boundary gains a clear, strongly-typed contract that can be validated and logged consistently. The use of a record ensures value-based equality and immutable semantics, which helps prevent accidental mutation during transport or handling and makes it straightforward to pattern-match or deconstruct if needed in higher layers. In the overall authentication flow, this DTO sits alongside other EchoHub authentication DTOs and forms the low-level transport shape for refresh token exchanges. + +## Example +```csharp +var request = new RefreshRequest("sample-refresh-token"); +``` + +## Notes +- Do not log or expose the RefreshToken; avoid writing it to logs or UI. +- Ensure the token is transmitted over HTTPS and handled only in the request body, not in URLs. +- Validate that the token is non-empty before sending to the refresh endpoint; handle nulls gracefully. + + +--- + +## RegisterRequest +> **File:** `src/EchoHub.Core/DTOs/AuthDtos.cs` +> **Kind:** record + +```csharp +public record RegisterRequest(string Username, string Password, string? DisplayName = null, string? InviteCode = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Username` | `string` | — | +| `Password` | `string` | — | +| `DisplayName` | `string?` | `null` | +| [`InviteCode`](../Models/InviteCode.cs.md) | `string?` | `null` | + + +RegisterRequest is a compact data-transfer object used to convey the information necessary to register a new user. It requires a Username and Password, and optionally accepts a DisplayName and an InviteCode. Implemented as a C# positional record, it is immutable and uses value-based equality, making it ideal for transport across API boundaries and for straightforward comparisons in tests. This DTO is typically produced by a client during registration and consumed by server-side authentication logic. The DisplayName parameter is nullable with a default of null, allowing clients to omit it; InviteCode is also nullable and used only when the onboarding flow supports invitation codes. + +## Remarks +This symbol acts as a stable contract for the registration flow: it encapsulates the required credentials and optional metadata in a single, immutable object. By using a record, equality and deconstruction align with value semantics, making it easy to compare requests and to pass them through layers without mutation. Because DisplayName and InviteCode are optional, validation often happens elsewhere, enabling flexible client behavior while preserving a clear API boundary. + +## Example +```csharp +// Typical usage with all fields +var full = new RegisterRequest("jdoe", "P@ssw0rd", "John Doe", "INVITE-42"); + +// Minimal usage: only required fields +var minimal = new RegisterRequest("jdoe", "P@ssw0rd"); +``` + +## Notes +- Do not log or leak the Password value; treat it as sensitive data and rely on secure transport and proper logging practices. +- Optional fields may be null; server-side validation should enforce any business rules regarding DisplayName or InviteCode as appropriate. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md new file mode 100644 index 0000000..1bb86b0 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md @@ -0,0 +1,598 @@ +# ChatDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/ChatDtos.cs` + +## Contents + +- [AttachmentDto](#attachmentdto) +- [ChannelCryptoDto](#channelcryptodto) +- [ChannelDto](#channeldto) +- [ChannelMetaDto](#channelmetadto) +- [CreateChannelRequest](#createchannelrequest) +- [EmbedDto](#embeddto) +- [JoinChannelResult](#joinchannelresult) +- [MessageDto](#messagedto) +- [RekeyChannelRequest](#rekeychannelrequest) +- [ReplyRefDto](#replyrefdto) +- [SendMessageRequest](#sendmessagerequest) +- [SendUrlRequest](#sendurlrequest) +- [UpdateTopicRequest](#updatetopicrequest) +- [UserDto](#userdto) + +--- + +## AttachmentDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record AttachmentDto( + AttachmentKind Kind, + string Url, + string FileName, + long FileSize, + string? AsciiPreview = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Kind` | [`AttachmentKind`](../Models/AttachmentKind.cs.md) | — | +| `Url` | `string` | — | +| `FileName` | `string` | — | +| `FileSize` | `long` | — | +| `AsciiPreview` | `string?` | `null` | + + +Represents a file attachment attached to a chat message. It carries the attachment kind, a URL to access the resource, the original file name, the size of the file, and an optional ASCII preview used for color-tag art when available. This DTO is used when composing or processing message payloads that include attachments, or when consuming message data that contains attachment metadata. In end-to-end encrypted channels the content behind the URL and the preview may be ciphertext that the server cannot read. + +## Remarks +AttachmentDto serves as a compact, immutable value object that consolidates attachment metadata for transport, storage, and rendering across UI and API boundaries. Being a record provides value-based equality, which simplifies deduplication and caching scenarios, and makes it natural to compare attachments without inspecting the entire payload. It decouples attachment handling from the message body, enabling consistent rendering and processing of attachments regardless of how the message content is structured. + +## Example +```csharp +// Example: construct an attachment DTO for a file attachment +var attachment = new AttachmentDto( + default(AttachmentKind), + "https://cdn.example.com/files/document.pdf", + "document.pdf", + 204800, + null); +``` + +## Notes +- AsciiPreview is optional; when present, it provides a text-based preview but is not guaranteed to render a full image. Clients should gracefully fall back to the URL or file name if the preview is absent. +- AttachmentDto is a record, so instances are immutable and compare by value. This supports straightforward caching and deduplication strategies across layers. + +--- + +## ChannelCryptoDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record ChannelCryptoDto(bool IsEncrypted, string? EncryptionSalt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `IsEncrypted` | `bool` | — | +| `EncryptionSalt` | `string?` | — | + + +ChannelCryptoDto carries the public cryptographic metadata required by a client to derive its join credential from a passphrase. It should be used by clients during the channel join flow to determine if a passphrase-based derivation is necessary and to access the salt used for key derivation, without ever handling the wrapped room key. + +## Remarks +This DTO isolates derivation parameters from actual keys, enabling authentication-related components to reason about how a credential is derived without touching or exposing key material. The IsEncrypted flag indicates whether a passphrase-based join is applicable, and EncryptionSalt provides the salt used in the derivation when encryption is in effect. When IsEncrypted is false, EncryptionSalt may be null, reflecting that no passphrase-based derivation is required. + +## Notes +- If IsEncrypted is true, EncryptionSalt should be non-null to derive the join credential; when false, the salt may be null. +- This is a simple data transfer object intended to convey derivation parameters safely; never serialize or expose wrapped key material. + + +--- + +## ChannelDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record ChannelDto( + Guid Id, + string Name, + string? Topic, + bool IsPublic, + int MessageCount, + DateTimeOffset CreatedAt, + bool IsProtected = false, + bool IsEncrypted = false, + bool IsSystem = false) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `Name` | `string` | — | +| `Topic` | `string?` | — | +| `IsPublic` | `bool` | — | +| `MessageCount` | `int` | — | +| `CreatedAt` | `DateTimeOffset` | — | +| `IsProtected` | `bool` | `false` | +| `IsEncrypted` | `bool` | `false` | +| `IsSystem` | `bool` | `false` | + + +ChannelDto is an immutable data transfer object that encapsulates the core metadata of a chat channel. It groups the channel’s unique identifier, display name, an optional topic, visibility, message count, and creation timestamp, together with flags that describe its characteristics (protected, encrypted, and system channels). This object is commonly produced by the server when retrieving or creating channel data and is consumed by clients and services that need a stable snapshot of a channel’s state. As a record, ChannelDto provides value-based equality and supports convenient cloning via with-expressions without mutating the original instance. + +## Remarks +ChannelDto serves as a transport-friendly abstraction that decouples channel metadata from domain models. The boolean flags encode common channel semantics: IsPublic indicates whether the channel is publicly discoverable, IsProtected denotes restricted access, IsEncrypted signals encryption usage, and IsSystem marks built-in, system-managed channels. CreatedAt represents the creation-time snapshot and should be treated as immutable; for updates, create a new ChannelDto instance (e.g., with a with-expression) rather than mutating the existing one. + +## Example +```csharp +var channel = new ChannelDto( + Id: Guid.NewGuid(), + Name: "general", + Topic: "General discussion", + IsPublic: true, + MessageCount: 482, + CreatedAt: DateTimeOffset.UtcNow, + IsProtected: false, + IsEncrypted: true, + IsSystem: false +); +``` + +## Notes +- Topic may be null; consumers should handle absence of a topic gracefully. +- ChannelDto is immutable; to derive a modified version use the with expression (e.g., channel with { Name = "new-name" }). +- Boolean flags default to false when omitted, so explicit values should reflect the actual channel semantics. + +--- + +## ChannelMetaDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record ChannelMetaDto( + Guid Id, + string Name, + string? Topic, + bool IsEncrypted, + bool IsProtected, + int MessageCount, + int UniqueUserCount, + long EstimatedSizeBytes, + DateTimeOffset CreatedAt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `Name` | `string` | — | +| `Topic` | `string?` | — | +| `IsEncrypted` | `bool` | — | +| `IsProtected` | `bool` | — | +| `MessageCount` | `int` | — | +| `UniqueUserCount` | `int` | — | +| `EstimatedSizeBytes` | `long` | — | +| `CreatedAt` | `DateTimeOffset` | — | + + +ChannelMetaDto is a data transfer object that captures human-facing metadata for a chat channel as surfaced by the /meta command. It exposes the channel's identity (Id), presentation (Name), optional description (Topic), security properties (IsEncrypted, IsProtected), participation metrics (MessageCount, UniqueUserCount), a best-effort size estimate of content (EstimatedSizeBytes), and the creation timestamp (CreatedAt). For encrypted channels, the server retains counts, timestamps, and blob sizes but cannot read the content itself; EstimatedSizeBytes is the sum of stored attachment blob sizes plus message text length, so it is an estimate rather than an exact on-disk total. + +## Remarks +This immutable record serves as a stable, client-facing contract that decouples internal storage from UI rendering. By aggregating these fields, it enables lightweight channel listings and meta views without exposing message content, while still providing enough information to gauge activity and scope. + +## Notes +- Topic may be null; clients should handle absence gracefully when rendering. +- EstimatedSizeBytes is an approximation; the value may drift as new messages or attachments are added. + +--- + +## CreateChannelRequest +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record CreateChannelRequest( + string Name, + string? Topic = null, + bool IsPublic = true, + string? [REDACTED:CONNECTION_STRING_PASSWORD] + string? EncryptionSalt = null, + string? WrappedRoomKey = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Name` | `string` | — | +| `Topic` | `string?` | `null` | +| `IsPublic` | `bool` | `true` | +| `EncryptionSalt` | `string? [REDACTED:CONNECTION_STRING_PASSWORD] + string?` | `null` | +| `WrappedRoomKey` | `string?` | `null` | + + +Represents the payload for creating a new chat channel. It encapsulates the channel name, an optional topic, a visibility flag, and optional cryptographic data used to secure channel communications. A redacted credentials field stands in for a sensitive connection password and should be supplied securely at runtime rather than stored or logged. + +## Remarks +This record is an immutable value object intended to be used as a single payload passed from client to API for channel creation. It coalesces related creation parameters in one place, facilitating validation and transport across layers while remaining independent of any particular persistence or network protocol. The redacted password field highlights a security concern: avoid exposing credentials in logs or UI surfaces; handle it through secure channels only. + +## Notes +- Name is required; Topic, IsPublic, EncryptionSalt, WrappedRoomKey are optional with sensible defaults (Topic = null, IsPublic = true, EncryptionSalt = null, WrappedRoomKey = null). +- IsPublic defaults to true; set to false to create a private channel. +- Sensitive fields (the redacted password) must be handled securely; avoid logging or exposing the value in logs or UI. + +--- + +## EmbedDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record EmbedDto( + string? SiteName, + string? Title, + string? Description, + string? ImageAscii, + string Url, + string? ThemeColor = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `SiteName` | `string?` | — | +| `Title` | `string?` | — | +| `Description` | `string?` | — | +| `ImageAscii` | `string?` | — | +| `Url` | `string` | — | +| `ThemeColor` | `string?` | `null` | + + +EmbedDto is a lightweight, immutable data carrier for the metadata needed to render a rich embed in chat messages. As a C# record, it provides value-based equality and convenient construction, making it ideal for transporting embed information across layers without mutating state. It carries optional metadata fields (SiteName, Title, Description, ImageAscii, ThemeColor) and requires a Url that points to the embed resource. + +## Remarks +This abstraction centralizes all embed-related data into a single contract, decoupling embedding details from other message payloads. By using a record, it gains structural equality and easy pattern matching, which simplifies testing and usage in render pipelines. The optional ThemeColor guides UI theming, while ImageAscii allows lightweight, ASCII-based previews when a graphical asset is unavailable. + +## Example +```csharp +var embed = new EmbedDto( + SiteName: "Aurora Gallery", + Title: "Landscape Preview", + Description: "A sample landscape embed", + ImageAscii: "[ASCII_ART]", + Url: "https://example.org/embeds/landscape", + ThemeColor: "#3366FF"); +``` + +## Notes +- All fields except Url are optional, so a minimal EmbedDto can be created with just the Url. +- Being a record, EmbedDto is immutable and supports with-expressions to create modified copies without changing the original instance. + +--- + +## JoinChannelResult +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record JoinChannelResult( + bool Success, + List History, + string? Error = null, + bool PasswordRequired = false, + string? EncryptionSalt = null, + string? WrappedRoomKey = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Success` | `bool` | — | +| `History` | `List` | — | +| `Error` | `string?` | `null` | +| `PasswordRequired` | `bool` | `false` | +| `EncryptionSalt` | `string?` | `null` | +| `WrappedRoomKey` | `string?` | `null` | + + +JoinChannelResult is a value object that conveys the outcome of attempting to join a chat channel. It exposes whether the operation succeeded, provides the channel's message history for immediate rendering, and carries optional security-related data (password requirement, encryption salt, and wrapped room key) that consumers can act on after the join completes. + +## Remarks +JoinChannelResult centralizes all information produced by a join attempt, keeping the caller decoupled from the join logic. By pairing a success flag with the History and optional security fields, it supports both happy-path UI rendering and encrypted or password-protected channels without additional payloads. The inclusion of EncryptionSalt and WrappedRoomKey suggests a workflow where the client may fetch or negotiate encryption material as part of joining, rather than as a separate round-trip. + +## Example +```csharp +// Successful join with history +List history = new List(); +var result = new JoinChannelResult(true, history); + +// Join that requires a password and includes encryption material +var secured = new JoinChannelResult(true, history, PasswordRequired: true, EncryptionSalt: \"salt123\", WrappedRoomKey: \"wrappedKey\"); +``` + +## Notes +- Error is typically non-null only when Success is false; use it to surface the failure reason to the user. +- EncryptionSalt and WrappedRoomKey are meaningful only for encrypted or password-protected channels; they may be null in plain channels. +- History should be treated as the initial set of messages to render immediately after a join; it may be empty in failure scenarios or when a channel has no prior messages. + +--- + +## MessageDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record MessageDto( + Guid Id, + string Content, + string SenderUsername, + string? SenderNicknameColor, + string ChannelName, + DateTimeOffset SentAt, + List? Attachments = null, + List? Embeds = null, + string? SenderDisplayName = null, + ReplyRefDto? ReplyTo = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `Content` | `string` | — | +| `SenderUsername` | `string` | — | +| `SenderNicknameColor` | `string?` | — | +| `ChannelName` | `string` | — | +| `SentAt` | `DateTimeOffset` | — | +| `Attachments` | `List?` | `null` | +| `Embeds` | `List?` | `null` | +| `SenderDisplayName` | `string?` | `null` | +| `ReplyTo` | `ReplyRefDto?` | `null` | + + +MessageDto is an immutable data transfer object that captures the essential details of a chat message as it moves across the EchoHub chat API surface. Implemented as a C# record, it provides value-based equality and straightforward construction for message data, making it ideal for serialization and transport between layers (e.g., API, client, and service boundaries). The object aggregates core message data such as Id, Content, SenderUsername, ChannelName, and SentAt, while also supporting optional enhancements like Attachments and Embeds, a human-friendly SenderDisplayName, and a ReplyTo reference for threaded conversations. This shape keeps message-related concerns contained in a single DTO without leaking domain internals, enabling predictable data contracts for consumers. + +## Remarks +This symbol serves as a boundary object that encapsulates a complete chat message payload, including optional media and UI hints. By composing AttachmentDto and EmbedDto, it allows rich messages to travel without forcing callers to depend on internal domain types. The use of a record emphasizes that MessageDto represents a snapshot of message data at a point in time; consumers should treat instances as immutable and, if changes are needed, create new instances. The presence of optional fields (SenderNicknameColor, Attachments, Embeds, SenderDisplayName, ReplyTo) reflects real-world variability in messaging scenarios (e.g., plain text messages, media-enabled messages, or replies). + +## Notes +- Attachments and Embeds may be null; downstream code should handle nulls or default to empty collections to avoid null reference errors. +- SenderNicknameColor and SenderDisplayName are optional UI hints and may be absent; consumers should gracefully handle missing values. +- ReplyTo is optional and only populated for messages that are replies to another message; check for null before accessing related data. + +--- + +## RekeyChannelRequest +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record RekeyChannelRequest( + string OldPassword, + string NewPassword, + string NewEncryptionSalt, + string NewWrappedRoomKey) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `OldPassword` | `string` | — | +| `NewPassword` | `string` | — | +| `NewEncryptionSalt` | `string` | — | +| `NewWrappedRoomKey` | `string` | — | + + +Passphrase change for an encrypted channel: the client proves knowledge of the old passphrase (old auth key), then supplies the re-wrapped room key under the new one. + +This RekeyChannelRequest is a data transfer object used to perform a channel rekey. It carries the old password to prove knowledge of the current key, the new password and its salt, and the re-wrapped room key to be used under the new credentials. + +## Remarks +This type serves as a single payload boundary in the channel rekey workflow, encapsulating all data required to authenticate the existing context and establish a new encryption context for the room. Being a record enforces immutability and provides straightforward value-based equality, which simplifies testing and auditing of rekey requests. It acts as a contract between the client and server for the rotation of the room key tied to a new passphrase. + +## Example +```csharp +var request = new RekeyChannelRequest( + OldPassword: "old-passphrase", + NewPassword: "new-passphrase", + NewEncryptionSalt: "salt-42", + NewWrappedRoomKey: "BASE64_WRAPPED_ROOM_KEY" +); +``` + +## Notes +- Do not log or expose OldPassword, NewPassword, or NewWrappedRoomKey; treat them as highly sensitive and avoid telemetry. +- NewEncryptionSalt should be a cryptographically strong, per-operation salt generated by a secure RNG; do not reuse salts. +- This object represents a single rekey operation and should not be reused for multiple independent requests. + +--- + +## ReplyRefDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record ReplyRefDto( + Guid MessageId, + string SenderUsername, + string Content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `MessageId` | `Guid` | — | +| `SenderUsername` | `string` | — | +| `Content` | `string` | — | + + +ReplyRefDto is a compact, immutable data transfer object that identifies the message a user is replying to. It carries the target message's ID, the original sender's username, and the Content of that message as transmitted over the network, enabling clients and services to render contextual reply previews and preserve the reply's linkage. Content is treated exactly like ordinary message content on the wire: transport-encrypted, and for end-to-end encrypted rooms it is room ciphertext the client must decrypt (the server truncates only plaintext snippets). If the original message has been deleted, the related MessageDto will be null; the reply reference remains a valid anchor for rendering the reply context. + +## Remarks +Represents the reply target in chat threads as a minimal reference, decoupling the UI payload from the full MessageDto. It ensures consistent wire-format handling across plaintext and end-to-end encrypted rooms, while allowing clients to display reply context without requiring the entire original payload. + +## Example +```csharp +var reference = new ReplyRefDto( + MessageId: Guid.Parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301"), + SenderUsername: "alice", + Content: "Hello world" +); +``` + +## Notes +- Content is the exact on-wire representation of the referenced message; it may be ciphertext in encrypted rooms and should be decrypted by the client when applicable. +- If the original message has been deleted, the MessageDto may be null, but the ReplyRefDto still anchors the reply context for UI rendering; callers should handle potential missing referenced data gracefully. + +--- + +## SendMessageRequest +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record SendMessageRequest(string ChannelName, string Content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ChannelName` | `string` | — | +| `Content` | `string` | — | + + +SendMessageRequest is an immutable data transfer object that encapsulates the information required to send a message to a specific chat channel. It combines the ChannelName and the Content to be delivered so transport or messaging layers can operate on a single payload. As a record, it provides value-based equality and easy cloning with the with-expression, which helps when constructing variations without mutating existing instances. + +## Remarks + +Acts as a boundary contract between UI/API layers and the messaging service. The record's immutability and structural equality make it reliable for logging, caching, and test assertions. Validation rules or routing decisions should live outside this DTO; this type should not perform domain validation. Its simple two-string shape also makes it friendly to common serialization mechanisms, enabling straightforward transport across boundaries. + +## Notes + +- No validation is performed by the type itself; ensure ChannelName and Content conform to domain rules before sending. +- The type is immutable; to modify, create a new instance (or use the with-expression) rather than mutating an existing one. +- Suitable for serialization; the plain two-property shape works well with JSON, XML, or other common serializers. + +--- + +## SendUrlRequest +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record SendUrlRequest(string Url) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Url` | `string` | — | + + +SendUrlRequest is a tiny, immutable URL payload represented as a C# record. It’s intended for scenarios where a URL must be passed across boundaries in a strongly-typed way rather than as a raw string, gaining value-based equality and straightforward deconstruction in the process. + +## Remarks +Using a record for this DTO ensures immutability, value-based equality, and built-in deconstruction. This makes SendUrlRequest a natural fit for messaging or API surfaces that expect a dedicated URL payload type instead of raw strings, reducing the chance of accidental mutation and enabling pattern-based handling of the URL payload. + +## Example +```csharp +var request = new SendUrlRequest("https://example.com"); +``` + +## Notes +- No validation is performed inside the type; ensure the URL is valid at the call site or in downstream handlers. + +--- + +## UpdateTopicRequest +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record UpdateTopicRequest(string? Topic) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Topic` | `string?` | — | + + +Represents a request to update the topic of a chat or conversation. This immutable record acts as a lightweight DTO that carries an optional Topic value; use it when issuing an update operation—provide a non-null Topic to set a new topic, or pass null to indicate that the topic should be cleared or left unchanged by the API, depending on server semantics. + +## Remarks +This abstraction communicates the intent of updating only the topic field, leveraging a nullable Topic to express optionality. The record nature provides value-based equality and simple construction, and you can create modified copies with the with-expression (e.g., updating the Topic while preserving other fields in a derived request). + +## Example +```csharp +// Set a new topic +var request = new UpdateTopicRequest("New Topic"); + +// Clear the topic (behavior depends on the API) +var clearRequest = new UpdateTopicRequest(null); + +// Create a modified copy +var updated = request with { Topic = "Updated Topic" }; +``` + +## Notes +- Topic is nullable; serialization and API behavior may vary—null may mean "no change" or "clear" depending on the endpoint. +- Because this is a record, instances are immutable; use the with-expression to derive variations without mutating the original. + +--- + +## UserDto +> **File:** `src/EchoHub.Core/DTOs/ChatDtos.cs` +> **Kind:** record + +```csharp +public record UserDto( + Guid Id, + string Username, + string? DisplayName, + string? NicknameColor, + UserStatus Status, + DateTimeOffset LastSeenAt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `Username` | `string` | — | +| `DisplayName` | `string?` | — | +| `NicknameColor` | `string?` | — | +| `Status` | [`UserStatus`](../Models/UserStatus.cs.md) | — | +| `LastSeenAt` | `DateTimeOffset` | — | + + +UserDto is a lightweight, immutable data transfer object that conveys a user's identity and presence-related attributes across boundaries such as API responses or UI bindings. It aggregates the user's unique identifier, login name, optional display name and nickname color, current status, and the last seen timestamp so clients can present a consistent and responsive user summary. + +## Remarks +As a record, UserDto benefits from value-based equality and structural immutability, making it easy to compare user summaries and safely pass them around without worrying about accidental mutation. DisplayName and NicknameColor are optional to accommodate scenarios where presentation details are missing. LastSeenAt and Status provide presence information that can drive UI indicators and sorting. + +## Notes +- DisplayName and NicknameColor are nullable; null should be treated as absent presentation data. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md new file mode 100644 index 0000000..cba7cad --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/CommonDtos.cs.md @@ -0,0 +1,282 @@ +# CommonDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/CommonDtos.cs` + +## Contents + +- [ApiResponse](#apiresponse) +- [ApiResponse](#apiresponse-1) +- [ChannelOperationResult](#channeloperationresult) +- [ErrorResponse](#errorresponse) +- [PaginatedResponse](#paginatedresponse) +- [UserOperationResult](#useroperationresult) +- [ChannelError](#channelerror) +- [UserError](#usererror) + +--- + +## ApiResponse +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record ApiResponse(bool Success, string? Message = null, List? Errors = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Success` | `bool` | — | +| [`Message`](../Models/Message.cs.md) | `string?` | `null` | +| `Errors` | `List?` | `null` | + + +ApiResponse is a lightweight data transfer object used to convey the outcome of an operation. It carries a required Success flag and optional Message and Errors to provide feedback and diagnostics to callers. + +## Remarks +Used as a common response shape across service boundaries to avoid ad-hoc return types. The primary purpose is to separate control flow (success/failure) from payload, facilitating simple success messaging and error propagation. Be mindful that Errors is a `List`, which remains mutable if the same instance is shared; convert to a read-only collection or copy before returning to external consumers. + +## Notes +- The Errors property is a mutable `List`—wrap or copy it if you intend to preserve a fixed snapshot when returning to consumers. +- Message may be null; supply a default user-friendly message or handle nulls in UI/logging. + +--- + +## ApiResponse +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record ApiResponse(bool Success, string? Message = null, List? Errors = null, T? Data = default) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Success` | `bool` | — | +| [`Message`](../Models/Message.cs.md) | `string?` | `null` | +| `Errors` | `List?` | `null` | +| `Data` | `T?` | `default` | + + +`ApiResponse` is a generic wrapper you return from API methods to convey a successful outcome, an optional human-friendly message, and a payload of type T, along with any per-call errors. Use this pattern when you want a consistent contract for success, messaging, and data across endpoints rather than returning raw data alone. + +## Remarks +`ApiResponse` is an immutable value type (a record with a primary constructor) that standardizes how results are communicated. It separates the data payload from status information, allowing clients to inspect Success, Message, and Errors independently from Data. Because Message and Errors are optional, responses can remain concise for successful operations while still providing rich error detail when needed. + +## Example +```csharp +using System.Collections.Generic; + +// success with data +var result = new ApiResponse(true, "Operation completed", null, "payload"); + +// error with details +var failure = new ApiResponse(false, "Validation failed", new List { "Email is invalid" }, null); +``` + +## Notes +- Message and Errors are nullable; always check Success before relying on these fields, and provide defaults if you need non-null output. +- `ApiResponse` is immutable; to modify it, use a with-expression to create a copy (e.g., var updated = result with { Data = newData };). + + +--- + +## ChannelOperationResult +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record ChannelOperationResult(ChannelDto? Channel, ChannelError? Error, string? ErrorMessage) +{ + public bool IsSuccess => Error is null; + + public static ChannelOperationResult Success(ChannelDto channel) => new(channel, null, null); + public static ChannelOperationResult Fail(ChannelError error, string message) => new(null, error, message); +} +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| [`Channel`](../Models/Channel.cs.md) | `ChannelDto?` | — | +| `Error` | `ChannelError?` | — | +| `ErrorMessage` | `string?` | — | + + +ChannelOperationResult is a lightweight result wrapper used by channel-creation/lookup operations to return either a ChannelDto on success or an error descriptor on failure. Callers typically inspect IsSuccess and then access Channel or Error/ErrorMessage, using the static factories to produce a well-formed result rather than constructing it directly. + +## Remarks +It captures the outcome of channel-oriented operations in a single, immutable value, reducing the need for exception-based control flow. By pairing either a Channel with no error or an Error with a message, it forces consumers to handle both success and failure paths in a uniform way. It complements the ChannelDto and ChannelError types by providing a minimal, self-describing container that can be passed through layers without leaking implementation details. + +## Notes +- Prefer the static factories to create instances to preserve the intended invariant that a result carries either a Channel or an error. The public constructor can produce degenerate states if misused. +- The ErrorMessage is optional; provide a descriptive message to aid debugging when using Fail. + +--- + +## ErrorResponse +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record ErrorResponse(string Error, string? Detail = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Error` | `string` | — | +| `Detail` | `string?` | `null` | + + +ErrorResponse is a small, immutable data transfer object used to convey error information from the server to API clients. Implemented as a C# record with two positional properties, Error and Detail, it carries a concise error identifier or message and optional supplemental details. Use it when standardizing error payloads across API endpoints or error-handling middleware that wants to provide a consistent error shape. + +## Remarks +Using a record provides value-based equality and immutability, making ErrorResponse a stable payload that is easy to compare in tests and to clone with modifications via with-expressions. The Error field represents a short error code or message, while Detail offers optional, human-friendly context. This type is intended to be reused across API boundaries, ensuring clients receive a uniform error shape. + +## Notes +- Avoid leaking sensitive internals in Error; prefer stable, client-friendly codes or messages. +- Detail is nullable; when null, serialization may omit the property depending on serializer settings. +- As a DTO, this record should be produced by a dedicated error-handling path rather than constructed manually in business logic. + +--- + +## PaginatedResponse +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record PaginatedResponse(List Items, int Total, int Offset, int Limit) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Items` | `List` | — | +| `Total` | `int` | — | +| `Offset` | `int` | — | +| `Limit` | `int` | — | + + +Represents a paginated result set for a collection of items of type T. It bundles the items for the current page together with paging metadata (Total, Offset, and Limit), enabling consumers to render pages and request subsequent pages without fetching the entire dataset. Use `PaginatedResponse` when an API or service returns a slice of a larger collection and you need to convey both the page content and the overall size. + +## Remarks +This generic DTO unifies paging across different endpoints by pairing a page of items with metadata describing the total size of the set and the paging window (Offset and Limit). Consumers can derive the total number of pages and navigate accordingly, without duplicating paging logic. + +## Example +```csharp +var page = new PaginatedResponse( + Items: new List { 1, 2, 3 }, + Total: 10, + Offset: 0, + Limit: 3 +); +``` + +## Notes +- The Items property is a `List`, which is mutable. Mutating the list after construction will affect the PaginatedResponse instance. If you require immutability of the collection, consider exposing `ReadOnlyCollection` or `IReadOnlyList` instead of `List`, or wrap the list before returning. +- Because `PaginatedResponse` is a record, the wrapper itself uses value-based equality, but the `List` contained in Items is compared by reference. Two instances with equal contents but different `List` instances will not compare equal. + +--- + +## UserOperationResult +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** record + +```csharp +public record UserOperationResult(UserProfileDto? User, UserError? Error, string? ErrorMessage) +{ + public bool IsSuccess => Error is null; + + public static UserOperationResult Success(UserProfileDto user) => new(user, null, null); + public static UserOperationResult Fail(UserError error, string message) => new(null, error, message); +} +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| [`User`](../Models/User.cs.md) | `UserProfileDto?` | — | +| `Error` | `UserError?` | — | +| `ErrorMessage` | `string?` | — | + + +Represents the outcome of a user-related operation: it either carries a UserProfileDto for success or a UserError and an ErrorMessage for failure. Use IsSuccess to branch on the result and create instances via Success(user) for success or Fail(error, message) for failure. + +## Remarks +This abstraction uses a record with nullable payload fields to model a simple Result pattern without introducing a separate discriminated union. It provides a single return type across methods that can either yield a user profile or fail with details, enabling concise consumer code that checks IsSuccess first. Because User is nullable when the result is a failure, and because Error and ErrorMessage are null on success, callers should guard access to User unless IsSuccess is true. The helper methods ensure the invariant that a successful result always carries a user while a failure carries an error and message. + +## Notes +- Read result.User only after confirming IsSuccess; otherwise the value may be null. +- On failure, User will be null; consult Error and ErrorMessage for details. + +--- + +## ChannelError +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** enum + +```csharp +public enum ChannelError +{ + ValidationFailed, + AlreadyExists, + NotFound, + Forbidden, + Protected +} +``` + + +ChannelError enumerates the discrete failure cases that can arise when managing channels in EchoHub. It provides a finite set of error codes so callers can distinguish invalid input, duplicates, missing resources, permission issues, and protected resources without resorting to free-form strings. + +## Remarks +This enum lives in the DTO layer to convey precise failure reasons from service or repository operations to API clients. By centralizing channel-related errors, it enables consistent error handling, mapping to user-friendly responses, and easier client-side interpretation across create, update, and lookup workflows. The member names align with common REST/DTO conventions, reducing ambiguity when serializing and documenting API contracts. + +## Notes +- Changing the enum's members or their order can impact clients that serialize/deserialize error codes; treat it as a public contract. +- If you enable numeric JSON serialization for enums, ensure the API contract documents the expected codes to avoid confusion. + +--- + +## UserError +> **File:** `src/EchoHub.Core/DTOs/CommonDtos.cs` +> **Kind:** enum + +```csharp +public enum UserError +{ + ValidationFailed, + AlreadyExists, + NotFound, + InvalidCredentials, + Banned +} +``` + + +Represents the set of user-related errors that can occur during authentication, registration, lookup, or other user-identity operations in the EchoHub DTO layer. This enum provides a typed, contract-friendly way to communicate failure modes from server to client, enabling centralized handling and consistent feedback without scattering string literals across the codebase. + +Values include: +- ValidationFailed: input data failed validation. +- AlreadyExists: a resource with the given identifier already exists. +- NotFound: the requested user or resource could not be found. +- InvalidCredentials: credentials were invalid during authentication. +- Banned: the user is banned from the system. + +## Remarks +By consolidating these common errors into a single enum, this abstraction decouples transport contracts from domain logic and supports uniform error mapping on the client. It simplifies UI messaging, and it allows the server to evolve its error vocabulary without changing method signatures. + +## Notes +- Be mindful of how the enum is serialized in API responses (numeric vs string); consider standardizing on string representations to avoid client breakage when new values are added. +- Adding new values is a contract change; document and version the API accordingly, and ensure clients handle unknown values gracefully. +- This enum is a DTO-level error vocabulary; do not encode domain exceptions here. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/InviteDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/InviteDtos.cs.md new file mode 100644 index 0000000..ac4f63b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/InviteDtos.cs.md @@ -0,0 +1,94 @@ +# InviteDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/InviteDtos.cs` + +## Contents + +- [CreateInviteRequest](#createinviterequest) +- [InviteDto](#invitedto) + +--- + +## CreateInviteRequest +> **File:** `src/EchoHub.Core/DTOs/InviteDtos.cs` +> **Kind:** record + +```csharp +public record CreateInviteRequest(int? MaxUses = null, int? ExpiresInHours = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `MaxUses` | `int?` | `null` | +| `ExpiresInHours` | `int?` | `null` | + + +This record serves as the payload for creating an invitation. It carries optional constraints that govern the invite: MaxUses limits how many times the invite can be redeemed, and ExpiresInHours determines how long the invite remains valid (in hours). When constructing the request, omit values you don’t want to constrain; null properties indicate the server should apply its defaults. + +## Remarks +Because CreateInviteRequest is a C# record, it provides value-based equality and immutable semantics, making it a reliable DTO for API calls and caching. The nullable properties express optional constraints without introducing separate flags, keeping the surface area small and expressive. + +## Example +```csharp +var request = new CreateInviteRequest(MaxUses: 5, ExpiresInHours: 24); +``` + +## Notes +- Null on a property means no constraint; the API defaults apply. +- Many serializers omit null fields; if the API requires an explicit indicator for "no constraint," ensure your serializer preserves the field or you configure it accordingly. +- If you need to convey zero constraints explicitly, pass 0 (not null) for the respective property; null is not the same as zero. + + +--- + +## InviteDto +> **File:** `src/EchoHub.Core/DTOs/InviteDtos.cs` +> **Kind:** record + +```csharp +public record InviteDto( + string Code, + string CreatedByUsername, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + int MaxUses, + int UseCount) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Code` | `string` | — | +| `CreatedByUsername` | `string` | — | +| `CreatedAt` | `DateTimeOffset` | — | +| `ExpiresAt` | `DateTimeOffset?` | — | +| `MaxUses` | `int` | — | +| `UseCount` | `int` | — | + + +InviteDto is a small, transport-oriented representation of an invitation. It encapsulates the invitation code, the creator's username, the moment of creation, an optional expiry, and simple usage counters, making it suitable for API responses and inter-layer data transfers without revealing domain internals. + +## Remarks +As a record, InviteDto is immutable and uses value-based equality, which makes caching and comparisons straightforward. It decouples transport concerns from domain logic by presenting only the data clients need. The fields map directly to invitation semantics: Code is the token, CreatedByUsername and CreatedAt capture provenance, ExpiresAt denotes expiry (nullable means no expiry), and MaxUses/UseCount express the usage limits and current consumption. + +## Example +```csharp +var invite = new InviteDto( + Code: "WELCOME-ABC123", + CreatedByUsername: "admin", + CreatedAt: DateTimeOffset.UtcNow, + ExpiresAt: DateTimeOffset.UtcNow.AddDays(7), + MaxUses: 5, + UseCount: 0 +); +``` + +## Notes +- Null ExpiresAt means the invitation does not expire; ensure your validation logic accounts for that. +- InviteDto is immutable; to reflect state changes (e.g., after a use), construct a new instance rather than mutating the existing one. +- Use UTC times for CreatedAt/ExpiresAt to avoid timezone ambiguity. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md new file mode 100644 index 0000000..484e9b7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md @@ -0,0 +1,127 @@ +# ModerationDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/ModerationDtos.cs` + +## Contents + +- [AssignRoleRequest](#assignrolerequest) +- [BanRequest](#banrequest) +- [KickRequest](#kickrequest) +- [MuteRequest](#muterequest) + +--- + +## AssignRoleRequest +> **File:** `src/EchoHub.Core/DTOs/ModerationDtos.cs` +> **Kind:** record + +```csharp +public record AssignRoleRequest(string Username, ServerRole Role) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Username` | `string` | — | +| `Role` | [`ServerRole`](../Models/ServerRole.cs.md) | — | + + +AssignRoleRequest is a lightweight, immutable data transfer object that carries the intent to assign a specific server role to a user. It encapsulates just two pieces of information—the target Username and the desired Role—and is intended to be serialized and sent to moderation or authorization services that perform the actual role assignment. + +## Remarks +The record type provides value-based equality and immutability, making it a reliable payload for messaging boundaries between UI, services, and backend handlers. By expressing the action as data rather than behavior, it supports clean separation of concerns and straightforward routing in moderation workflows. + +## Notes +- Ensure Username conforms to identity rules at the boundary before processing the request. +- Because this is an immutable record, callers should create a new instance for every distinct request; do not modify an existing instance. + +--- + +## BanRequest +> **File:** `src/EchoHub.Core/DTOs/ModerationDtos.cs` +> **Kind:** record + +```csharp +public record BanRequest(string? Reason = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Reason` | `string?` | `null` | + + +BanRequest is a lightweight, immutable data container used when issuing moderation bans. It carries an optional Reason and is designed to be passed as a single object through the moderation pipeline instead of a group of disparate parameters. This structure makes future extension straightforward (e.g., adding additional ban metadata) without changing call sites. + +## Remarks +BanRequest acts as a boundary between the transport/presentation layer and the moderation domain. Using a record provides value-based equality and predictable serialization, which aids testing, logging, and caching. The optional Reason supports both silent bans and bans accompanied by rationale, with policy decisions about requiring a reason typically enforced at higher layers. + +## Notes +- Reason is nullable; handle nulls gracefully when displaying or persisting data, and apply any policy about requiring a reason at the appropriate layer. + +--- + +## KickRequest +> **File:** `src/EchoHub.Core/DTOs/ModerationDtos.cs` +> **Kind:** record + +```csharp +public record KickRequest(string? Reason = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Reason` | `string?` | `null` | + + +KickRequest is a lightweight, immutable payload used when performing a moderation kick. It carries an optional Reason describing why the kick occurred. Callers construct this record when issuing a kick action and attach the reason if one is known; if no reason is provided, Reason remains null. The record shape ensures value-based equality and easy serialization across boundaries, making it a convenient transport object for moderation workflows. + +## Remarks +KickRequest isolates the transport of a kick action from its core moderation logic. This abstraction makes it easy to extend later with additional fields (for example, moderatorId, timestamp, or kick ban duration) without changing the public contract. It also supports consistent logging and audit trails by treating the kick reason as optional metadata. + +## Notes +- Reason is optional; validate as needed at the API boundary if your scenario requires a non-null reason. +- When serializing, null Reason might be omitted depending on serializer configuration; be explicit if you need to communicate 'no reason'. +- This is a simple DTO; do not conflate it with the domain entity for a kick; use it to transport data. + +--- + +## MuteRequest +> **File:** `src/EchoHub.Core/DTOs/ModerationDtos.cs` +> **Kind:** record + +```csharp +public record MuteRequest(string? Reason = null, int? DurationMinutes = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Reason` | `string?` | `null` | +| `DurationMinutes` | `int?` | `null` | + + +MuteRequest is a compact, immutable data transfer object used to initiate a moderation mute. It carries two optional fields: Reason and DurationMinutes, allowing you to specify a rationale and a duration when issuing a mute; omitting either field leaves that detail to the receiver's policy. + +## Remarks +By grouping the fields into a single record, this abstraction reduces API surface area and provides a consistent payload for mute-related actions across the moderation layer. The record semantics also enable value-based equality and straightforward testing and transport. + +## Example +```csharp +// Mute for 30 minutes with a reason +var request = new MuteRequest("Spamming in chat", 30); + +// Mute without specifying details +var request2 = new MuteRequest(); +``` + +## Notes +- Reason may contain user-provided content; avoid including it in logs or telemetry unless explicitly permitted. +- Because the type is a record with nullable fields, ensure boundary validation and handle nulls gracefully at the call site or in the receiving layer. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md new file mode 100644 index 0000000..c062098 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md @@ -0,0 +1,202 @@ +# ProfileDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` + +## Contents + +- [AvatarUploadResponse](#avataruploadresponse) +- [UpdateProfileRequest](#updateprofilerequest) +- [UpdateStatusRequest](#updatestatusrequest) +- [UserPresenceDto](#userpresencedto) +- [UserProfileDto](#userprofiledto) + +--- + +## AvatarUploadResponse +> **File:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` +> **Kind:** record + +```csharp +public record AvatarUploadResponse(string AvatarAscii) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `AvatarAscii` | `string` | — | + + +AvatarUploadResponse is a tiny, immutable data container that represents the server’s response to an avatar-upload operation. It carries a single payload, AvatarAscii, which holds the ASCII-art representation of the uploaded avatar. Use this type as a typed contract when returning avatar data from a service or API endpoint, rather than returning a raw string scattered through your responses. + +## Remarks +This abstracted DTO isolates the avatar representation behind a named contract, making it easier to evolve the API (e.g., by adding metadata) without breaking call sites. The record semantics ensure value-based equality and straightforward deconstruction, which pairs well with serialization and testing. + +## Example +```csharp +var resp = new AvatarUploadResponse("ASCII_ART"); +Console.WriteLine(resp.AvatarAscii); +``` + +## Notes +- AvatarAscii may contain newline characters; ensure your JSON/HTTP layer preserves them. +- Keep the payload size reasonable; extremely large ASCII art can inflate responses. +- This type is a pure DTO with no behavior; avoid placing business logic here. + +--- + +## UpdateProfileRequest +> **File:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` +> **Kind:** record + +```csharp +public record UpdateProfileRequest( + string? DisplayName = null, + string? Bio = null, + string? NicknameColor = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `DisplayName` | `string?` | `null` | +| `Bio` | `string?` | `null` | +| `NicknameColor` | `string?` | `null` | + + +UpdateProfileRequest is a data transfer object used when updating a user's profile. All fields are optional, enabling partial updates by supplying only the fields you want to change (DisplayName, Bio, or NicknameColor). This object is typically sent to a profile update endpoint or service, where the provided values are applied while unspecified fields remain unchanged. + +## Remarks +By modeling the payload as a record with nullable properties, this abstraction communicates intent clearly: you're patching specific aspects of a profile rather than replacing it wholesale. It decouples API contract from the underlying domain model and reinforces immutability semantics for the request object. The combination of a concise DTO and nullable members makes it straightforward for clients to express partial updates without constructing separate patch types. + +## Example +```csharp +// Update only the display name +var request1 = new UpdateProfileRequest(DisplayName: "Nova"); + +// Update multiple fields +var request2 = new UpdateProfileRequest(DisplayName: "Nova", Bio: "Software engineer", NicknameColor: "#1E90FF"); +``` + +## Notes +- Omitted properties are treated as "no update" by the receiver; a null value may be interpreted differently depending on backend semantics. +- If you need to clear a value, verify the server's rules: null may not clear a field unless explicitly supported; you may need to provide an empty string or use a dedicated API path to clear a value. + +--- + +## UpdateStatusRequest +> **File:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` +> **Kind:** record + +```csharp +public record UpdateStatusRequest( + UserStatus Status, + string? StatusMessage = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Status` | [`UserStatus`](../Models/UserStatus.cs.md) | — | +| `StatusMessage` | `string?` | `null` | + + +UpdateStatusRequest is a small, immutable data transfer object used to submit a user's status update. It bundles the new Status and, optionally, an accompanying StatusMessage to be processed by a profile update operation. + +## Remarks +Being a C# 9 record, UpdateStatusRequest is immutable and supports value-based equality, which makes it reliable to pass across process boundaries and into tests. The Status is a required field that identifies the new user state via UserStatus, while StatusMessage provides optional context. This DTO participates in the profile update workflow and is typically serialized as part of requests to the profile service. + +## Notes +- StatusMessage is nullable; if the receiver accepts no message, null can be sent and should be handled gracefully. +- Because UpdateStatusRequest is a record, you can create modified copies using the with expression, e.g. existing with { Status = newStatus } to preserve other fields. + +--- + +## UserPresenceDto +> **File:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` +> **Kind:** record + +```csharp +public record UserPresenceDto( + string Username, + string? DisplayName, + string? NicknameColor, + UserStatus Status, + string? StatusMessage, + ServerRole Role, + bool IsIrc = false) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Username` | `string` | — | +| `DisplayName` | `string?` | — | +| `NicknameColor` | `string?` | — | +| `Status` | [`UserStatus`](../Models/UserStatus.cs.md) | — | +| `StatusMessage` | `string?` | — | +| `Role` | [`ServerRole`](../Models/ServerRole.cs.md) | — | +| `IsIrc` | `bool` | `false` | + + +Represents a single snapshot of a user's presence in EchoHub. This record aggregates the user's identity (Username and optional DisplayName), their current presence state (Status and optional StatusMessage), and their server role (Role). It also carries UI-related hints such as NicknameColor and an IsIrc flag indicating whether the presence originated from IRC. The type is a C# record with positional parameters, making it an immutable, value-based data object that is ideal for transport across API boundaries and for equality comparisons of presence data. + +## Remarks +Consolidating identity, status, and role into one DTO reduces the number of cross-cutting data transfers required to render a user in a presence list or chat UI. The NicknameColor provides a presentation cue without forcing consumers to derive display styling; the IsIrc flag lets calling code distinguish between sources. As a record, instances compare by their values, enabling straightforward caching, deduplication, and change detection. + +## Notes +- Nullable fields (DisplayName, NicknameColor, and StatusMessage) may be null; callers should handle nulls gracefully. +- IsIrc defaults to false; set to true when constructing from IRC-origin data. +- This is a positional-parameter record; properties are init-only and the object is immutable after construction; create a new instance to represent a changed presence. + +--- + +## UserProfileDto +> **File:** `src/EchoHub.Core/DTOs/ProfileDtos.cs` +> **Kind:** record + +```csharp +public record UserProfileDto( + Guid Id, + string Username, + string? DisplayName, + string? Bio, + string? NicknameColor, + string? AvatarAscii, + UserStatus Status, + string? StatusMessage, + ServerRole Role, + DateTimeOffset CreatedAt, + DateTimeOffset LastSeenAt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Id` | `Guid` | — | +| `Username` | `string` | — | +| `DisplayName` | `string?` | — | +| `Bio` | `string?` | — | +| `NicknameColor` | `string?` | — | +| `AvatarAscii` | `string?` | — | +| `Status` | [`UserStatus`](../Models/UserStatus.cs.md) | — | +| `StatusMessage` | `string?` | — | +| `Role` | [`ServerRole`](../Models/ServerRole.cs.md) | — | +| `CreatedAt` | `DateTimeOffset` | — | +| `LastSeenAt` | `DateTimeOffset` | — | + + +Represents a compact, transport-friendly snapshot of a user's profile used across boundaries (e.g., API responses, UI layers). As a C# record, it provides value-based equality and immutability, ensuring a stable contract when serializing user data. It collects identity (Id, Username), optional display attributes (DisplayName, Bio, NicknameColor, AvatarAscii), current status (Status, StatusMessage), role (Role), and timestamp metadata (CreatedAt, LastSeenAt). + +## Remarks +This DTO exists to decouple internal domain models from the data contract exposed to clients. By using a dedicated record, changes to the underlying domain models won't automatically ripple into API payloads. The explicit nullable fields model optional user attributes, and the timestamp fields communicate when the profile was created and last observed; consumers must handle time values robustly across time zones. + +## Notes +- Nullable properties (DisplayName, Bio, NicknameColor, AvatarAscii, StatusMessage) may be null; handle accordingly in consumers. +- CreatedAt and LastSeenAt are DateTimeOffset values; when displaying, convert to a user-friendly timezone or use UTC representation as defined by the API contract. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ServerDtos.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ServerDtos.cs.md new file mode 100644 index 0000000..f060c2a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/DTOs/ServerDtos.cs.md @@ -0,0 +1,73 @@ +# ServerDtos.cs + +> **Source:** `src/EchoHub.Core/DTOs/ServerDtos.cs` + +## Contents + +- [EncryptionKeyResponse](#encryptionkeyresponse) +- [ServerStatusDto](#serverstatusdto) + +--- + +## EncryptionKeyResponse +> **File:** `src/EchoHub.Core/DTOs/ServerDtos.cs` +> **Kind:** record + +```csharp +public record EncryptionKeyResponse(string Key) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Key` | `string` | — | + + +EncryptionKeyResponse is a tiny, immutable data transfer object that carries a single encryption key via its Key property. Use it whenever a caller must receive an encryption key in a strongly-typed envelope (instead of returning a plain string) to improve clarity and compatibility with serialization and tooling. + +## Remarks +By leveraging a C# record, EncryptionKeyResponse benefits from value-based equality, structural deconstruction, and concise construction. It serves as a semantic wrapper around the raw key, making intent explicit in APIs that issue or relay keys, and aligns with other DTOs in the EchoHub.Core DTOs layer. + +## Notes +- The Key contains sensitive material; avoid logging or exposing it in request traces. Ensure transport channels are secure (TLS) and that only authorized callers can obtain the key. +- Because it is a simple wrapper, use it when a typed envelope adds value (e.g., API contracts or structured responses) and avoid over-modeling plain, ephemeral keys. + + +--- + +## ServerStatusDto +> **File:** `src/EchoHub.Core/DTOs/ServerDtos.cs` +> **Kind:** record + +```csharp +public record ServerStatusDto( + string Name, + string? Description, + int OnlineUsers, + int TotalChannels, + string RegistrationMode = "open") +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Name` | `string` | — | +| `Description` | `string?` | — | +| `OnlineUsers` | `int` | — | +| `TotalChannels` | `int` | — | +| `RegistrationMode` | `string` | `"open"` | + + +ServerStatusDto is an immutable data-transfer object that represents the current status of a server in EchoHub. It exposes the server name, an optional description, the number of online users, the total number of channels, and a registration mode (defaulting to open). As a C# record with a primary constructor, it benefits from value-based equality and convenient deconstruction, making it a natural payload for API responses that describe the server's state. + +## Remarks +A record provides value-based equality and immutability for a simple data carrier, which is exactly what a status payload is. The Description field is optional, so consumers must be prepared to handle null. The shape is designed to be serialized to JSON for API responses and easily deconstructed when mapping to other domain models. + +## Notes +- Nullable Description means clients must handle nulls. +- RegistrationMode defaults to "open" when not supplied, preserving backward compatibility. +- As a record, two instances with identical property values compare equal (value equality). + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/Attachment.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/Attachment.cs.md new file mode 100644 index 0000000..0a8dffe --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/Attachment.cs.md @@ -0,0 +1,18 @@ +# Attachment + +> **File:** `src/EchoHub.Core/Models/Attachment.cs` +> **Kind:** class + +```csharp +public class Attachment +``` + + +Represents a file attached to a message, such as an image, audio, or document. A message may carry zero or more attachments alongside its text content (Discord-style). + +## Remarks +Decouples attachment data from the message to allow independent storage and retrieval while keeping a lightweight reference to the owning message. The Url provides the relative download path (for example, /api/files/{fileId}) and FileName preserves the original filename. FileSize stores the stored blob size in bytes, which corresponds to ciphertext size when database encryption is enabled. AsciiPreview offers a rendered ASCII-art preview for images in color-tag format and is null for non-image attachments; it is stored encrypted-at-rest and, in end-to-end encrypted channels, remains room-encrypted. + +## Notes +- AsciiPreview is only populated for image attachments; for other kinds of attachments it is null. +- The Message navigation property may be null if the related Message entity isn't loaded; use MessageId for persistence and rely on Message when the relationship is loaded. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/AttachmentKind.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/AttachmentKind.cs.md new file mode 100644 index 0000000..a91f351 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/AttachmentKind.cs.md @@ -0,0 +1,39 @@ +# AttachmentKind + +> **File:** `src/EchoHub.Core/Models/AttachmentKind.cs` +> **Kind:** enum + +```csharp +public enum AttachmentKind +{ + Image, + Audio, + File +} +``` + + +AttachmentKind enumerates the possible types of a message attachment and signals how the client should render it. Use this enum when you know the specific attachment kind (image, audio, or file) so the UI can render an ASCII preview, a playback control, or a download option instead of a generic attachment rendering. + +## Remarks +This enum centralizes the presentation logic for attachments and serves as a simple discriminator that decouples the attachment data from its rendering. By representing the modality with a single value, components can switch on kind to choose the appropriate UI affordance without inspecting the content payload. It helps maintain a clean separation between the data model (what the attachment is) and the presentation (how it should be shown). + +## Example +```csharp +AttachmentKind kind = AttachmentKind.Image; +switch (kind) +{ + case AttachmentKind.Image: + Console.WriteLine("Render as ASCII image preview"); + break; + case AttachmentKind.Audio: + Console.WriteLine("Render with audio controls"); + break; + case AttachmentKind.File: + Console.WriteLine("Render as downloadable file"); + break; +} +``` + +## Notes +- If the enum is extended in the future, ensure all switch expressions include a default/fallback to handle unknown values gracefully. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/Channel.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/Channel.cs.md new file mode 100644 index 0000000..7ec5eb8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/Channel.cs.md @@ -0,0 +1,11 @@ +# Channel + +> **File:** `src/EchoHub.Core/Models/Channel.cs` +> **Kind:** class + +```csharp +public class Channel +``` + + +Represents a chat channel (room) within EchoHub's domain model. It stores the channel's identity, metadata for access control, an optional topic, and the collection of messages that belong to the channel, as well as an encryption envelope used for end-to-end security. Use this type to model a distinct conversation space that can be public or restricted, with the possibility of system-managed channels that are auto-created and not user-initiated. The class ties together the channel's identity (Id, Name), its description (Topic), its visibility (IsPublic) and authentication data (PasswordHash), its system-channel semantics (IsSystem), its client-managed encryption data (EncryptionSalt, WrappedRoomKey), creation auditing (CreatedAt, CreatedByUserId), and the message history (Messages). \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/ChannelMembership.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/ChannelMembership.cs.md new file mode 100644 index 0000000..6043003 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/ChannelMembership.cs.md @@ -0,0 +1,28 @@ +# ChannelMembership + +> **File:** `src/EchoHub.Core/Models/ChannelMembership.cs` +> **Kind:** class + +```csharp +public class ChannelMembership +``` + + +ChannelMembership is a lightweight data container that models the association between a user and a channel, recording when the user joined. It is intended for persistence and transport of membership data; instantiate and persist this model when recording channel participation rather than scattering ad-hoc data structures. + +## Remarks +ChannelMembership encapsulates the many-to-many relationship between users and channels along with a join timestamp, enabling straightforward CRUD operations, serialization, and display of membership data. As a plain DTO, it contains no behavior beyond storage of UserId, ChannelId, and JoinedAt; it complements User and Channel entities by representing their linkage. The JoinedAt default is DateTimeOffset.UtcNow at construction, which is convenient for new memberships but should be overridden or preserved from storage when loading existing records. + +## Example +```csharp +var membership = new ChannelMembership +{ + UserId = Guid.NewGuid(), + ChannelId = Guid.NewGuid() + // JoinedAt defaults to DateTimeOffset.UtcNow +}; +``` + +## Notes +- The default JoinedAt value applies only to newly created instances; deserialization from a data store will populate JoinedAt from the stored value. +- This class is a plain data holder with no validation or invariants; enforce domain rules at a higher layer when necessary. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/InviteCode.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/InviteCode.cs.md new file mode 100644 index 0000000..d4cc18a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/InviteCode.cs.md @@ -0,0 +1,36 @@ +# InviteCode + +> **File:** `src/EchoHub.Core/Models/InviteCode.cs` +> **Kind:** class + +```csharp +public class InviteCode +``` + + +Represents a registration invitation code used to gate account creation when the server's registration mode is set to invite. An InviteCode captures the unique identifier, the actual code string, who created it, and when it was created, plus optional expiration and per-invite usage constraints. When a new REST or IRC account is created and the system is configured for invite-based registration, the incoming code must match an existing InviteCode that has not expired and that has remaining uses. + +## Remarks +InviteCode acts as a persistence-side contract for invitation-based onboarding. It separates the concerns of registration gating from user data and provides a straightforward way to enforce expiration and single-use or limited-use policies at the data layer. The server's registration flow should consult these properties to validate a code before creating a new account and to record each use via UseCount, potentially preventing additional uses after MaxUses is reached. + +## Example +```csharp +// Example usage: initialize a new invite code that will expire in 7 days and allow up to 5 uses +Guid adminUserId = Guid.NewGuid(); +var invite = new InviteCode +{ + Id = Guid.NewGuid(), + Code = "INVITE-2026-ACME", + CreatedByUserId = adminUserId, + CreatedByUsername = "admin", + CreatedAt = DateTimeOffset.UtcNow, + ExpiresAt = DateTimeOffset.UtcNow.AddDays(7), + MaxUses = 5, + UseCount = 0 +}; +``` + +## Notes +- Use of 'required' Code property ensures that a code value is provided when constructing instances; compile-time enforcement. +- ExpiresAt null means never expires; If ExpiresAt is not set, the code is perpetual. +- The class does not implement persistence or concurrency control; UseCount and MaxUses must be enforced by the application or data layer. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/Message.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/Message.cs.md new file mode 100644 index 0000000..64d0dee --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/Message.cs.md @@ -0,0 +1,14 @@ +# Message + +> **File:** `src/EchoHub.Core/Models/Message.cs` +> **Kind:** class + +```csharp +public class Message +``` + + +Message is the persistence model for a chat message in EchoHub, capturing who sent it, when, where, and what was said. Content is required text (which may be empty if the message carries only attachments), with an optional EmbedJson and a list of Attachments for attached files; SenderUserId/SenderUsername identify the author and ChannelId/Channel locate the conversation. Messages may reply to another message via ReplyToMessageId. It also includes legacy pre-attachments fields (Type, AttachmentUrl, AttachmentFileName, AttachmentFileSize) retained to support a one-time startup migration that folds old single-attachment messages into Attachments; new code never writes these and they are nulled after migration and not exposed in DTOs. + +## Remarks +Architecturally, Message acts as the persistence model for chat messages, combining the modern Attachments collection with legacy fields retained to support a one-time startup data migration. New code never writes the legacy fields; they are nulled after migration and are not exposed in DTOs. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/MessageType.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/MessageType.cs.md new file mode 100644 index 0000000..f58d73e --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/MessageType.cs.md @@ -0,0 +1,24 @@ +# MessageType + +> **File:** `src/EchoHub.Core/Models/MessageType.cs` +> **Kind:** enum + +```csharp +public enum MessageType +{ + Text, + Image, + File, + Audio +} +``` + + +Represents the category of a message in EchoHub. MessageType defines the four concrete payload kinds that a message can carry: Text, Image, File, or Audio. Use this enum whenever a component, data model, or API needs to convey which kind of content is attached to a message so consumers can handle, display, or validate it in a type-safe way instead of relying on strings or magic numbers. + +## Remarks +Centralizes classification: this enum provides a single source of truth for message content kinds, enabling consistent routing, rendering, and validation across the system. It helps collaborators—models, serializers, and UI layers—make decisions based on content type without duplicating logic for string constants. By using an enum, you get compile-time checks and clearer intent. + +## Notes +- When stored or transferred, the underlying value defaults to int (0-3) in the order shown; changing the sequence or renaming members may break persisted data. +- If external systems expect string representations, consider mapping to/from MessageType names to avoid breaking compatibility. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/RefreshToken.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/RefreshToken.cs.md new file mode 100644 index 0000000..dbae3c8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/RefreshToken.cs.md @@ -0,0 +1,14 @@ +# RefreshToken + +> **File:** `src/EchoHub.Core/Models/RefreshToken.cs` +> **Kind:** class + +```csharp +public class RefreshToken +``` + + +RefreshToken is a persistence model that represents a refresh token tied to a user. It stores a hashed token (TokenHash), the associated user via UserId, and validity information such as ExpiresAt and CreatedAt (which defaults to the current UTC time), plus an optional RevokedAt timestamp. It exposes IsExpired, IsRevoked, and IsActive to quickly assess the token’s state. A developer would create and persist these tokens when issuing refresh tokens in an authentication flow, check IsActive (or IsExpired/IsRevoked) when validating a refresh attempt, and use RevokedAt to mark a token as revoked. + +## Remarks +This class serves as a persistence-facing token entity with a foreign key to User and a corresponding navigation property, enabling lifecycle management (creation, expiry, revocation) at the data layer while providing simple state checks for business logic. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerRole.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerRole.cs.md new file mode 100644 index 0000000..72d67b6 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerRole.cs.md @@ -0,0 +1,44 @@ +# ServerRole + +> **File:** `src/EchoHub.Core/Models/ServerRole.cs` +> **Kind:** enum + +```csharp +public enum ServerRole +{ + Member = 0, + Mod = 1, + Admin = 2, + Owner = 3 +} +``` + + +Represents the role assigned to a member within a server context in EchoHub. It defines four distinct levels of authority: Member, Mod (moderator), Admin, and Owner. Use this enum whenever you need to distinguish capabilities, gate UI or actions, or persist role information instead of relying on magic numbers. + +## Remarks +By centralizing roles in a single enum, the codebase can map each role to its corresponding permissions in one place, enabling consistent authorization checks across services. The explicit integer values also support stable serialization and interop when persisting or transmitting role data, without forcing string-based representations. + +## Example +```csharp +var role = ServerRole.Admin; +switch (role) +{ + case ServerRole.Owner: + case ServerRole.Admin: + // elevated permissions + break; + case ServerRole.Mod: + // moderation tasks + break; + case ServerRole.Member: + // regular user actions + break; +} +Console.WriteLine($"User role: {role}"); // prints Owner, Admin, Mod, or Member +``` + +## Notes +- Do not treat ServerRole as a Flags enum; do not combine roles with bitwise operators. +- Prefer using the named constants in checks; avoid relying on numeric ordering for access decisions. +- Changing the underlying values (0–3) can affect serialized data; coordinate evolution across all consumers to preserve compatibility. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerStatsReport.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerStatsReport.cs.md new file mode 100644 index 0000000..d41701f --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/ServerStatsReport.cs.md @@ -0,0 +1,20 @@ +# ServerStatsReport + +> **File:** `src/EchoHub.Core/Models/ServerStatsReport.cs` +> **Kind:** class + +```csharp +public class ServerStatsReport +``` + + +Represents a snapshot of server activity for a single reporting window, produced periodically by the stats-report background job. It captures timing data (PeriodStart, PeriodEnd, WindowHours, GeneratedAt) and per-window metrics (MessagesSent, FilesUploaded, BytesUploaded, NewMembers, ActiveMembers, Connections, Disconnections, Kicks, Bans) as well as end-of-window totals (TotalMembers, OnlineNow, PeakOnline) for persistence as pretty-printed JSON. + +## Remarks +Serves as a stable, serializable container for periodic server activity, enabling dashboards and trend analyses to compare windows over time. By separating window semantics (start/end, duration) from generation time, it supports reliable aggregation and rhythm-based alerts when metrics diverge. + +## Notes +- GeneratedAt is intended to equal PeriodEnd; ensure synchronization when populating the model. The default initializer uses DateTimeOffset.UtcNow, which may diverge if PeriodEnd is set to a different value. + +## Dependencies +- DateTimeOffset (System) — used for all timestamp properties on the model. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/User.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/User.cs.md new file mode 100644 index 0000000..83a9caf --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/User.cs.md @@ -0,0 +1,21 @@ +# User + +> **File:** `src/EchoHub.Core/Models/User.cs` +> **Kind:** class + +```csharp +public class User +``` + + +The User class is a domain model that represents a person using EchoHub, encapsulating identity (Id, Username, PasswordHash), profile details (DisplayName, Bio, NicknameColor, AvatarAscii), presence (Status, StatusMessage), role-based access (Role), moderation flags (IsMuted, MutedUntil, IsBanned), and auditing timestamps (CreatedAt, LastSeenAt). Username and PasswordHash are required to create a usable user, while other fields are optional to support rich profiles; defaults establish an online, member-facing user with current timestamps when a new instance is created. + +## Remarks + +This class serves as a central data container used across authentication, user management, presence rendering, and authorization checks. It’s designed to be lightweight and serializable for persistence, while keeping domain concerns cohesive with a single user entity. The defaults for Status and Role, along with the auditing timestamps, provide a sensible initial state for newly created users. + +## Notes + +- The required fields (Username and PasswordHash) enforce that essential credentials are provided when constructing a user instance. +- PasswordHash should be treated as sensitive data; avoid exposing it in logs or API responses and ensure the persistence layer handles security appropriately. +- If hydrating from storage, ensure CreatedAt and LastSeenAt reflect the persisted values rather than new defaults. diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Models/UserStatus.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Models/UserStatus.cs.md new file mode 100644 index 0000000..5b390c8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Models/UserStatus.cs.md @@ -0,0 +1,17 @@ +# UserStatus + +> **File:** `src/EchoHub.Core/Models/UserStatus.cs` +> **Kind:** enum + +```csharp +public enum UserStatus +{ + Online, + Away, + DoNotDisturb, + Invisible +} +``` + + +Represents the current presence state of a user in EchoHub, used by UI presence indicators and presence logic throughout the app. Use Online when the user is connected and active, Away when the user is idle, DoNotDisturb to signal notifications should be minimized, and Invisible when the user should not appear online to others. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Security/RoomCrypto.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Security/RoomCrypto.cs.md new file mode 100644 index 0000000..5d2e3c3 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Security/RoomCrypto.cs.md @@ -0,0 +1,38 @@ +# RoomCrypto + +> **File:** `src/EchoHub.Core/Security/RoomCrypto.cs` +> **Kind:** class + +```csharp +public static class RoomCrypto +``` + + +Client-side envelope encryption primitives used for end-to-end encrypted channels: derive per-room keys from a passphrase, generate random room content keys (RCKs), and encrypt/decrypt room content using AES-GCM. Use this class when you need a canonical, interoperable way to create room key material, wrap/unlock a room key with a passphrase-derived key, and produce/recognize the wire format used on the server ($RC1$base64(nonce||tag||ciphertext)). + +## Remarks +This class encapsulates the protocol choices and low-level crypto work so callers don't compose PBKDF2, hex encoding, and AES-GCM themselves. It implements an envelope pattern: the client generates a random 256-bit room content key (RCK) to encrypt room data; the RCK is stored server-side wrapped (AES-GCM) with a key-encryption key (KEK) derived from the user's passphrase. PBKDF2-SHA256 with 210000 iterations produces 64 bytes: the first 32 bytes (returned as lowercase hex) are the auth key used as the join gate, and the final 32 bytes are the KEK (never sent). Re-wrapping the RCK on passphrase change avoids re-encrypting history. + +## Example +```csharp +// Typical client flow: +// 1) Create room: generate salt and room key, derive keys from passphrase, wrap RCK and send auth key + wrapped blob to server. +var salt = RoomCrypto.GenerateSalt(); +var roomKey = RoomCrypto.GenerateRoomKey(); +var derived = RoomCrypto.DeriveKeys("correct horse battery staple", salt); +// derived.AuthKeyHex is sent to server as the join credential +// derived.KeyEncryptionKey (KEK) is used locally to wrap roomKey with AES-GCM (use EncryptBytes/EncryptText as appropriate) + +// 2) Encrypt/decrypt room content with the room key +var plaintext = "hello room"; +var ct = RoomCrypto.EncryptText(plaintext, roomKey); +if (RoomCrypto.IsRoomCiphertext(ct) && RoomCrypto.TryDecryptText(ct, roomKey, out var recovered)) +{ + // recovered == "hello room" +} +``` + +## Notes +- PBKDF2 parameters are fixed: 16-byte salt, 210000 iterations, 64-byte output; the auth key is returned as lowercase hex and the KEK as raw bytes. +- AES-GCM parameters are fixed: 12-byte nonce, 16-byte tag, 32-byte key (AES-256). Text wire format is the literal prefix "$RC1$" then base64(nonce||tag||ciphertext). +- TryDecryptText returns false for non-room ciphertext or when decryption/authentication fails (malformed base64, wrong key, or tampering). Protect KEK and RCK in memory and avoid persisting raw keys. diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Services/AsciiBannerService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Services/AsciiBannerService.cs.md new file mode 100644 index 0000000..162c456 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Services/AsciiBannerService.cs.md @@ -0,0 +1,25 @@ +# AsciiBannerService + +> **File:** `src/EchoHub.Core/Services/AsciiBannerService.cs` +> **Kind:** class + +```csharp +public static class AsciiBannerService +``` + + +Renders input text as a 5-row block-character banner (the /banner command). It uses a self-contained, hand-authored font defined in code, with no dependencies or network access, producing plain text content that can be transmitted like any other message; the renderer trims input to the maximum length and skips characters not defined in the font. + +## Remarks +This symbol provides a deterministic, dependency-free banner renderer that can be used anywhere a compact ASCII-art label is desirable. The font is embedded in code as a glyph dictionary, so rendering is purely local and consistent across environments. Input is uppercased to match the glyph keys, glyphs are joined per row with a single space, and ink is rendered by replacing the '#' glyphs with the block character '█' and '.' with spaces; trailing spaces on each line are trimmed to minimize payload. + +## Example +```csharp +string? banner = AsciiBannerService.Render("EchoHub"); +if (banner != null) + Console.WriteLine(banner); +``` + +## Notes +- Non-renderable input (no supported characters) yields null; callers should handle null results to avoid printing empty banners. +- The method trims whitespace and enforces a maximum length of 20 characters; longer input is truncated before rendering. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Services/FileValidationHelper.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Services/FileValidationHelper.cs.md new file mode 100644 index 0000000..e3d49e8 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Services/FileValidationHelper.cs.md @@ -0,0 +1,19 @@ +# FileValidationHelper + +> **File:** `src/EchoHub.Core/Services/FileValidationHelper.cs` +> **Kind:** class + +```csharp +public static class FileValidationHelper +``` + + +FileValidationHelper centralizes lightweight, stream-based validation for common image formats and audio file names. Its IsValidImage(Stream) method reads the stream header (without changing the stream's position) and recognizes JPEG, PNG, GIF, and WebP by their magic numbers, returning true for known formats and false otherwise. IsAudioFile(string) validates a file name’s extension against a predefined set of audio extensions in a case-insensitive manner. Together, these helpers let callers pre-filter content before attempting to decode or process media data. + +## Remarks +This symbol provides a single, testable utility to detect supported media formats without pulling in a full decoder. By encapsulating the magic-number checks and the extension-based guard, it reduces duplication and concentrates format-coverage decisions in one place. It favors a fast, low-allocation validation path and leaves actual parsing to dedicated components. + +## Notes +- Non-seekable streams cause IsValidImage to return false (the check stream.CanSeek is performed up-front). +- IsAudioFile relies solely on the file extension and does not inspect file contents. +- WebP detection requires a RIFF header followed by a WEBP tag at the expected offsets; malformed headers degrade gracefully to false. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Core/Services/ImageToAsciiService.cs.md b/docs/auriondocs/Code/src/EchoHub.Core/Services/ImageToAsciiService.cs.md new file mode 100644 index 0000000..e0f2d8c --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Core/Services/ImageToAsciiService.cs.md @@ -0,0 +1,28 @@ +# ImageToAsciiService + +> **File:** `src/EchoHub.Core/Services/ImageToAsciiService.cs` +> **Kind:** class + +```csharp +public class ImageToAsciiService +``` + + +ImageToAsciiService is a lightweight utility that converts an input image stream into color-aware ASCII art by packing two vertical pixels into a single character cell using half-block characters and per-cell color tags. Use GetDimensions to pick a target resolution and ConvertToAscii when you need a textual, ASCII-only representation of an image for logs, chat, or environments without graphical support. + +## Remarks +The class embodies a small, focused translation between raster images and ASCII art. It emits inline color tokens only when the color changes, preserving color fidelity while keeping the output readable in plain-text environments. The two-pixel vertical mapping (top pixel as the foreground color, bottom pixel as the background) enables higher-density representation than single-character ASCII, while remaining printable and parseable by consumers that understand the {F:...}{B:...}{X} tags. An even-height safeguard ensures the processing loop always handles complete pixel pairs, resizing the image as needed to maintain consistent output. + +## Example +```csharp +using System.IO; + +var stream = File.OpenRead("path/to/image.png"); +var service = new ImageToAsciiService(); +string ascii = service.ConvertToAscii(stream, 80, 40); +Console.WriteLine(ascii); +``` + +## Notes +- The ASCII output relies on the presence of the {F:RRGGBB}{B:RRGGBB}{X} tags and the block characters; ensure your rendering environment understands these tokens, otherwise you will see literal tags. +- If a height is provided as an odd number, the implementation advances to an even height, which may slightly alter the aspect ratio of the produced art. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcBroadcaster.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcBroadcaster.cs.md new file mode 100644 index 0000000..7186975 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcBroadcaster.cs.md @@ -0,0 +1,19 @@ +# IrcBroadcaster + +> **File:** `src/EchoHub.Server.Irc/IrcBroadcaster.cs` +> **Kind:** class + +```csharp +public class IrcBroadcaster : IChatBroadcaster +``` + + +Broadcasts chat events to IRC clients by translating application-level messages and room/user events into IRC protocol lines and sending them via the IrcGatewayService. Decrypts transport-layer-encrypted message content so IRC clients (which do not support the application's app-layer encryption) receive readable text; end-to-end room ciphertext markers (e.g. $RC1$) are preserved. Use this class when you need to mirror server chat rooms and user lifecycle events to connected IRC clients. + +## Remarks +IrcBroadcaster is the IRC-specific implementation of the IChatBroadcaster contract and acts as the bridge between the chat model and the IRC wire format. It relies on IMessageEncryptionService to remove transport-layer encryption for IRC consumers and on IrcMessageFormatter to produce IRC-compliant lines (including splitting long messages and formatting reply prefixes/embeds). Messages are dispatched by enumerating connections returned from the gateway and sending formatted lines to each connection; the broadcaster also follows IRC conventions such as avoiding echoing a message back to the originating connection. + +## Notes +- Message content is decrypted before formatting; E2E room ciphertext (explicit markers like $RC1$) is left unchanged so room-encrypted messages are not exposed. +- The broadcaster avoids echoing by comparing connection IDs (excludeConnectionId) when sending normal messages. Be aware this requires callers to pass the originating connection id to suppress local echoes correctly when appropriate. +- Sends are awaited sequentially per connection/line (each connection's SendAsync is awaited in a loop). Under high fan-out this can introduce latency; consider batching or parallelization at the caller/gateway level if latency becomes an issue. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcClientConnection.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcClientConnection.cs.md new file mode 100644 index 0000000..03d7bd0 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcClientConnection.cs.md @@ -0,0 +1,22 @@ +# IrcClientConnection + +> **File:** `src/EchoHub.Server.Irc/IrcClientConnection.cs` +> **Kind:** class + +```csharp +public sealed class IrcClientConnection : IAsyncDisposable +``` + + +Manages a single IRC client TCP connection: wraps a TcpClient/Stream pair, serializes outgoing IRC lines, provides simple registration and channel membership state, and exposes read/write helpers for the IRC protocol. Use this when handling a single connected client in server code so you get consistent CRLF framing, UTF-8 encoding without BOM, and serialized writes. + +## Remarks +This type represents the per-connection state and I/O for one IRC client. It centralizes the socket-level StreamReader/StreamWriter setup (UTF-8 without BOM, CRLF line endings, AutoFlush) and enforces serialized writes with an internal SemaphoreSlim. The class keeps mutable registration and presence properties (nickname, username, authentication flags, away message, joined channels) so higher-level command handlers and broadcaster threads can consult or update a single source of truth. Channel membership access is guarded by a private lock and exposed via snapshot methods so broadcaster threads can read without additional synchronization. + +## Notes +- ReadLineAsync swallows read exceptions and returns null; treat a null result as "connection closed" or irrecoverable read error. +- SendAsync swallows write exceptions (connection lost) after serializing via an internal semaphore; callers cannot observe write failures directly. +- Registration properties (Nickname, Username, UserId, IsRegistered, etc.) are not synchronized by this class — callers should coordinate concurrent access if needed. +- Channel membership APIs (JoinChannel, LeaveChannel, IsInChannel, GetJoinedChannels) are thread-safe: the implementation takes a lock and GetJoinedChannels returns a snapshot list to avoid callers iterating the internal set directly. +- Hostmask composes Nickname and Username; Username may be null so Hostmask uses Username ?? Nickname in its string formatting. +- DisposeAsync closes the underlying TcpClient and disposes the reader/writer and semaphore; do not use the connection after disposing. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md new file mode 100644 index 0000000..ee1d6e6 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md @@ -0,0 +1,933 @@ +# IrcCommandHandler.cs + +> **Source:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` + +## Contents + +- [IrcCommandHandler](#irccommandhandler) + - [IrcCommandHandler (constructor)](#irccommandhandler-constructor) + - [ServerName](#servername) + - [HandleAuthenticateAsync](#handleauthenticateasync) + - [HandleAwayAsync](#handleawayasync) + - [HandleCapAsync](#handlecapasync) + - [HandleCommandAsync](#handlecommandasync) + - [HandleJoinAsync](#handlejoinasync) + - [HandleListAsync](#handlelistasync) + - [HandleModeAsync](#handlemodeasync) + - [HandleNamesAsync](#handlenamesasync) + - [HandleNickAsync](#handlenickasync) + - [HandlePartAsync](#handlepartasync) + - [HandlePassAsync](#handlepassasync) + - [HandlePingAsync](#handlepingasync) + - [HandlePrivmsgAsync](#handleprivmsgasync) + - [HandleQuitAsync](#handlequitasync) + - [HandleTopicAsync](#handletopicasync) + - [HandleUserAsync](#handleuserasync) + - [HandleWhoAsync](#handlewhoasync) + - [IrcToEchoHubChannel](#irctoechohubchannel) + - [RequireRegisteredAsync](#requireregisteredasync) + - [RunAsync](#runasync) + - [SendChannelTopicAsync](#sendchanneltopicasync) + - [SendModeErrorAsync](#sendmodeerrorasync) + - [SendMotdAsync](#sendmotdasync) + - [SendNamesReplyAsync](#sendnamesreplyasync) + - [SendWelcomeBurstAsync](#sendwelcomeburstasync) + - [TryCompleteRegistrationAsync](#trycompleteregistrationasync) +- [HandleWhoisAsync](#handlewhoisasync) + +--- + +## IrcCommandHandler +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** class + +```csharp +public sealed class IrcCommandHandler +``` + + +Acts as the main dispatcher that translates incoming IRC protocol messages from a single IrcClientConnection into actions against the server-side chat, user and channel services. Reach for this class when you need the gateway that accepts an IRC client, performs registration/authentication (SASL or PASS), sends the welcome/MOTD burst, and maps channel/query commands (JOIN, PART, PRIVMSG, NAMES, TOPIC, WHO/WHOIS, LIST, etc.) into the server's chat/channel/user APIs. + +## Remarks +This sealed handler centralizes IRC protocol handling for one client connection. It coordinates authentication (including SASL and PASS fallbacks), completes IRC registration (NICK/USER), and then routes post-registration commands to the underlying IChatService, IUserService, and IChannelService. It also enforces gateway-specific policies mentioned in the source comments: encrypted rooms are not readable over IRC (so joins are blocked), system channels are not proxied to IRC, and private channels are omitted from LIST results. Message history replay must be decrypted via IMessageEncryptionService before being sent to the IRC client. + +## Notes +- Encrypted rooms are intentionally blocked from JOIN over the IRC gateway: the gateway does not hold room keys and therefore cannot expose encrypted room contents to IRC clients. +- Private channels are hidden from LIST to match the SignalR client's channel visibility; expect LIST to only include public/discoverable channels. +- Registration and authentication have multiple paths (SASL, PASS, or account registration fallback); callers should expect asynchronous authentication flow and that RunAsync accepts a CancellationToken to stop processing. + +--- + +### IrcCommandHandler (constructor) +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** constructor + +```csharp +public IrcCommandHandler( + IrcClientConnection conn, + IrcOptions options, + IChatService chatService, + IUserService userService, + IChannelService channelService, + IMessageEncryptionService encryption, + ILogger logger) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `conn` | [`IrcClientConnection`](IrcClientConnection.cs.md) | — | +| `options` | [`IrcOptions`](IrcOptions.cs.md) | — | +| `chatService` | [`IChatService`](../EchoHub.Core/Contracts/IChatService.cs.md) | — | +| `userService` | [`IUserService`](../EchoHub.Core/Contracts/IUserService.cs.md) | — | +| `channelService` | [`IChannelService`](../EchoHub.Core/Contracts/IChannelService.cs.md) | — | +| `encryption` | [`IMessageEncryptionService`](../EchoHub.Core/Contracts/IMessageEncryptionService.cs.md) | — | +| `logger` | `ILogger` | — | + + +The constructor initializes an IrcCommandHandler by wiring together its required collaborators: IrcClientConnection, IrcOptions, IChatService, IUserService, IChannelService, IMessageEncryptionService, and ILogger. It stores these dependencies in private fields so the command-handling logic can access the IRC connection, configuration, chat and user/channel services, encryption features, and logging throughout command processing. This pattern follows dependency injection, enabling easy testing with mocks and seamless composition by the application’s DI container at startup. + +## Remarks +By aggregating these collaborators, the constructor centralizes the wiring of core capabilities—network I/O, configuration, domain services for chat, user and channel state, cryptographic operations, and observability—so command processing remains focused on business logic rather than setup. This design promotes testability, consistency, and clear separation of concerns within the IRC subsystem. + +## Notes +- The constructor as shown does not perform null checks; ensure the DI container enforces non-null registrations or add guards in production code. +- Be mindful of lifetime management: the handler should typically share lifetimes with its collaborators or be disposed in tandem to avoid resource leaks. + +--- + +### ServerName +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** property + +```csharp +private string ServerName => _options.ServerName +``` + + +This private read-only property exposes the server name configured in the handler’s options by forwarding to _options.ServerName. It should be used whenever the command handler needs the target IRC server name, offering a single indirection point if the source of that value changes in the future. + +## Remarks + +By wrapping the access in ServerName, you decouple usage from the underlying options data. This centralization makes future changes (like deriving the server name from a different config source or applying normalization) localized to this property. It also communicates that the server name is a configuration concern and not a computed field of the handler itself. + +## Notes + +- The property simply forwards to _options.ServerName; it does not perform validation or mutation. +- If _options.ServerName can change at runtime, callers may observe updates on subsequent accesses. + +--- + +### HandleAuthenticateAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleAuthenticateAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles SASL authentication for a connected IRC client by processing the SASL-related AUTHENTICATE messages. It supports initiating SASL with PLAIN, aborting SASL, and performing the actual PLAIN payload verification, ultimately authenticating or registering the user, and then updating the connection state and sending appropriate IRC numeric replies. + +## Remarks +This method centralizes SASL negotiation within the command handler, bridging the IRC SASL protocol with the application's user store. It redacts the password in logs and relies on the user service to either authenticate or register the user, enabling a smooth first-time login flow. It validates payload structure and wraps the process in a catch block to translate unexpected errors into SASL failure feedback while preserving a consistent connection state. + +## Notes +- The SASL payload must decode to a null-delimited string yielding at least three parts; malformed payloads trigger an ERR_SASLFAIL response. +- The code derives the username from parts[1] when present, otherwise parts[0], and normalizes it to lowercase; the actual password is sourced from a redacted variable and is not logged. +- On success, the connection's Nickname and UserId are populated, the connection is marked authenticated, and the client receives both a LOGGEDIN notice and a SASL success reply; failures emit ERR_SASLFAIL and are logged for auditing. + + +--- + +### HandleAwayAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleAwayAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandleAwayAsync processes a user's away status in response to the IRC AWAY command. It first ensures the caller is registered; if not, it exits early. When a non-empty parameter is supplied, it stores that string as the away message on the connection, updates the user's status to Away via the chat service, and sends a RPL_NOWAWAY reply to the client. If no parameter is provided, it clears the away message, updates the status to Online with a null message, and sends a RPL_UNAWAY reply. The method is asynchronous, so it does not block the command handling path while performing persistence and network communication. + +## Remarks +Consolidates away-state handling in a single place so all callers see the same effect on status and client notification. It keeps IrcCommandHandler lean by delegating away management and relies on _chatService to persist user state. It uses a simple, deterministic flow based on whether a message parameter is provided. + +## Notes +- Accessing _conn.UserId with the null-forgiving operator assumes RequireRegisteredAsync succeeded; calling this method without a valid registered session could throw a NullReferenceException. +- This method sends numeric replies (RPL_NOWAWAY / RPL_UNAWAY) to the connected client; ensure ServerName and _conn are valid at call time. + +--- + +### HandleCapAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleCapAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandleCapAsync processes CAP negotiation commands from the IRC server. It requires at least one parameter; if none are provided, it returns without action. It switches on the upper-cased first parameter to implement the SASL/capability handshake: on LS it requests the sasl capability and marks negotiation as in progress; on REQ it either acknowledges the 'sasl' request and enables SASL, or responds with NAK for the requested capability; on END it ends negotiation and, if identity information is available and the client is not yet registered, triggers a registration attempt via TryCompleteRegistrationAsync. + +## Remarks +This method centralizes the CAP negotiation lifecycle for the IRC connection, coordinating with the connection state (_conn) to track whether a CAP negotiation is underway, whether SASL is engaged, and whether registration has completed. By encapsulating the protocol specifics here, it avoids scattering CAP handling logic across multiple handlers and ensures correct sequencing between CAP negotiation, SASL activation, and user registration. + +## Notes +- The method short-circuits when there are no parameters, avoiding potential null-reference issues. +- The REQ path treats a missing or non-matching second parameter as a NAK for the requested capability, preserving protocol safety. +- END clears the negotiation flag and only triggers registration if Nickname and Username are non-null and the client is not already registered, preventing premature or repeated registration attempts. + + +--- + +### HandleCommandAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private Task HandleCommandAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Dispatches incoming IRC commands by normalizing the command to uppercase and routing to the corresponding per-command asynchronous handler, centralizing the IRC command handling logic (e.g., CAP -> HandleCapAsync, PRIVMSG -> HandlePrivmsgAsync). If the command is unknown, it responds with the ERR_UNKNOWNCOMMAND numeric back to the client. + +## Remarks +Centralizes command dispatch behind a single switch expression, mapping command strings to their asynchronous handlers. This design makes it straightforward to extend support for new commands by adding a new case to the switch. It returns a Task to support asynchronous work and relies on the private _conn to send numeric replies back to the client; some branches return Task.CompletedTask to represent no-op work for certain commands (e.g., PONG). + +## Example +```csharp +// Example: dispatch flow for a known command +IrcMessage msg = /* ... */; +await HandleCommandAsync(msg); // if msg.Command == "PRIVMSG" this path invokes HandlePrivmsgAsync(msg) +``` + +## Notes +- Unknown commands trigger an ERR_UNKNOWNCOMMAND reply, authored with the server name and the raw command. +- The PONG path is treated as a no-op by returning Task.CompletedTask, avoiding unnecessary asynchronous work. + + +--- + +### HandleJoinAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleJoinAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles an IRC JOIN request for a registered user, performing parameter validation, channel-name mapping, and policy checks before joining the user to each requested channel. It delegates to backend services to perform the join, then updates the client with a JOIN confirmation, channel topic, NAMES list, and a decrypted history replay. + +## Remarks +This function centralizes the join workflow for the IRC gateway and enforces privacy and policy constraints: end-to-end encrypted channels and server-managed system channels are blocked from IRC joins, ensuring the EchoHub client remains the source of truth for restricted channels. It coordinates with the connection object, channel service, and chat service to validate input, perform joins per channel (supporting RFC 1459-style per-channel keys), and synchronize the IRC client view (JOIN message, topic, NAMES, and history). + +## Notes +- Requires the user to be registered; if not, the method exits early and no join is attempted. +- If there are fewer than one parameter, the gateway responds with ERR_NEEDMOREPARAMS to indicate insufficient input. +- For each channel, invalid channel names yield ERR_NOSUCHCHANNEL with an invalid channel notice. +- End-to-end encrypted channels are blocked from IRC joins; use the EchoHub client for such channels. +- System channels are blocked from IRC joins because they stream content over SignalR; use the EchoHub client for access. +- When a channel join requires a password and the provided key is incorrect or missing, the gateway responds with ERR_BADCHANNELKEY. +- History is replayed after joining, with Content and any embedded replies decrypted for proper IRC presentation. + +--- + +### HandleListAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleListAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Implements the IRC LIST command for the server. After verifying the client is registered, it fetches the channel list from the channel service, filters to public channels, and sends one RPL_LIST reply per channel containing the channel name, online user count, and topic. If a channel is protected, a [+k] lock hint is prefixed to the topic. Private channels are intentionally hidden to match what the SignalR client sees. Once all public channels have been reported, it sends RPL_LISTEND to signal completion. + +## Remarks +This handler encapsulates the server-side semantics of channel discovery separate from the client protocol encoding. By filtering to IsPublic channels, it keeps private channels from being exposed to clients, preserving privacy where appropriate. The lock indicator (+k) encodes channel protection state in the LIST output, while the Topic is plumbed directly into the listing, enabling clients to present useful metadata without additional requests. The approach keeps channel management in _channelService and I/O in _conn, promoting testability and a clean separation between data retrieval and protocol signaling. + +## Notes +- The method requires a registered user; unauthenticated users will cause the method to return early without emitting LIST data due to the initial RequireRegisteredAsync check. +- Private channels are hidden by design via the IsPublic filter; modify the filter only if you intend to expose private channels and ensure client expectations are updated accordingly. + + +--- + +### HandleModeAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleModeAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandleModeAsync processes incoming MODE commands for channels and queries. It first ensures the caller is registered, then validates parameters and resolves the IRC target. For channel targets, it either returns the current channel mode or applies mode changes (notably +k to set a channel password and -k to clear it), persisting changes through the channel service and signaling results with the appropriate IRC numerics. When the target is not a channel, it responds with the user-mode indicator (+) to indicate no user modes are reported. If the channel cannot be resolved, it returns ERR_NOSUCHCHANNEL. When querying a channel's mode (MODE #channel with no extra parameters), it responds with RPL_CHANNELMODEIS and, if the channel is protected, indicates +k. For mode changes, it handles +k (requiring a key) and -k (clearing the key); unknown modes yield ERR_UNKNOWNMODE. A small, targeted behavior detail is that probing the ban list returns an empty list via RPL_ENDOFBANLIST to mirror common client expectations during join. + +## Dependencies +- MODE +- Parameters +- IrcNumericReply + +## Dependency APIs (verified signatures) +- property `Parameters` (`src/EchoHub.Server.Irc/IrcMessage.cs`) +- class [`IrcNumericReply`](IrcNumericReply.cs.md) (`src/EchoHub.Server.Irc/IrcNumericReply.cs`) + - field `string RPL_WELCOME` + - field `string RPL_YOURHOST` + - field `string RPL_CREATED` + - field `string RPL_MYINFO` + - field `string RPL_ISUPPORT` + - field `string RPL_MOTDSTART` + - field `string RPL_MOTD` + - field `string RPL_ENDOFMOTD` + - field `string ERR_NOMOTD` + - field `string RPL_NOTOPIC` + - field `string RPL_TOPIC` + - field `string RPL_NAMREPLY` + - …and 35 more member(s) not shown + +## Symbol To Document +- Name: HandleModeAsync +- Kind: method +- File: src/EchoHub.Server.Irc/IrcCommandHandler.cs +- Language: csharp +- ID: 7207cb42-b229-42e0-9b0c-126018e8c975 + +--- + +### HandleNamesAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleNamesAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandleNamesAsync processes an incoming NAMES-like query for the IRC command handler. It first ensures the caller is registered by awaiting RequireRegisteredAsync; if the user is not registered, the method exits early to prevent exposing channel membership information to unauthorized callers. It then requires at least one parameter; if none are provided, it returns without a response. It converts the first parameter to the internal EchoHub channel using IrcToEchoHubChannel; if this mapping yields null, the method again exits. When all preconditions succeed, it issues the names response for the mapped channel by calling SendNamesReplyAsync with that channel. + +## Remarks +This method centralizes the NAMES query flow, isolating authentication, input validation, and channel-name resolution from the response formatting logic. It enforces that only authenticated, well-formed requests proceed to produce a response, contributing to predictable and secure command handling. + +## Notes +- Silent declines: if preconditions fail (not registered, missing parameters, or invalid channel mapping), the method returns without emitting a response. +- The mapping function (IrcToEchoHubChannel) determines whether an IRC channel reference has a corresponding internal EchoHub channel; a null result means no valid target was found, and no response is produced. + +--- + +### HandleNickAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleNickAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles the NICK command from a connected IRC client. It validates that a nickname parameter is supplied, enforces the server's username rules, stores a canonical lowercase nickname on the connection, and, when applicable, advances the registration flow by attempting to complete registration if a username is already present. + +## Remarks +Centralizes nickname processing in the command handler to ensure consistent validation, normalization, and state progression. It uses numeric replies to communicate issues back to the client (missing nickname or invalid nickname) and coordinates with the registration logic via TryCompleteRegistrationAsync once the client is partially authenticated. Normalizing to lowercase provides a stable internal identity, independent of the client's casing. + +## Notes +- The error text for invalid nicknames lists allowed characters and length; confirm that UsernameRegex() and the user-visible message remain in sync to avoid misleading users. + +--- + +### HandlePartAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandlePartAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Leaves one or more IRC channels as requested by an incoming IrcMessage. It first ensures the caller is registered; if not, it exits early without issuing any IRC traffic. It expects at least one parameter; the first parameter is a comma-separated list of raw channel names, and an optional second parameter carries a part message to be appended after PART. For each channel in the list, the method translates the raw channel into an internal channel name using IrcToEchoHubChannel; if mapping returns null, that channel is skipped. It then tells the chat service to leave the mapped channel, updates the local connection state by calling LeaveChannel, and finally emits the IRC PART command for that channel, including the optional message. + +## Remarks +Acts as a coordination boundary between the IRC protocol and the application's connection state. It encapsulates registration verification, channel translation, state mutation, and protocol emission in a single command path. Because it awaits each channel in sequence, multiple PARTs are issued in order rather than in parallel. + +## Notes +- Early returns ensure no actions occur if the user is not registered or if no channels are specified. +- Channels that cannot be translated via IrcToEchoHubChannel are skipped without error. +- The emitted PART command uses the hostmask and a '#channel' target, and appends an optional message if provided. + +--- + +### HandlePassAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private Task HandlePassAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandlePassAsync is a private helper in the IRC command handling flow that processes the PASS command for a connection. It blocks re-registration by sending ERR_ALREADYREGISTERED when the connection is already registered, and if a password parameter is provided, it routes that parameter to the connection’s password handling path (the actual value is redacted in this snippet). In cases where neither condition applies, it completes without performing additional work. + +## Remarks +This abstraction centralizes PASS command handling within the command handler to ensure consistent protocol error signaling and password processing across the handshake sequence. It delegates state management and messaging to the underlying connection object, which keeps the command dispatch logic focused and testable. The explicit redaction of the password demonstrates a security-conscious approach to handling sensitive data, avoiding exposure in logs or snapshots. By returning a Task, the method remains composable with the asynchronous command pipeline. + +## Notes +- If a PASS parameter is provided, ensure proper validation and secure handling of the credential; the actual value is redacted here, so verify correctness in your environment. +- The method relies on external state (_conn.IsRegistered) and may either complete synchronously or proceed asynchronously via SendNumericAsync; callers should await as appropriate to preserve command-ordering guarantees. +- This function does not perform full authentication itself; it coordinates with the connection object for state and output, acting as a gateway in the PASS handling path. + +--- + +### HandlePingAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandlePingAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Responds to IRC PING messages by sending a corresponding PONG back to the server to keep the connection alive. It chooses the token to include in the PONG from the incoming message: if a parameter is present, that token is used; otherwise it falls back to the server name. The response is sent using the underlying connection with the format : PONG :. + +## Remarks +Internally, this method serves as the keep-alive handler for the IRC command flow. By basing the PONG on ServerName and the received parameters, it guarantees a consistent reply format and avoids leaking raw protocol details to higher layers. It relies on the ServerName and Parameters dependencies and on the underlying connection to transmit the response. + +## Example +```csharp +// Example: a PING with a token results in a PONG containing that token +var token = "12345"; +// Assuming ServerName is "irc.example.org" +var response = $":{ServerName} PONG {ServerName} :{token}"; +// The actual send occurs via _conn.SendAsync in HandlePingAsync +``` + +## Notes +- If msg.Parameters is empty, token defaults to ServerName. +- The method is private; usage is internal to the IrcCommandHandler and not exposed publicly. +- Exceptions from SendAsync propagate; callers may need to log or retry as part of larger connection management. + +--- + +### HandlePrivmsgAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandlePrivmsgAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles the PRIVMSG command by validating parameters, ensuring the sender is registered, and routing channel-targeted messages to the EchoHub chat service. It rejects private messages (targets that do not start with '#') with an appropriate error and surfaces delivery failures back to the IRC client. + +## Remarks +This method acts as a boundary between IRC protocol handling and the EchoHub chat system. It enforces channel-only messaging for PRIVMSG, consolidates parameter validation and error reporting via IRC numeric replies, and delegates the actual delivery to a dedicated chat service. By encapsulating channel-name translation (IrcToEchoHubChannel) and the delivery call (SendMessageAsync), it keeps command handling focused and testable, while remaining resilient to mapping failures and chat-service errors. + +## Notes +- Requires the current connection to be registered; otherwise the operation is short-circuited. +- If the PRIVMSG target does not begin with '#', a private-message error is returned: ERR_NOSUCHNICK with a hint to use channels. +- If channel name mapping returns null, the method exits without performing delivery. +- If SendMessageAsync reports an error, the client receives ERR_CANNOTSENDTOCHAN to indicate delivery failure to the channel. + +--- + +### HandleQuitAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleQuitAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles a quit event by sending an IRC ERROR line to the active connection that signals the closing of the link. It derives the quit reason from the first parameter of the incoming IrcMessage when provided, otherwise it uses 'Client quit' as a default. + +## Remarks +Centralizes the termination messaging for quit scenarios, ensuring a consistent closing notice across paths that terminate a connection. It formats the message with the current nickname and the resolved quit reason, and delegates the actual network transmission to _conn.SendAsync, keeping the higher-level quit flow simple and testable. + +## Example +```csharp +// Example usage within the same class (quit with a reason) +var msg = new IrcMessage { Parameters = new List { "Server maintenance" } }; +await HandleQuitAsync(msg); +``` + +## Notes +- This method only sends the closing line; it does not by itself terminate the connection. The caller should close the connection after the message is sent. +- It relies on msg.Parameters[0] as the quit reason; if there are multiple parameters, only the first is used. +- Assumes msg.Parameters is non-null; if it's null, this will throw a NullReferenceException. + +--- + +### HandleTopicAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleTopicAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +HandleTopicAsync processes the IRC TOPIC command for a channel. It verifies the caller is registered, resolves the channel name from the command parameters, and either sends the current topic or updates it via the channel service using the provided topic text. On a successful update, it broadcasts the change to SignalR clients and echoes the topic back to the IRC client; on failure it returns an appropriate IRC numeric error. + +## Remarks +This method acts as the integration point between IRC command handling, domain services, and client notifications. It relies on the authentication check (RequireRegisteredAsync) and uses the channel service to persist topic changes while informing connected clients through the chat service. Numeric errors are produced through IrcNumericReply based on the nature of the failure (non-existent channel vs. insufficient privileges), ensuring correct IRC protocol behavior. When a topic is cleared, a whitespace topic is treated as null and passed to UpdateTopicAsync, signaling a topic removal. + +## Notes +- The method returns early if the caller is not registered or if there are insufficient parameters, preventing unintended state changes. +- It uses a null-forgiving operator on UserId when updating the topic; preconditions ensure a valid user context. +- Topic clearing is achieved by passing null to UpdateTopicAsync when the provided topic string is whitespace. +- Error handling maps ChannelError.NotFound to ERR_NOSUCHCHANNEL and all other failure cases to ERR_CHANOPRIVSNEEDED, aligning with IRC protocol expectations. + +--- + +### HandleUserAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleUserAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles the USER command as part of the IRC registration handshake. It first rejects re-registration attempts, then validates that enough parameters are present, stores the provided username and real name on the connection, and finally triggers registration completion if a nickname has already been supplied. + +## Remarks +This method encapsulates the user-side portion of the registration flow, coordinating between the incoming command data (via IrcMessage.Parameters) and the connection state. By separating the completion trigger (TryCompleteRegistrationAsync) from initial USER parsing, it keeps the registration logic cohesive and allows the NICK/USER agreement to occur in any order. It relies on the server-generated numeric replies to communicate errors back to the client and uses the connection state to decide when registration can advance. + +## Notes +- Parameter indexing assumes four parameters for a valid USER command; if fewer are provided, the handler responds with ERR_NEEDMOREPARAMS. The RealName is taken from Parameters[3], which is a potential source of off-by-one mistakes if the protocol is extended or parameters are reformatted. +- A full registration is only completed when a nickname is already present; otherwise, the method merely populates Username and RealName and leaves completion to a later trigger when Nickname arrives. +- The code does not validate that Username or RealName are non-empty; additional validation may be needed if stricter user data integrity is required. + +--- + +### HandleWhoAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleWhoAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Responds to an IRC WHO request for a channel by listing online users and signaling completion. It is invoked when a registered client asks for the current participants of a channel; it maps the supplied channel parameter to EchoHub's channel, retrieves online users via the chat service, and streams RPL_WHOREPLY rows followed by RPL_ENDOFWHO to the client. + +## Remarks +By translating EchoHub's channel membership into IRC WHO semantics, this method acts as the bridge between the IRC protocol and the chat model. It performs early guards (registration and parameter validation) before querying the chat service, ensuring consistent behavior and preventing unnecessary work for unauthenticated callers. Each user is emitted with a RPL_WHOREPLY line containing their nick, username, server, and away/here flag, followed by a final EndOfWho line to signal completion. + +## Notes +- Always emits an End of WHO line even if the channel has no online users. +- Away vs. here status is encoded as 'G' for away and 'H' for present, matching IRC conventions. + +--- + +### IrcToEchoHubChannel +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private static string? IrcToEchoHubChannel(string ircChannel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ircChannel` | `string` | — | + +**Returns:** `string?` + + +Converts a raw IRC channel into a canonical EchoHub channel name by stripping the leading '#', lowercasing, and trimming the remainder, returning null if the result does not satisfy ValidationConstants.ChannelNameRegex. This is used when bridging IRC channels to EchoHub to obtain a policy-compliant channel identifier. + +## Remarks +Centralizes the logic for translating IRC-style channels into EchoHub identifiers and enforces channel naming policy via ValidationConstants.ChannelNameRegex. It returns a lowercase, trimmed name when valid, or null when the input cannot be mapped, allowing callers to handle non-mappable channels explicitly. + +## Notes +- If ircChannel is null, this method will throw a NullReferenceException; callers should ensure a non-null value before calling. +- Results are always lowercase due to ToLowerInvariant, providing a consistent channel namespace. +- A non-matching input yields null rather than an exception, signaling an unmapped channel to the caller. + +--- + +### RequireRegisteredAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task RequireRegisteredAsync() +``` + +**Returns:** `Task` + + +RequireRegisteredAsync is a small helper that enforces a precondition: the client connection must be registered before proceeding with commands that require registration. It returns true when the connection is already registered; otherwise it sends the IRC error reply ERR_NOTREGISTERED and returns false. Callers await this method to guard subsequent operations and avoid duplicating boilerplate checks across command handlers. + +## Remarks +This abstraction centralizes the registration precondition and the associated user feedback. It guarantees consistent behavior by issuing the standard ERR_NOTREGISTERED along with the message You have not registered, matching the IRC protocol's expectations, and it short-circuits command execution when the precondition isn’t met. + +## Example +```csharp +// Usage: ensure the user is registered before issuing a command that requires registration +if (!await RequireRegisteredAsync()) +{ + return; // bail out if not registered +} + +// proceed with the operation that requires registration +``` + +## Notes +- Ensure the caller returns immediately when RequireRegisteredAsync() returns false to avoid sending duplicate replies. +- This helper assumes the underlying connection (_conn) and the server name (ServerName) are initialized; null references may occur if called too early. + +--- + +### RunAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +public async Task RunAsync(CancellationToken ct) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ct` | `CancellationToken` | — | + +**Returns:** `Task` + + +Runs an asynchronous loop that continuously reads lines from the IRC connection, trims trailing CR/LF, ignores blank lines, and dispatches each non-empty message to the IRC command handler until cancellation is requested. This is the core IO loop for processing incoming IRC traffic in the command handler lifecycle; you start it to begin processing and cancel it to stop. + +## Remarks +RunAsync is the primary lifecycle loop for the IRC command processor. It reads a raw line via _conn.ReadLineAsync(ct), cleans trailing CR/LF, and skips empty lines before turning the line into an IrcMessage with IrcMessage.Parse. The resulting message is passed to HandleCommandAsync for per-command processing, and any exceptions thrown during that processing are caught and logged to avoid tearing down the loop. Only the HandleCommandAsync call is wrapped in the try-catch; errors in reading, parsing, or line pre-processing may bubble up if they throw, which means callers should supervise the task accordingly. + +## Notes +- Exceptions from ReadLineAsync or IrcMessage.Parse are not caught here; they could terminate the loop. +- The loop ends when a null line is read (end of stream) or when the cancellation token is canceled. +- Whitespace-only lines are ignored; lines are trimmed before parsing. + +--- + +### SendChannelTopicAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task SendChannelTopicAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Fetches the current topic for the specified channel and sends the corresponding IRC numeric to the client. It queries the channel service for (topic, exists) and, if the channel exists, emits RPL_TOPIC when a topic is set or RPL_NOTOPIC when no topic is configured; if the channel doesn't exist, it returns without replying. + +## Remarks +By centralizing the topic-resolution and numeric-emission logic in a single private method, this symbol encapsulates the IRC topic-response behavior for channel-related command flow. It hides the implementation details of IrcNumericReply mappings behind a concise interface and ensures consistent message formatting (channel name prefixed with '#', topic payload prefixed with ':') when interacting with the connection and channel services. + +## Notes +- If exists is false, the method returns early with no notification to the client. +- When a channel exists but has no topic, a RPL_NOTOPIC reply is sent with the message "No topic is set". + +--- + +### SendModeErrorAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task SendModeErrorAsync(string channelName, ChannelOperationResult result) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `result` | [`ChannelOperationResult`](../EchoHub.Core/DTOs/CommonDtos.cs.md) | — | + +**Returns:** `Task` + + +Translates a channel operation error into the corresponding IRC numeric response and sends it to the client for the specified channel. It chooses the numeric based on result.Error (NotFound -> ERR_NOSUCHCHANNEL, Forbidden -> ERR_CHANOPRIVSNEEDED, otherwise ERR_KEYSET) and delivers a message containing the channel (prefixed with '#') and the human-readable error via _conn.SendNumericAsync(ServerName, numeric, `#${channelName} :${result.ErrorMessage}`). This method centralizes the error reporting for channel-mode operations so callers don't duplicate the mapping and formatting logic. + +## Remarks +By centralizing the error-to-numeric mapping, this method ensures consistent client feedback and prevents duplication of channel-name formatting and error-message construction across callers. It relies on the surrounding class’s _conn and ServerName being available; changes to the mapping or messaging format would affect all mode-error reports produced by this helper. + +## Notes +- The error mapping is not exhaustive: any ChannelError value not explicitly NotFound or Forbidden will default to ERR_KEYSET. +- This method is private and intended solely for internal command-handling use; it is not part of the public API. + +--- + +### SendMotdAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task SendMotdAsync() +``` + +**Returns:** `Task` + + +SendMotdAsync is an internal helper that transmits the server's Message of the Day (MOTD) to the connected client. It validates the configured Motd; if it is missing or whitespace it replies with ERR_NOMOTD and stops. Otherwise it sends a MOTD banner with RPL_MOTDSTART, then each newline-delimited line as an RPL_MOTD, trimming CR characters, and ends with RPL_ENDOFMOTD. + +This method consolidates MOTD delivery behind a private surface, so higher-level Irc command handlers don't need to know the exact numeric codes or line-breaking semantics. It depends on _conn for transport and _options for the Motd value, and it's a private method intended to be invoked by the MOTD-related command flow. + +## Remarks +Encapsulates the formatting and transport of MOTD to ensure consistent behavior across the server. By isolating the MOTD delivery, it keeps the command-handling code focused on protocol logic rather than presentation details. + +## Notes +- If Motd is null or whitespace, the method sends ERR_NOMOTD and returns without sending any MOTD lines. +- Each MOTD line is sent as a separate RPL_MOTD message; the code splits on '\n' and trims a trailing '\r' from each line to normalize Windows-style endings. A trailing newline in Motd may produce an empty MOTD line. +- All sends are awaited asynchronous calls to the connection; exceptions propagate to the caller. + +--- + +### SendNamesReplyAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task SendNamesReplyAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Sends the channel’s NAMES list to the IRC client by querying the chat service for online users in the channel, producing a space-separated set of nicknames, and then emitting two standard IRC numerics: RPL_NAMREPLY with the channel and nicklist, and RPL_ENDOFNAMES to mark completion. This method is invoked when handling a NAMES request for a channel, and it centralizes the formatting and numeric-codes so callers don't have to build the response themselves. + +## Remarks + +This keeps NAMES formatting centralized and aligns with the IRC protocol surface exposed by IrcNumericReply. It delegates data retrieval to _chatService and transmission to _conn, making the implementation resilient to channel naming and user list changes. It also ensures the end-of-list is always signaled after the list is sent, which is essential for IRC clients to know the response is complete. + +## Notes +- If no online users are found, the NAMES reply will carry an empty nicklist while still issuing EndOfNames; clients should handle an empty list gracefully. +- Any exceptions raised by GetOnlineUsersAsync or SendNumericAsync bubble up to the caller, so this method assumes the surrounding command handler will decide how to respond to errors. + +--- + +### SendWelcomeBurstAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task SendWelcomeBurstAsync() +``` + +**Returns:** `Task` + + +Sends the IRC welcome burst to a newly connected client by issuing the standard numeric replies (RPL_WELCOME, RPL_YOURHOST, RPL_CREATED, RPL_MYINFO, RPL_ISUPPORT) and then starts the MOTD flow via SendMotdAsync. It uses the current connection's nickname and the server name to populate the messages, and awaits each dispatch to preserve the canonical handshake order. + +## Remarks +It centralizes the initial handshake, ensuring a consistent greeting sequence for every new user. By consuming IrcNumericReply codes and composing messages with the live nickname, server name, and current time, it guarantees the client receives both identification and capability information before proceeding. The method delegates the final output of the MOTD to SendMotdAsync, keeping the handshake concerns isolated from the MOTD generation. + +## Notes +- Relies on _conn and Nickname being non-null; the null-forgiving operator means a null nickname could yield a greeting with an empty nickname. +- RPL_CREATED uses DateTimeOffset.UtcNow; this stamps the handshake time rather than the server creation date, which may be intentional for the MOTD moment but can be misleading if interpreted as server age. + +--- + +### TryCompleteRegistrationAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task TryCompleteRegistrationAsync() +``` + +**Returns:** `Task` + + +Finalizes the user's registration by completing the authentication handshake and establishing an active session. It guards against concurrent registration work by returning early if capability negotiation is still in progress or the user is already registered. If SASL-based authentication has already succeeded (IsAuthenticated and UserId is not null), it marks the connection as registered, notifies the chat service of the connected user, and sends the welcome burst to complete onboarding. + +If SASL authentication is not yet complete, it enforces a password-based login: a missing password results in an IRC error and authentication failure. When a password is supplied, it delegates to the user service to authenticate; if that fails, it attempts to register a new user with the provided nickname and password. On a successful outcome, it stores the resulting UserId and Username on the connection, marks the connection as authenticated and registered, signals the chat service that the user has connected, and sends the welcome burst. + +The method is a private helper used during the IRC session setup to ensure the connection transitions to a fully authenticated and registered state before normal chat activity begins. + +--- + +## HandleWhoisAsync +> **File:** `src/EchoHub.Server.Irc/IrcCommandHandler.cs` +> **Kind:** method + +```csharp +private async Task HandleWhoisAsync(IrcMessage msg) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `msg` | [`IrcMessage`](IrcMessage.cs.md) | — | + +**Returns:** `Task` + + +Handles an IRC WHOIS command by querying the target nick's user profile and returning the standard WHOIS information to the requester. It validates the connection is registered, extracts the nick from the message, fetches the user profile via _userService, and then dispatches a sequence of numeric replies: WHOIS user, WHOISSERVER, and optionally WHOISCHANNELS, RPL_AWAY if the user is away, and RPL_WHOISIDLE with idle and sign-on times, finishing with RPL_ENDOFWHOIS. If no profile exists for the nick, it replies with ERR_NOSUCHNICK. The method relies on asynchronous services and formats times using the profile's LastSeenAt and CreatedAt to populate idle and sign-on data. + +## Remarks +This method centralizes the WHOIS response logic for a given nickname, encapsulating the sequence of IRC numeric replies required to convey user information. It coordinates multiple collaborators (the connection, user service, and chat service) to assemble a consistent, standards-compliant response stream without leaking implementation details to callers. The precondition that the connection must be registered is enforced up front, ensuring WHOIS handling only occurs in an appropriate session context. + +## Notes +- If the target profile cannot be found, the handler emits ERR_NOSUCHNICK and aborts further replies. +- Idle time is calculated from LastSeenAt and sign-on time from CreatedAt; both are emitted via RPL_WHOISIDLE when available. +- The RPL_WHOISCHANNELS reply is sent only when the user belongs to one or more channels; otherwise this section is omitted. +- Away status (RPL_AWAY) is emitted only if the profile.Status is Away and a StatusMessage exists. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcGatewayService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcGatewayService.cs.md new file mode 100644 index 0000000..f734e4a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcGatewayService.cs.md @@ -0,0 +1,48 @@ +# IrcGatewayService + +> **File:** `src/EchoHub.Server.Irc/IrcGatewayService.cs` +> **Kind:** class + +*Figure: How IrcGatewayService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +start(("Start")) --> checkOpt{"Check IrcOptions.Enabled?"} +checkOpt -- "false" --> logDisabled["Log #quot;IRC gateway is disabled#quot;"] +logDisabled --> end1(("End")) +checkOpt -- "true" --> init["Initialize listeners list and add RunListenerAsync(Options.Port, useTls:false)"] +init --> checkTls{"Are Options.TlsEnabled and Options.TlsCertPath set?"} +checkTls -- "true" --> addTls["Add RunListenerAsync(Options.TlsPort, useTls:true)"] +checkTls -- "false" --> awaitAll +addTls --> awaitAll["Await Task.WhenAll(listeners)"] +awaitAll --> runListener["RunListenerAsync: start TcpListener and loop AcceptTcpClientAsync"] +runListener --> acceptClient["On accept: fire-and-forget HandleClientAsync(tcpClient, useTls)"] +acceptClient --> runListener +acceptClient --> createConn["Create new IrcClientConnection and add to _connections"] +createConn --> handleClient{"HandleClientAsync: useTls?"} +handleClient -- "true" --> tlsHandshake["Load cert from IrcOptions and AuthenticateAsServerAsync"] +tlsHandshake --> handshakeOk{"TLS handshake succeeded?"} +handshakeOk -- "false" --> closeTcp["Log error and close tcpClient"] +closeTcp --> endConn(("End connection setup")) +handshakeOk -- "true" --> proceedConn["Assign SslStream and continue"] +handleClient -- "false" --> proceedConn +proceedConn --> addConn["Add connection to _connections dictionary (IrcClientConnection)"] +addConn --> startProcessing["Start message processing with IrcCommandHandler and required services (IChatService, IUserService, IChannelService, IMessageEncryptionService)"] +startProcessing --> endConn +``` + +```csharp +public sealed class IrcGatewayService : BackgroundService +``` + + +Provides a hosted IRC gateway that listens for incoming TCP (and optional TLS) client connections and dispatches each to an IrcCommandHandler that bridges IRC protocol traffic to the application's chat, user and channel services. Start this BackgroundService when you want the application to accept IRC client connections without manually managing TcpListeners, TLS handshakes, or per-connection handler wiring. + +## Remarks +This BackgroundService reads configuration from IrcOptions and opens one or two listeners (plain and optionally TLS) for the ports configured. For every accepted TcpClient it creates an IrcClientConnection, stores it in an internal ConcurrentDictionary keyed by ConnectionId, and constructs an IrcCommandHandler (using IChatService, IUserService, IChannelService and IMessageEncryptionService from DI) to drive the connection. The service centralizes lifecycle concerns: listener startup/shutdown, TLS handshake and per-connection dispatching so higher-level application code can focus on chat/user/channel logic implemented in the injected services. + +## Notes +- If IrcOptions.Enabled is false the service logs and returns immediately; no listeners are started. +- TLS is only attempted when TlsEnabled is true and TlsCertPath is provided; TLS handshake failures are logged and the client connection is closed. +- The Connections collection is a ConcurrentDictionary and entries are added when clients connect. Public helper methods (GetAllConnections, GetConnectionsInChannel) filter by IrcClientConnection.IsAuthenticated — use those to obtain the set of active, authenticated clients rather than inspecting the raw dictionary directly. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessage.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessage.cs.md new file mode 100644 index 0000000..12e4dcb --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessage.cs.md @@ -0,0 +1,17 @@ +# IrcMessage + +> **File:** `src/EchoHub.Server.Irc/IrcMessage.cs` +> **Kind:** class + +```csharp +public sealed class IrcMessage +``` + + +IrcMessage is a parsed representation of an IRC protocol line that exposes the optional Prefix, the Command, and the Parameters that form the line's arguments; if a trailing payload is present, Trailing provides access to it. Use IrcMessage.Parse to convert a raw line into a structured object and inspect the command and its arguments without manual parsing. + +## Remarks +IrcMessage encapsulates the parsing result and keeps IRC-logic separate from application code. Its properties are immutable (init-only), which makes parsed messages safe to share across components after parsing. Trailing is a derived convenience that reflects the trailing payload via the Parameters collection, aligning with the IRC grammar without introducing extra mutable state. + +## Notes +- Trailing property returns the last parameter when any parameters exist; it's a convenience for the trailing payload and assumes a leading ':' in the raw line to populate it. If there was no trailing parameter in the line, Trailing will reflect the final parameter but may not be semantically a trailing payload. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessageFormatter.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessageFormatter.cs.md new file mode 100644 index 0000000..22f08cb --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcMessageFormatter.cs.md @@ -0,0 +1,21 @@ +# IrcMessageFormatter + +> **File:** `src/EchoHub.Server.Irc/IrcMessageFormatter.cs` +> **Kind:** class + +```csharp +public static class IrcMessageFormatter +``` + + +IrcMessageFormatter is a small, focused helper that converts a MessageDto into IRC PRIVMSG lines suitable for delivery in an IRC channel. It handles plain text and CTCP ACTION content, prefixes replies with the standard '> nick: snippet | ' format, and renders attachments as separate URL lines with concise type tags, using an absolute URL when a public base URL is supplied. + +## Remarks + +It centralizes the IRC-specific formatting and line-breaking logic used by the server when presenting messages to IRC clients, shielding callers from the quirks of the IRC protocol (such as per-line length limits and CTCP wrapping). The private FormatReplyPrefix creates a consistent context string for replies, including redaction of room ciphertext when needed and truncating long snippets to a safe length. Attachments are surfaced as individual lines with a small tag ([Image: ...], [Audio: ...], or [File: ...]) followed by an absolute URL, aligning with common IRC client behavior and improving link reliability. Embeds are appended using FormatEmbed, enabling rich previews where supported. + +## Notes + +- The FormatMessage path enforces line-length constraints via MaxIrcLineContentBytes, causing long content to be split across multiple PRIVMSG lines as needed. +- Encrypted-reply content is masked by the ciphertext-detection logic (e.g., [encrypted]) to avoid leaking room ciphertext in IRC. +- Absolute URL generation relies on ToAbsoluteUrl and the optional publicBaseUrl; without a base URL, attachments may render with their original (potentially relative) URLs. diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcNumericReply.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcNumericReply.cs.md new file mode 100644 index 0000000..d2f0257 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcNumericReply.cs.md @@ -0,0 +1,24 @@ +# IrcNumericReply + +> **File:** `src/EchoHub.Server.Irc/IrcNumericReply.cs` +> **Kind:** class + +```csharp +public static class IrcNumericReply +``` + + +IrcNumericReply is a static container of string constants that encode the standard IRC protocol numeric replies. It centralizes the protocol’s numeric codes so developers can reference them by name (e.g., RPL_WELCOME, ERR_UNKNOWNCOMMAND) instead of sprinkling literal strings throughout the codebase. The constants are organized by functional areas such as registration, MOTD, channel operations, list operations, WHO/WHOIS, away status, mode, errors, and SASL. + +## Remarks +Having all codes in one static class provides a single source of truth and makes it straightforward to update or extend the set as the IRC spec evolves. It also clarifies intent at call sites: emitting an IRC reply uses the corresponding constant rather than a magic string, and parsing branches can compare against these constants with confidence. This abstraction keeps server and client code aligned on canonical codes without duplicating literals. + +## Example +```csharp +// Example: emit a welcome reply using the canonical code +string code = IrcNumericReply.RPL_WELCOME; // "001" +string reply = $":server {code} Welcome to the IRC network"; +``` + +## Notes +- The constants are strings, not integers; avoid parsing them as numbers if you need to preserve leading zeros (e.g., "001"). \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcOptions.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcOptions.cs.md new file mode 100644 index 0000000..bd298b7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcOptions.cs.md @@ -0,0 +1,19 @@ +# IrcOptions + +> **File:** `src/EchoHub.Server.Irc/IrcOptions.cs` +> **Kind:** class + +```csharp +public sealed class IrcOptions +``` + + +IrcOptions is a simple configuration container that aggregates the settings controlling EchoHub's IRC bridge. It exposes toggles and values for enabling IRC, selecting ports for non-TLS and TLS connections, TLS certificate details, the server identity, an optional MOTD, and how attachment URLs are resolved via a public base URL. An application binds this object from configuration to influence how the IRC integration is started and how clients connect securely. + +## Remarks +This class acts as a plain data container that centralizes IRC-related settings, separating configuration concerns from connection logic. The SectionName constant indicates the configuration section used when binding settings, while PublicBaseUrl affects how attachment URLs are translated for IRC clients—absolute URLs when set, otherwise relative paths. It is designed to be a simple DTO bound from configuration rather than responsible for validation or side effects. + +## Notes +- If TLS is enabled but a certificate path or password is missing or invalid, TLS connections may fail; ensure a valid certificate and credentials are supplied when TlsEnabled is true. +- PublicBaseUrl, when set, makes attachment URLs absolute for IRC clients; if left unset, attachment lines fall back to the relative path. +- The defaults describe typical behavior: Port = 6667, TlsPort = 6697, and ServerName = "echohub". \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md new file mode 100644 index 0000000..0e43015 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md @@ -0,0 +1,19 @@ +# IrcServiceExtensions + +> **File:** `src/EchoHub.Server.Irc/IrcServiceExtensions.cs` +> **Kind:** class + +```csharp +public static class IrcServiceExtensions +``` + + +Extends WebApplicationBuilder with AddIrcGateway to wire up IRC gateway support. It reads a configuration flag to enable or disable the gateway and wires the necessary services when enabled, returning the builder for fluent startup configuration. + +## Remarks +Centralizes startup concerns for the IRC gateway: the extension reads IrcOptions from a configured section and conditionally registers the gateway components, enabling the feature via configuration. It keeps startup code concise and tests-focused by encapsulating the wiring behind a single extension method. + +## Notes +- IrcGatewayService and IrcBroadcaster registrations are conditional on Irc:Enabled; if false, IRC components are not registered. +- Ensure IrcOptions.SectionName matches your configuration so there is a valid section to bind from. +- Returning the builder enables fluent chaining like builder.AddIrcGateway().() \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Auth/JwtTokenService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Auth/JwtTokenService.cs.md new file mode 100644 index 0000000..17b497a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Auth/JwtTokenService.cs.md @@ -0,0 +1,18 @@ +# JwtTokenService + +> **File:** `src/EchoHub.Server/Auth/JwtTokenService.cs` +> **Kind:** class + +```csharp +public class JwtTokenService +``` + + +JwtTokenService centralizes the creation of JSON Web Tokens used for authenticating API requests. It reads the signing secret, issuer, and audience from configuration and exposes two overloads of GenerateAccessToken for User and UserProfileDto, returning the token string along with its expiration timestamp. Each generated token includes standard claims such as sub (the user/profile id), username, display_name (falling back to username if not provided), role, and a unique jti, and is signed with HmacSha256 using the configured secret. Access tokens expire after 15 minutes, while a companion refresh token can be generated with GenerateRefreshToken and hashed with HashToken for secure storage. + +## Remarks +JwtTokenService centralizes token creation, ensuring consistent signing, claims, and expiry semantics across authentication flows. By loading Jwt:Secret, Jwt:Issuer, and Jwt:Audience from configuration in one place, it reduces the risk of mismatched values and scattered configuration access. The two overloads for GenerateAccessToken allow tokens to be produced from either a User or a UserProfileDto while preserving a uniform JWT shape and claims set, including a unique jti for traceability. + +## Notes +- If Jwt:Secret, Jwt:Issuer, or Jwt:Audience is missing from configuration, the constructor throws an InvalidOperationException with a clear message, preventing startup with a misconfigured token engine. +- GenerateRefreshToken produces a cryptographically random 64-byte value and returns it as a base64 string; HashToken provides a SHA-256-based digest suitable for secure, persisted storage. The class itself does not persist refresh tokens, so you should implement storage and revocation logic in your authentication flow if needed. diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Config/ServerLogsOptions.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Config/ServerLogsOptions.cs.md new file mode 100644 index 0000000..9fd7d77 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Config/ServerLogsOptions.cs.md @@ -0,0 +1,11 @@ +# ServerLogsOptions + +> **File:** `src/EchoHub.Server/Config/ServerLogsOptions.cs` +> **Kind:** class + +```csharp +public sealed class ServerLogsOptions +``` + + +Live server-log room configuration is encapsulated by this strongly-typed options class. It binds to the ServerLogs config section and supports environment overrides, controlling whether the live streaming channel is created and who can view it. When Enabled is true, a read-only system channel is auto-created and log events are streamed in real time; log lines themselves are not stored as messages in the database, with persistence remaining in the rolling Serilog log files. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Config/SpamOptions.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Config/SpamOptions.cs.md new file mode 100644 index 0000000..4be0af9 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Config/SpamOptions.cs.md @@ -0,0 +1,19 @@ +# SpamOptions + +> **File:** `src/EchoHub.Server/Config/SpamOptions.cs` +> **Kind:** class + +```csharp +public sealed class SpamOptions +``` + + +SpamOptions is a configuration object that encapsulates the anti-spam thresholds used by the server. It is bound from the Spam config section and exposes the toggles and numeric limits that govern how the system enforces per-user rate limits, duplicate message handling, auto-muting behavior, and the protections around first-time channel joins and channel creation. The defaults are intentionally lenient so a fast typist won’t trip them, and moderators (and above) are exempt from these protections. Use this class to adjust spam-protection policy without changing code. + +## Remarks +SpamOptions centralizes policy decisions for anti-spam enforcement, serving as a single source of truth for the thresholds consumed by the spam protection subsystem. By binding to configuration, it keeps rules out of hard-coded logic and enables runtime tuning via the Spam section. The design separates concerns across rate limiting (per-user messages), duplicate detection, auto-mute behavior, and early channel-join/channel-create protections, making it easier to tune each facet without collateral impact. The auto-mute behavior ties into the existing moderation tooling (MuteExpirationService), illustrating cohesive behavior with the broader user-suspension lifecycle. The note about end-to-end encrypted rooms clarifies that identical plaintext can yield different ciphertext, so the duplicate-detection rule may not apply in those contexts. + +## Notes +- Auto-mute is controlled by AutoMuteMinutes. Setting AutoMuteMinutes to 0 disables auto-mute (rejections still apply if thresholds are reached). +- MaxMessagesPerWindow and WindowSeconds govern per-user message rate; adjust them with awareness of your typical user pacing to avoid false positives. +- MaxJoinsPerWindow and JoinWindowSeconds apply to first-time channel joins; joins to channels the user already belongs to do not count toward the limit, ensuring normal reconnects don’t trigger protections. diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Config/StatsOptions.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Config/StatsOptions.cs.md new file mode 100644 index 0000000..4e89dca --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Config/StatsOptions.cs.md @@ -0,0 +1,19 @@ +# StatsOptions + +> **File:** `src/EchoHub.Server/Config/StatsOptions.cs` +> **Kind:** class + +```csharp +public sealed class StatsOptions +``` + + +StatsOptions is a bound configuration object that governs the periodic server-stats reporter. When Enabled is true, a background job periodically snapshots server activity, logs the snapshot as pretty-printed JSON, and persists it to the database; IntervalHours controls cadence, and RetentionDays controls how long reports are kept. The environment override Stats__Enabled allows turning the reporter on or off via environment configuration without changing code. + +## Remarks +StatsOptions serves as a simple, sealed data contract that the configuration system binds to at startup, providing a single source of truth for the reporter settings. Centralizing these knobs here avoids scattering config keys throughout the code and makes it easy to swap configuration providers or add validation in one place. The defaults (Enabled = true, IntervalHours = 6, RetentionDays = 90) define the out-of-the-box behavior and can be overridden by environment or configuration. + +## Notes +- RetentionDays: 0 means keep reports indefinitely; any positive number prunes older entries. +- IntervalHours is a double; fractional values (e.g., 1.5) are allowed, but scheduling resolution depends on the hosting environment. +- Enabled acts as the master switch for the background job; disabling it stops snapshots until re-enabled. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Config/UploadLimits.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Config/UploadLimits.cs.md new file mode 100644 index 0000000..286e96a --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Config/UploadLimits.cs.md @@ -0,0 +1,31 @@ +# UploadLimits + +> **File:** `src/EchoHub.Server/Config/UploadLimits.cs` +> **Kind:** class + +```csharp +public sealed class UploadLimits +``` + + +UploadLimits is a configuration-bound value object that centralizes the admin-defined upload size caps. It reads sizes in megabytes from the Uploads configuration and exposes corresponding byte-sized properties used during enforcement. When the Uploads section is missing or incomplete, the defaults mirror HubConstants to preserve the historical built-in limits. + +## Remarks +UploadLimits centralizes the policy governing uploads (files, images, audio, avatars) and the maximum number of attachments per message. The MB-based properties feed their byte-sized counterparts (MaxFileSizeBytes, MaxImageSizeBytes, etc.) for enforcement. MaxForKind provides a per-kind ceiling, while MaxRequestBodyBytes computes the overall request-body cap (largest file size multiplied by the attachment limit) to ensure configuration changes actually take effect at the HTTP boundary. + +## Example +```csharp +var limits = new UploadLimits +{ + MaxFileSizeMB = 64, + MaxAttachmentsPerMessage = 4 +}; + +long maxImageBytes = limits.MaxImageSizeBytes; +long imageCeiling = limits.MaxForKind(AttachmentKind.Image); +long requestBody = limits.MaxRequestBodyBytes; +``` + +## Notes +- Changing MaxAttachmentsPerMessage scales the MaxRequestBodyBytes non-linearly; the request-body cap will constrain multipart uploads even if per-file size increases. +- Defaults are tied to HubConstants; if those constants change, the default limits change too unless overridden in the Uploads configuration. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/AuthController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/AuthController.cs.md new file mode 100644 index 0000000..11a7eeb --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/AuthController.cs.md @@ -0,0 +1,21 @@ +# AuthController + +> **File:** `src/EchoHub.Server/Controllers/AuthController.cs` +> **Kind:** class + +```csharp +[ApiController] +[Route("api/auth")] +[EnableRateLimiting("auth")] +public class AuthController : ControllerBase +``` + + +AuthController is the API surface that coordinates user authentication. It exposes endpoints for registering, logging in, refreshing tokens, and logging out under /api/auth, and ties together user management, JWT token generation, and refresh-token persistence. + +## Remarks +AuthController centralizes authentication concerns to enable consistent security policies such as token lifetimes and rotation. It orchestrates between user management (IUserService), token generation (JwtTokenService), and persistence of refresh tokens (EchoHubDbContext), including rotation semantics to revoke old tokens on each refresh. + +## Notes +- Refresh token rotation: on a successful refresh, the old token is revoked (RevokedAt is set) and a new token pair is issued. Clients should replace the old token with the new one and avoid reusing the former. +- Security handles: access tokens have shorter lifetimes, refresh tokens are hashed in storage, and all token exchanges occur over HTTPS. Treat tokens as highly sensitive data and store them securely on the client side. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md new file mode 100644 index 0000000..6dcc10b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md @@ -0,0 +1,453 @@ +# ChannelsController.cs + +> **Source:** `src/EchoHub.Server/Controllers/ChannelsController.cs` + +## Contents + +- [ChannelsController](#channelscontroller) + - [ChannelsController (constructor)](#channelscontroller-constructor) + - [CreateChannel](#createchannel) + - [DeleteChannel](#deletechannel) + - [GetChannelCrypto](#getchannelcrypto) + - [MapChannelError](#mapchannelerror) + - [ParseKind](#parsekind) +- [GetChannelMeta](#getchannelmeta) +- [GetChannels](#getchannels) +- [RekeyChannel](#rekeychannel) +- [SendMessageWithAttachments](#sendmessagewithattachments) +- [SendUrl](#sendurl) +- [UpdateTopic](#updatetopic) + +--- + +## ChannelsController +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** class + +```csharp +[ApiController] +[Route("api/channels")] +[Authorize] +[EnableRateLimiting("general")] +public class ChannelsController : ControllerBase +``` + + +Exposes the HTTP surface for channel-related operations under the route prefix api/channels. Authenticated clients use this controller to list and create channels, retrieve public crypto metadata and human-facing channel summaries, perform passphrase rewraps (rekey), update topics, delete channels, and post messages (including multipart uploads). Prefer calling these endpoints from client code or tests; use the underlying services (IChannelService, IMessageEncryptionService, etc.) directly only when you need to bypass HTTP semantics or perform server-side orchestration. + +## Remarks +This controller is a thin HTTP façade that orchestrates several backend services rather than implementing business logic itself. It enforces [Authorize] and configurable rate-limiting (attributes show general and upload policy groups) and delegates persistence, file storage, ASCII preview generation, encryption operations, and chat routing to injected dependencies such as IChannelService, EchoHubDbContext, FileStorageService, ImageToAsciiService, IMessageEncryptionService, IChatService and UploadLimits. Upload size and multipart limits are applied at runtime using the UploadLimits configuration rather than compile-time attributes so the controller can honor configurable limits for large attachments. + +## Notes +- GetChannelCrypto returns public crypto metadata and the PBKDF2 salt clients need to derive a join credential; it never returns the wrapped room key (that is issued only after a successful join). +- RekeyChannel re-wraps the room key to change the passphrase; historical messages are not re-encrypted (the room content key itself does not change). +- SendMessageWithAttachments applies upload limits at runtime from UploadLimits; the controller trusts clients for encrypted-channel attachments (clients must declare each file's kind and provide room-encrypted previews), while for non-encrypted channels the server may inspect files and generate ASCII previews for images. + +--- + +### ChannelsController (constructor) +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** constructor + +```csharp +public ChannelsController( + IChannelService channelService, + EchoHubDbContext db, + FileStorageService fileStorage, + ImageToAsciiService asciiService, + IHttpClientFactory httpClientFactory, + IChatService chatService, + IMessageEncryptionService encryption, + UploadLimits uploadLimits, + ILogger logger) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelService` | [`IChannelService`](../../EchoHub.Core/Contracts/IChannelService.cs.md) | — | +| `db` | [`EchoHubDbContext`](../Data/EchoHubDbContext.cs.md) | — | +| `fileStorage` | [`FileStorageService`](../Services/FileStorageService.cs.md) | — | +| `asciiService` | [`ImageToAsciiService`](../../EchoHub.Core/Services/ImageToAsciiService.cs.md) | — | +| `httpClientFactory` | `IHttpClientFactory` | — | +| `chatService` | [`IChatService`](../../EchoHub.Core/Contracts/IChatService.cs.md) | — | +| `encryption` | [`IMessageEncryptionService`](../../EchoHub.Core/Contracts/IMessageEncryptionService.cs.md) | — | +| `uploadLimits` | [`UploadLimits`](../Config/UploadLimits.cs.md) | — | +| `logger` | `ILogger` | — | + + +The ChannelsController constructor wires up the controller by receiving its dependencies through dependency injection and assigning them to private fields. This pattern allows the controller to orchestrate channel-related functionality by delegating to dedicated services such as IChannelService, EchoHubDbContext, FileStorageService, ImageToAsciiService, IHttpClientFactory, IChatService, IMessageEncryptionService, UploadLimits, and `ILogger`. The framework supplies these collaborators at creation time, enabling a testable, loosely coupled design where concerns are separated and easily mockable for unit tests. This constructor is invoked by the ASP.NET Core runtime during request handling, not by consumer code directly. + +## Remarks +The constructor centralizes the wiring of the controller's collaborators, which supports clean separation of concerns and testability. It enables the ChannelsController to delegate specialized tasks (e.g., data access, file handling, image processing, HTTP calls, chat interactions, and encryption) to dedicated services rather than embedding logic directly. + +The lack of explicit null validation means misconfigured dependency injection (missing service registrations) could surface as NullReferenceExceptions later when members are used. Relying on the DI container to validate registrations is common, but tests should provide explicit mocks to ensure predictable behavior. + +## Notes +- The constructor does not perform null checks; ensure all dependencies are registered in the DI container to avoid runtime null reference issues. +- When writing unit tests for ChannelsController, provide concrete or mock implementations for all injected services to exercise behavior reliably. + +--- + +### CreateChannel +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpPost] + public async Task CreateChannel([FromBody] CreateChannelRequest request) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `request` | [`CreateChannelRequest`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** `[HttpPost] + public async `Task`` + + +Source Code +The CreateChannel action handles the HTTP POST to create a new channel for the authenticated user. It first verifies authentication by pulling the user ID from the current user’s claims; if the claim is missing, it responds with Unauthorized and an ErrorResponse indicating that authentication is required. It then delegates the actual creation to the channel service via CreateChannelAsync, passing the caller’s GUID along with the channel properties supplied in the request (Name, Topic, IsPublic, Password, EncryptionSalt, WrappedRoomKey). If the service reports a failure, the action returns a mapped error via MapChannelError. If a channel is successfully created and it is public, it broadcasts the updated channel through the chat service to notify connected clients. Finally, it returns a 201 Created response with the location of the new channel and the Channel data in the response body. + +Dependencies +- IActionResult +- ErrorResponse +- User +- ClaimTypes +- Guid +- Channel + +Dependency APIs (verified signatures) +- record [`ErrorResponse`](../../EchoHub.Core/DTOs/CommonDtos.cs.md) (`src/EchoHub.Core/DTOs/CommonDtos.cs`) +- property [`User`](../../EchoHub.Core/Models/User.cs.md) (`src/EchoHub.Core/Models/RefreshToken.cs`) +- class [`Channel`](../../EchoHub.Core/Models/Channel.cs.md) (`src/EchoHub.Core/Models/Channel.cs`) + - `Guid Id` + - `string Name` + - `string? Topic` + - `bool IsPublic` + - `bool IsSystem` + - `string? PasswordHash` + - `string? EncryptionSalt` + - `string? WrappedRoomKey` + - `DateTimeOffset CreatedAt` + - `Guid CreatedByUserId` + - `List Messages` + +Symbol To Document +- Name: CreateChannel +- Kind: method +- File: src/EchoHub.Server/Controllers/ChannelsController.cs +- Language: csharp +- ID: 373f63c8-2a87-460c-9821-46640d93a9fc + +## Remarks +Creates a channel on behalf of the authenticated user and encapsulates the orchestration between the domain service and the HTTP response surface. It relies on _channelService to enforce business rules and persistence, and on _chatService to refresh client views when appropriate. This action adheres to RESTful semantics by returning 401 for unauthenticated requests, propagating domain errors via MapChannelError, broadcasting updates for public channels, and signaling successful creation with 201 and the new channel resource. + +## Notes +- Be aware that Guid.Parse is used on the user ID claim. If the claim value is not a valid GUID, this will throw. Consider validating with Guid.TryParse at the call site if you anticipate non-GUID claim values. +- The publication check (IsPublic) gates whether a channel update is broadcast to clients; non-public channels skip broadcasting to peers. + + +--- + +### DeleteChannel +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpDelete("{channel}")] + public async Task DeleteChannel(string channel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}"` | — | — | + + +Deletes a channel for the authenticated user by handling an HTTP DELETE request to the channel route. It reads the user's ID from the authentication claims, delegates the deletion to the channel service using that ID and the channel name, and, on success, broadcasts the deletion to the chat service before returning HTTP 204 No Content. If authentication is missing, the method responds with 401 Unauthorized and an ErrorResponse. + +## Remarks +This endpoint acts as a thin HTTP boundary that orchestrates authentication, domain deletion, and cross-service notification. It centralizes HTTP-level error handling (Unauthorized, error mapping) while delegating business rules to the channel service and the side-effect of notifying the chat service. The normalization of the channel name for the broadcast (lowercase and trimmed) helps ensure consumers react to a consistent channel identifier. + +## Notes +- Authentication is required; requests without a valid NameIdentifier claim result in 401 Unauthorized with an ErrorResponse. +- The broadcast step uses channel.ToLowerInvariant().Trim(); differences between input casing and broadcast casing could affect downstream consumers. +- If the channel is deleted successfully but the broadcast fails, the method will surface a failure (no explicit retry here); consider compensating actions if eventual consistency is important. + +--- + +### GetChannelCrypto +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpGet("{channel}/crypto")] + public async Task GetChannelCrypto(string channel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/crypto"` | — | — | + + +GetChannelCrypto is an HTTP GET action on ChannelsController that exposes essential cryptographic metadata for a channel. It indicates whether the channel is end-to-end encrypted and provides the PBKDF2 salt clients need to derive their join credential. The endpoint deliberately does not return the wrapped room key; that secret is only handed out after a successful join. The action delegates retrieval to the channel service and translates the result into standard HTTP responses: 200 OK with the crypto data when the channel exists, or 404 Not Found with an ErrorResponse if the channel does not exist. + +## Remarks +By wrapping the service call behind a minimal HTTP surface, this symbol centralizes how cryptographic metadata is surfaced while keeping the actual cryptographic material protected. It demonstrates a clear separation of concerns: business logic lives in the ChannelService, while the controller handles HTTP semantics and error translation. The exposed salt enables client-side credential derivation, while the wrapped key remains strictly withheld until the proper join flow. + +## Notes +- The action does not perform explicit authorization; ensure the surrounding middleware or route configuration enforces the intended access policy. +- It returns 404 with a generic ErrorResponse when the channel does not exist; clients should handle this scenario as an absence of channel crypto metadata. +- Do not rely on this endpoint to retrieve any sensitive material beyond allowed cryptographic metadata; the wrapped key must never be exposed through this action. + +--- + +### MapChannelError +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +private IActionResult MapChannelError(ChannelOperationResult result) => result.Error switch +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `result` | [`ChannelOperationResult`](../../EchoHub.Core/DTOs/CommonDtos.cs.md) | — | + +**Returns:** `IActionResult` + + +Converts a ChannelOperationResult into an API response by pattern-matching on result.Error and returning an appropriate HTTP result that wraps an ErrorResponse. It centralizes the translation from channel-domain errors to standard HTTP status codes (400, 403, 404, 409) so the rest of the controller does not duplicate error handling logic. + +## Remarks +This encapsulates the error-handling policy for channel operations, ensuring clients see consistent HTTP semantics across all channel actions. It decouples domain error codes from HTTP choices, so updates to status codes or payload shapes can be made in one place rather than at every call site. + +## Notes +- The branches pass result.ErrorMessage! into ErrorResponse; if ErrorMessage can be null for any mapped error, this will throw at runtime. +- New ChannelError values require extending this switch to preserve the API's error contract. + + +--- + +### ParseKind +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +private static AttachmentKind ParseKind(string? kind) => kind?.ToLowerInvariant() switch +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `kind` | `string?` | — | + +**Returns:** [`AttachmentKind`](../../EchoHub.Core/Models/AttachmentKind.cs.md) + + +This private helper translates a nullable string that labels an attachment into a concrete AttachmentKind enum. It uses a case-insensitive comparison (ToLowerInvariant) to recognize 'image' and 'audio' and map them to AttachmentKind.Image and AttachmentKind.Audio, respectively; any other label (including null) falls back to AttachmentKind.File. Callers rely on this mapping when normalizing incoming attachment metadata before further processing in the channel/server pipeline. + +## Remarks +Centralizes the normalization logic so all attachment-kind labels are interpreted consistently across the server. By funneling strings through this method, the rest of the attachment processing can operate on a well-defined enum, reducing branching and potential mismatches. + +## Notes +- Unknown labels are treated as File by design; if a new kind is introduced, update this method or extend the enum. +- Because the method is private, it's exercised via the class's public APIs; ensure tests cover scenarios that exercise this mapping through those entry points. + +--- + +## GetChannelMeta +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpGet("{channel}/meta")] + public async Task GetChannelMeta(string channel) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/meta"` | — | — | + + +Retrieves the channel metadata for a given channel identifier via HTTP GET. It returns key overview details such as message count, the number of unique posters, an estimated size, the creation date, and the room id. These metadata are tracked by the server and are available even for encrypted channels, where the server cannot access the actual messages. If the channel does not exist, it responds with 404 and an ErrorResponse; otherwise it returns the metadata payload with a 200 OK. + +## Remarks +This endpoint provides a read-only surface for obtaining channel overview information without exposing message contents. It enables clients to populate channel lists or dashboards while preserving message privacy, including for encrypted channels. By delegating the data retrieval to _channelService.GetChannelMetaAsync, the API keeps data access concerns centralized and allows the underlying storage/collection strategy to evolve without changing the surface contract. + +## Notes +- The caller must handle a 404 NotFound with an ErrorResponse when the channel is missing. The error payload documents the failure reason. +- The endpoint exposes only metadata about a channel; actual messages remain inaccessible, preserving privacy for encrypted channels. +- The operation is asynchronous; consider service performance characteristics or potential caching strategies if metadata is requested frequently. + +--- + +## GetChannels +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpGet] + public async Task GetChannels([FromQuery] int offset = 0, [FromQuery] int limit = 50) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `offset` | `int` | `0` | +| `limit` | `int` | `50` | + +**Returns:** `[HttpGet] + public async `Task`` + + +Gets a paged list of channels for the authenticated user. It enforces authentication by checking the user claims, reads the user's GUID from the claims, normalizes paging parameters (offset non-negative; limit clamped to 1–100), and delegates to the channel service to retrieve the channels, returning the result in an HTTP 200 response. + +## Remarks + +This action is intentionally thin: it performs authentication, input normalization, and orchestration between the API layer and the domain service. Centralizing paging bounds and user identification here provides consistent behavior and error handling for per-user channel retrieval across clients. + +## Notes + +- Be aware that if the NameIdentifier claim is present but is not a valid GUID, Guid.Parse will throw. Prefer Guid.TryParse or ensure identity claims are well-formed. +- The limit is clamped to the range 1–100; requests outside that range are adjusted to the nearest bound. + +--- + +## RekeyChannel +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpPost("{channel}/rekey")] + public async Task RekeyChannel(string channel, [FromBody] RekeyChannelRequest request) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/rekey"` | — | — | + + +Changes an encrypted channel's passphrase by re-wrapping its room key. The caller proves knowledge of the existing passphrase via the old authentication key, and this operation preserves history by not changing the room content key. + +## Remarks +RekeyChannel acts as a thin HTTP boundary that enforces authentication and delegates the cryptographic work to the channel service. By re-wrapping the existing room key instead of re-encrypting the historical content, it minimizes disruption while changing access controls. The controller handles authentication and error translation, while RekeyChannelAsync encapsulates the cryptographic policy in the domain layer. + +## Notes +- Authentication is mandatory; if the user is not authenticated, the endpoint returns 401 Unauthorized with ErrorResponse("Authentication required."). +- The code uses Guid.Parse on the NameIdentifier claim; if the claim is present but not a valid GUID, a runtime exception may be thrown. + +--- + +## SendMessageWithAttachments +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpPost("{channel}/messages")] + [EnableRateLimiting("upload")] + public async Task SendMessageWithAttachments(string channel, [FromQuery] string? size = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/messages"` | — | — | + + +Use SendMessageWithAttachments when you need to post a chat message to a channel that includes optional text and one or more attachments, while enforcing per-channel upload limits and channel permissions. + +It supports both cleartext and end-to-end encrypted channels: in cleartext channels the server inspects file kinds to render ASCII previews and decrypts the content, while in encrypted channels the client uploads ciphertext with per-file kind and a pre-rendered encrypted preview and the server never inspects the ciphertext. + +## Remarks + +This endpoint centralizes the server-side orchestration for uploading messages with attachments, coordinating authentication via user claims, channel validation and mutability checks, multipart form handling, per-attachment processing, and interaction with the encryption and upload-limit subsystems. It relies on collaborators such as the channel service, the database context, and the encryption helper to enforce read-only channels, mute state, and maximum message length in a consistent manner. By encapsulating these concerns, it ensures secure, policy-compliant message delivery and prevents plaintext exposure of encrypted payloads. In short, it is the single integration point for sending rich messages with attachments in EchoHub.Server. + +## Notes + +- The request size is governed at runtime by UploadLimits; configure this to control maximum allowed payloads. +- For encrypted channels, ensure that per-file previews are provided in the ciphertext workflow and that file order remains aligned with the declared previews to avoid misrendering on the client. + +--- + +## SendUrl +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpPost("{channel}/send-url")] + [EnableRateLimiting("upload")] + public async Task SendUrl(string channel, [FromBody] SendUrlRequest request, [FromQuery] string? size = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/send-url"` | — | — | + + +SendUrl is an HTTP POST endpoint on ChannelsController that accepts a channel name, a request body containing an image URL, and an optional size parameter. It authenticates the caller, validates the channel, enforces channel policies (rejects system/read-only and end-to-end encrypted channels), validates the URL, downloads the image server-side, enforces size limits, validates the image format, saves the file, and generates an ASCII preview for display in the channel. + +## Remarks + +Centralizes remote image ingestion with strict, server-side validation to prevent improper content, inconsistent client behavior, or abuse. The endpoint relies on the application's security and storage abstractions: it checks user claims, ensures channel permissions, uses FileStorage to persist the file, and uses ImageToAsciiService to produce a lightweight ASCII representation for previews. The EnableRateLimiting("upload") attribute signals this is a potentially resource-intensive operation and should be throttled to guard against abuse. + +## Notes + +- Requires authentication; missing user claims yield Unauthorized responses with a helpful error. +- Validates channel state: if the channel does not exist, is system (read-only), or is encrypted, it responds with NotFound/403/400 and an ErrorResponse explaining the reason. +- Validates the supplied URL and only accepts http/https URLs; invalid URLs or unsupported schemes produce a BadRequest with a descriptive message. +- Downloads the image server-side using an HttpClient named "ImageDownload". It handles timeouts and HTTP errors by returning BadRequest with a clear message. +- Enforces file size limits via _uploadLimits.MaxImageSizeBytes before and after downloading the content. +- Validates that the downloaded content is a real image (JPEG, PNG, GIF, WebP) before persisting. +- Determines a filename from the URL or Content-Type; if missing, it falls back to a generated name with an appropriate extension. +- Persists the file and creates an ASCII representation (via ImageToAsciiService) for downstream use. + + +--- + +## UpdateTopic +> **File:** `src/EchoHub.Server/Controllers/ChannelsController.cs` +> **Kind:** method + +```csharp +[HttpPut("{channel}/topic")] + public async Task UpdateTopic(string channel, [FromBody] UpdateTopicRequest request) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `"{channel}/topic"` | — | — | + + +Updates a channel's topic for the currently authenticated user via HTTP PUT. It verifies authentication, calls ChannelService.UpdateTopicAsync with the user's ID, the channel, and the new topic, and on success broadcasts the channel update before returning the updated channel; on failure or missing authentication, it yields an HTTP error. + +## Remarks + +Acts as the HTTP API boundary for updating a channel topic, delegating the actual update to the domain service and handling authentication. It centralizes error translation via MapChannelError and ensures clients are informed of changes in real time by broadcasting after a successful update. + +## Notes + +- Be aware that Guid.Parse could throw if the user claim is not a valid GUID; consider Guid.TryParse to avoid runtime exceptions. +- The broadcast channel is normalized by lowercasing and trimming the channel name; this affects how subscribers perceive channel identifiers in updates. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/FilesController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/FilesController.cs.md new file mode 100644 index 0000000..12b3a1c --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/FilesController.cs.md @@ -0,0 +1,23 @@ +# FilesController + +> **File:** `src/EchoHub.Server/Controllers/FilesController.cs` +> **Kind:** class + +```csharp +[ApiController] +[Route("api/files")] +[Authorize] +[EnableRateLimiting("general")] +public class FilesController : ControllerBase +``` + + +Serves an uploaded file anonymously by design: the unguessable GUID in the URL is the access token (Discord-CDN-style capability URL), so attachment links can be opened directly in a browser and shared to IRC clients. E2E-encrypted room blobs are ciphertext at rest, so anonymous access reveals nothing for those channels. + +## Remarks +This symbol provides a minimal, token-based file access surface that does not require user authentication. It delegates path resolution to FileStorageService and consolidates content-type handling in one place, so callers can rely on consistent delivery behavior across file types. The design emphasizes shareable, browser-friendly links while safeguarding sensitive payloads behind the GUID-based URL. + +## Notes +- The endpoint validates the fileId as a GUID before attempting any storage access; invalid IDs yield a BadRequest response. +- Content types are determined by file extension with a broad fallback to application/octet-stream; unknown extensions will download as a generic binary. +- Images and audio files are rendered inline in the browser, while other types are delivered as attachments with the original file name. diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/InvitesController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/InvitesController.cs.md new file mode 100644 index 0000000..979d344 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/InvitesController.cs.md @@ -0,0 +1,23 @@ +# InvitesController + +> **File:** `src/EchoHub.Server/Controllers/InvitesController.cs` +> **Kind:** class + +```csharp +[ApiController] +[Route("api/invites")] +[Authorize] +[EnableRateLimiting("general")] +public class InvitesController : ControllerBase +``` + + +InvitesController provides admin-only endpoints to manage invite codes used for invite-gated registration. It stores and governs the lifecycle of codes within this server's own database, rather than delegating to a central service, and should be used whenever an administrator needs to issue, review, or revoke invites. + +## Remarks +Centralizing invite data in this controller creates a self-contained, auditable lifecycle for invites without relying on external services. It enforces admin ownership of creation, supports expiration and usage limits, and records actions for traceability via logs. By separating persistence (InviteCodes) from presentation (DTOs) and API responses, the design keeps concerns well-scoped and maintainable in this deployment. + +## Notes +- There is a potential race around the MaxActiveInvites check with concurrent create requests; consider transactional safeguards if concurrent admins can issue invites. +- ExpiresInHours is optional; omitting it yields non-expiring invites; the code only applies an expiration when a value is provided. +- Generated codes use a reserved alphabet that excludes ambiguous characters and follow the XXXX-YYYY pattern, aiding readability and reducing mis-typing. diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ModerationController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ModerationController.cs.md new file mode 100644 index 0000000..a139182 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ModerationController.cs.md @@ -0,0 +1,71 @@ +# ModerationController + +> **File:** `src/EchoHub.Server/Controllers/ModerationController.cs` +> **Kind:** class + +*Figure: How ModerationController works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +Start["POST api/moderation/role - AssignRoleRequest"] +GetCaller["Call GetCallerAsync(ServerRole.Admin)"] +CallerError{"GetCaller returned error?"} +ReturnError["Return ErrorResponse and stop"] + +CheckOwnerReq{"request.Role == ServerRole.Owner?"} +BadRequestOwner["Return BadRequest(ErrorResponse: Cannot assign the Owner role.)"] + +FindTarget["Query EchoHubDbContext.Users for request.Username.ToLower()"] +TargetNotFound{"target is null?"} +ReturnNotFound["Return NotFound(ErrorResponse: user not found)"] + +TargetIsOwner{"target.Role == ServerRole.Owner?"} +BadRequestOwner2["Return BadRequest(ErrorResponse: Cannot change the server owner role.)"] + +RoleTooHigh{"request.Role >= caller.Role?"} +BadRequestRole["Return BadRequest(ErrorResponse: Cannot assign a role equal to or above your own.)"] + +ApplyChange["Set previousRole, assign request.Role to target, call EchoHubDbContext.SaveChangesAsync()"] +ReturnOk["Return Ok(message: user is now role)"] + +Start --> GetCaller +GetCaller --> CallerError +CallerError -->|Yes| ReturnError +CallerError -->|No| CheckOwnerReq + +CheckOwnerReq -->|Yes| BadRequestOwner +CheckOwnerReq -->|No| FindTarget + +FindTarget --> TargetNotFound +TargetNotFound -->|Yes| ReturnNotFound +TargetNotFound -->|No| TargetIsOwner + +TargetIsOwner -->|Yes| BadRequestOwner2 +TargetIsOwner -->|No| RoleTooHigh + +RoleTooHigh -->|Yes| BadRequestRole +RoleTooHigh -->|No| ApplyChange + +ApplyChange --> ReturnOk +``` + +```csharp +[ApiController] +[Route("api/moderation")] +[Authorize] +[EnableRateLimiting("general")] +public class ModerationController : ControllerBase +``` + + +Exposes HTTP endpoints under api/moderation for server moderation operations such as assigning roles, kicking users, and banning users. Reach for this controller when implementing administrative or moderation features (web UI, automated moderation tools, or internal scripts) that must enforce role hierarchy, persist changes to the user store, notify connected clients, and clean up presence/connection state. + +## Remarks +This controller centralizes server-side moderation logic and enforces policy at the API boundary: callers must be authenticated and possess the appropriate ServerRole before actions are performed. It coordinates several responsibilities through injected services — persisting role changes via the DbContext, enumerating and notifying affected channels via the PresenceTracker and IChatBroadcaster implementations, forcing connection teardown and cleanup, and recording moderation metrics with ServerStatsCollector. The design keeps authorization and business rules (for example, preventing Owner reassignment and preventing actors from assigning or acting on users with equal or higher roles) inside the controller so callers cannot bypass them. + +## Notes +- Usernames are normalized (lowercased) before lookup; callers should supply usernames case-insensitively. +- Role comparisons rely on the numeric ordering of ServerRole (the controller rejects assigning or acting on roles that are equal to or higher than the caller). +- Methods have observable side effects: database updates, broadcasts to connected clients, forced disconnects and presence cleanup, and server-stat increments — consumers should treat these endpoints as state-changing and potentially long-running operations. +- The controller logs moderation actions (role changes, kicks, etc.); ensure logging and monitoring are configured appropriately for audit purposes. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ServerController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ServerController.cs.md new file mode 100644 index 0000000..9aac17c --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/ServerController.cs.md @@ -0,0 +1,23 @@ +# ServerController + +> **File:** `src/EchoHub.Server/Controllers/ServerController.cs` +> **Kind:** class + +```csharp +[ApiController] +[Route("api/server")] +public class ServerController : ControllerBase +``` + + +ServerController is an ASP.NET Core API controller that exposes the EchoHub server's administrative surface: endpoints to fetch live server statistics, retrieve the configured encryption key (when authorized), and inspect the directory registration state without exposing the claim token itself. Use it when you need operational visibility or admin actions, rather than wiring multiple components yourself. + +## Remarks + +This symbol acts as a unified HTTP boundary for server-wide concerns, coordinating three collaborators: EchoHubDbContext for live data (Users and Channels), IConfiguration for server configuration (name, description, and registration mode), and DirectoryClaimStore for directory registration state. The private GetCallerAsync helper centralizes authentication and role checks, ensuring privileged endpoints (e.g., GetDirectoryStatus) are accessible only to Admins. By composing a ServerStatusDto from runtime metrics and configuration-derived values, the controller provides a lightweight, admin-focused surface without leaking sensitive tokens. + +## Notes + +- GetEncryptionKey returns 503 if Encryption:Key is not configured on the server, signaling that encryption readiness is unavailable. +- GetDirectoryStatus is admin-only; if the caller lacks Admin rights, the endpoint yields an Unauthorized/403 response via GetCallerAsync. +- GetCallerAsync enforces authentication by reading the NameIdentifier claim, loading the user from the database, and validating their ServerRole; failures surface as Unauthorized or 403 with a clear message. diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Controllers/UsersController.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/UsersController.cs.md new file mode 100644 index 0000000..27fcac3 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Controllers/UsersController.cs.md @@ -0,0 +1,60 @@ +# UsersController + +> **File:** `src/EchoHub.Server/Controllers/UsersController.cs` +> **Kind:** class + +*Figure: How UsersController works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +UsersController["UsersController: receives HTTP request"] +UserService["UserService: GetUserProfileAsync(username)"] +ErrorResponse["ErrorResponse: create error response (message)"] +User["User: profile DTO / updated user"] +UpdateProfileRequest["UpdateProfileRequest: request body"] +IUserService["IUserService: UpdateProfileAsync(userId, displayName, bio, nicknameColor)"] +UserOperationResult["UserOperationResult: IsSuccess + User"] +UserError["UserError: domain error result"] +UploadLimits["UploadLimits: MaxAvatarSizeBytes"] + +UsersController -->|"GET {username}/profile"| UserService +UserService -->|"returns null"| ErrorResponse +ErrorResponse -->|"404 NotFound (User not found)"| UsersController +UserService -->|"returns profile"| User +User -->|"200 OK (profile)"| UsersController + +UsersController -->|"PUT /profile with UpdateProfileRequest"| UpdateProfileRequest +UpdateProfileRequest -->|"no userId claim"| ErrorResponse +UpdateProfileRequest -->|"has userId claim -> call UpdateProfileAsync"| IUserService +IUserService -->|"returns UserOperationResult"| UserOperationResult +UserOperationResult -->|"IsSuccess == false"| UserError +UserError -->|"MapUserError -> ErrorResponse"| ErrorResponse +UserOperationResult -->|"IsSuccess == true"| User +User -->|"200 OK (updated user)"| UsersController + +UsersController -->|"POST /avatar"| UsersController +UsersController -->|"no userId claim"| ErrorResponse +UsersController -->|"no form content or files"| ErrorResponse +UsersController -->|"file obtained from Request.Form.Files[0] -> check length"| UploadLimits +UploadLimits -->|"file length > MaxAvatarSizeBytes -> BadRequest"| ErrorResponse +``` + +```csharp +[ApiController] +[Route("api/users")] +[Authorize] +[EnableRateLimiting("general")] +public class UsersController : ControllerBase +``` + + +Handles HTTP endpoints rooted at /api/users for authenticated user operations such as retrieving a user's public profile, updating the caller's profile, and uploading an avatar. The controller delegates business logic to IUserService and ImageToAsciiService, applies rate limiting and upload-size checks, and returns standard DTOs like ErrorResponse and AvatarUploadResponse. + +## Remarks +This controller is the HTTP adapter for user-focused features: it validates requests and authorization, enforces upload and rate limits, converts uploaded images to ASCII art via ImageToAsciiService, and forwards profile and avatar changes to IUserService. It centralizes request-level concerns (model binding, auth, error translation) so the underlying services can remain framework-agnostic. + +## Notes +- UploadAvatar requires a multipart/form POST (Request.HasFormContentType) and will reject requests with no files or files exceeding the configured UploadLimits.MaxAvatarSizeBytes. +- The controller reads the caller's user id from ClaimTypes.NameIdentifier and uses Guid.Parse; if the claim is present but malformed the parse will throw. The implementation assumes authenticated tokens supply a well-formed GUID. +- Take care when extending or changing image validation: FileValidationHelper.IsValidImage is called on the uploaded stream before ImageToAsciiService.ConvertToAscii is invoked. If validation reads the stream to its end without rewinding, the conversion will receive an empty stream — ensure the validation either rewinds the stream or operates on a buffered/copy of the data. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md new file mode 100644 index 0000000..7507766 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md @@ -0,0 +1,11 @@ +# EchoHubDbContext + +> **File:** `src/EchoHub.Server/Data/EchoHubDbContext.cs` +> **Kind:** class + +```csharp +public class EchoHubDbContext : DbContext +``` + + +EchoHubDbContext serves as the EF Core persistence gateway for EchoHub's domain model. It exposes `DbSet`, `DbSet`, `DbSet`, `DbSet`, `DbSet`, `DbSet`, `DbSet`, and `DbSet`, enabling queries and updates against the underlying SQLite store. When not configured by the application host, it configures a file-based SQLite database named echohub.db located under the application base directory, providing a simple local data store for development and testing. In OnModelCreating it enforces domain rules through keys, indices, field length constraints, and relationship mappings (for example, a Channel has many Messages; a Message has many Attachments; ChannelMembership uses a composite key of UserId and ChannelId), ensuring data integrity and cascade behaviors across related entities. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Hubs/ChatHub.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Hubs/ChatHub.cs.md new file mode 100644 index 0000000..e4ea4cb --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Hubs/ChatHub.cs.md @@ -0,0 +1,60 @@ +# ChatHub + +> **File:** `src/EchoHub.Server/Hubs/ChatHub.cs` +> **Kind:** class + +*Figure: How ChatHub works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +User["User connects or calls JoinChannel"] +CH_OnConnected["ChatHub: OnConnectedAsync()"] +IChatServiceConn["IChatService: UserConnectedAsync(Context.ConnectionId, CurrentUserId, CurrentUsername)"] +BaseOnConnected["Call base.OnConnectedAsync()"] +OnConnectedCatch["On exception: Log error and rethrow"] + +CH_Join["ChatHub: JoinChannel(channelName, password)"] +IChatServiceJoin["IChatService: JoinChannelAsync(Context.ConnectionId, CurrentUserId, CurrentUsername, channelName, password)"] +CheckError{"error is not null?"} +ReturnFail["Return JoinChannelResult(false, [], error, passwordRequired)"] +AddGroup["Add connection to SignalR group 'channelName.ToLowerInvariant().Trim()'"] +IChannelServiceNode["IChannelService: GetChannelKeyEnvelopeAsync(channelName)"] +ReturnSuccess["Return JoinChannelResult(true, history, EncryptionSalt, WrappedRoomKey)"] +JoinCatch["On exception: Log error"] +ReturnJoinCatch["Return JoinChannelResult(false, [], 'Failed to join channel: ex.Message')"] + +User --> CH_OnConnected +CH_OnConnected --> IChatServiceConn +IChatServiceConn --> BaseOnConnected +CH_OnConnected -->|"exception"| OnConnectedCatch + +User --> CH_Join +CH_Join --> IChatServiceJoin +IChatServiceJoin --> CheckError +CheckError -->|"yes"| ReturnFail +CheckError -->|"no"| AddGroup +AddGroup --> IChannelServiceNode +IChannelServiceNode --> ReturnSuccess + +CH_Join -->|"exception"| JoinCatch +IChatServiceJoin -->|"exception"| JoinCatch +JoinCatch --> ReturnJoinCatch +``` + +```csharp +[Authorize] +public class ChatHub : Hub +``` + + +A SignalR Hub that exposes real-time chat operations to authenticated clients. ChatHub mediates between connected clients and the server-side chat logic (IChatService) and channel management (IChannelService), handling user connection lifecycle, channel join/leave actions, message sending, and delivery of channel encryption envelopes when applicable. + +## Remarks +ChatHub is an authorization-guarded entrypoint for real-time chat behavior: it uses the caller's claims to identify the user, registers and deregisters connection state with IChatService on connect/disconnect, and forwards channel and message operations to the underlying domain services. It centralizes error logging and converts service-level outcomes into client-facing responses (for example, returning a JoinChannelResult or invoking Error on the caller). The hub also normalizes group names (lowercasing and trimming) and returns channel key envelopes from IChannelService for encrypted rooms so clients can unwrap room keys locally. + +## Notes +- The hub requires authentication claims: CurrentUserId and CurrentUsername read from the connection's ClaimsPrincipal and will throw a HubException if the expected claims are missing. Ensure clients authenticate and include these claims. +- Channel names are normalized via ToLowerInvariant().Trim() before being added to or removed from SignalR groups; callers should expect case-insensitive channel membership. +- When joining encrypted channels the hub obtains an encryption salt and a wrapped room key from IChannelService and returns them to the client so the client can decrypt room keys locally — the server does not hold the raw room key. +- Connection lifecycle failures in OnConnectedAsync/OnDisconnectedAsync are logged and rethrown, while most per-operation failures return structured results or invoke Clients.Caller.Error so callers receive a clear error message without server-side leaks. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Program.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Program.cs.md new file mode 100644 index 0000000..578e5a7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Program.cs.md @@ -0,0 +1,15 @@ +# Program + +> **File:** `src/EchoHub.Server/Program.cs` +> **Kind:** file + + +Bootstraps and hosts the EchoHub.Server application as a resilient, self-hosting startup routine. It is the entrypoint that wires configuration, logging, data access, authentication, and service registrations, then starts the ASP.NET Core web host inside a self-healing loop that restarts on startup failures. + +## Remarks +Program serves as the composition root of EchoHub.Server. It orchestrates essential cross-cutting concerns—initial configuration via FirstRunSetup, bootstrap logging, server-logs integration with Serilog, data access via EF Core SQLite, and authentication via JWT—by registering the relevant services and options early in the host lifecycle. The self-restarting loop provides resilience during startup and deploy-time hiccups, ensuring the server recovers automatically while debugging and monitoring can observe repeated failures. It ties together the server's operational concerns and acts as the single entry point that other components rely upon to start the web application. + +## Notes +- The startup loop restarts the host on failures, enabling resilience but potentially causing rapid churn if issues persist; external monitoring is recommended to detect persistent problems. +- Jwt:Secret must be configured; missing configuration leads to startup failure (an InvalidOperationException is thrown during startup). +- The app uses SQLite by default (echohub.db) located in AppContext.BaseDirectory; ensure filesystem permissions and migrations are properly managed in deployment. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ChannelService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ChannelService.cs.md new file mode 100644 index 0000000..cfd6f1e --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ChannelService.cs.md @@ -0,0 +1,555 @@ +# ChannelService.cs + +> **Source:** `src/EchoHub.Server/Services/ChannelService.cs` + +## Contents + +- [ChannelService](#channelservice) + - [ChannelService (constructor)](#channelservice-constructor) + - [CreateChannelAsync](#createchannelasync) + - [DeleteChannelAsync](#deletechannelasync) + - [EnsureChannelMembershipAsync](#ensurechannelmembershipasync) + - [EnsureDefaultChannelAsync](#ensuredefaultchannelasync) + - [EnsureSystemChannelAsync](#ensuresystemchannelasync) + - [GetChannelByNameAsync](#getchannelbynameasync) + - [GetChannelCryptoAsync](#getchannelcryptoasync) + - [GetChannelListAsync](#getchannellistasync) + - [GetChannelMetaAsync](#getchannelmetaasync) + - [GetChannelsAsync](#getchannelsasync) + - [RekeyChannelAsync](#rekeychannelasync) + - [SetChannelPasswordAsync](#setchannelpasswordasync) + - [UpdateTopicAsync](#updatetopicasync) + - [ValidateChannelPassword](#validatechannelpassword) +- [GetChannelKeyEnvelopeAsync](#getchannelkeyenvelopeasync) +- [GetChannelTopicAsync](#getchanneltopicasync) + +--- + +## ChannelService +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** class + +```csharp +public class ChannelService : IChannelService +``` + + +Manages server-side channel (room) operations: creation, deletion, listing and metadata, membership enforcement, password gating, and end-to-end encryption key envelopes. Reach for ChannelService when you need authoritative server logic that enforces channel rules and persists channel state (including password and E2E envelope handling), rather than making client-side assumptions or manipulating storage directly. + +## Remarks +ChannelService is the central server implementation of IChannelService and enforces policy around channels: who may see or join rooms, how passwords and encryption envelopes are handled, and how the system "log" room is treated differently from ordinary channels. It coordinates presence tracking, spam-throttling (via SpamGuard), and server logging to ensure operations such as channel creation, rekeying, and membership checks are performed consistently and safely. The service preserves the distinction between password-gated channels and end-to-end (E2E) encrypted channels by exposing separate operations for setting/clearing passwords and for rekeying the wrapped room key. + +## Notes +- SetChannelPasswordAsync is not applicable to end-to-end encrypted channels; encrypted rooms change access by rekeying via RekeyChannelAsync so the room key envelope remains consistent. Clearing a password is performed by passing null as the password parameter. +- RekeyChannelAsync is restricted to the channel creator: administrators who do not know the current passphrase cannot rekey a channel on the creator's behalf. +- The system "live log" room is role-gated and its name is reserved even when the feature is disabled; this prevents user-owned channels from accidentally becoming the stream target if the feature is enabled later. +- Channel creation is subject to spam-throttling; moderators and higher roles are exempt from the throttle enforced by SpamGuard. + +--- + +### ChannelService (constructor) +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** constructor + +```csharp +public ChannelService( + IServiceScopeFactory scopeFactory, + PresenceTracker presenceTracker, + SpamGuard spamGuard, + ServerLogsService serverLogs, + ILogger logger) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `scopeFactory` | `IServiceScopeFactory` | — | +| `presenceTracker` | [`PresenceTracker`](PresenceTracker.cs.md) | — | +| `spamGuard` | [`SpamGuard`](SpamGuard.cs.md) | — | +| `serverLogs` | [`ServerLogsService`](ServerLogs/ServerLogsService.cs.md) | — | +| `logger` | `ILogger` | — | + + +Initializes ChannelService by wiring its required collaborators into private fields for later use. The constructor accepts a scope factory, a presence tracker, a spam guard, a server logs service, and a logger, and stores them for use by the instance. In typical applications, the dependency injection container supplies these services, so ChannelService can create short-lived scopes when needed, track user presence, guard against spam, record server-side events, and emit contextual logs. + +## Remarks +By taking dependencies through constructor injection, ChannelService remains loosely coupled and highly testable, since test doubles can be supplied in place of real implementations. This composition root clarifies the service's responsibilities—managing channel state with awareness of presence, applying spam protection, and observability through logs. + +## Notes +- If ChannelService is registered as a singleton, ensure that the injected services are thread-safe or have appropriate lifetimes; otherwise adjust registrations to avoid unsafe sharing. +- If the class creates scopes via the IServiceScopeFactory, dispose them promptly to avoid memory leaks or disposed-service access. +- Verify the DI container can resolve all dependencies at startup; a misconfiguration will surface as a runtime resolution failure. + +--- + +### CreateChannelAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task CreateChannelAsync( + Guid creatorUserId, string name, string? topic, bool isPublic, + string? [REDACTED:CONNECTION_STRING_PASSWORD] string? encryptionSalt = null, string? wrappedRoomKey = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `creatorUserId` | `Guid` | — | +| `name` | `string` | — | +| `topic` | `string?` | — | +| `isPublic` | `bool` | — | +| `encryptionSalt` | `string? [REDACTED:CONNECTION_STRING_PASSWORD] string?` | `null` | +| `wrappedRoomKey` | `string?` | `null` | + +**Returns:** `Task` + + +Creates a new chat channel using the provided parameters, validating the name, enforcing reserved names, optionally handling a password (hashed) and an end-to-end encryption envelope, and persisting the channel with the creator as a member. Use this when you need to create a channel with consistent validation, security, and membership semantics. + +## Remarks +This method centralizes all channel-creation logic, applying business rules such as name normalization (lowercasing and trimming), reserved-name protection for the log room, password requirements for encrypted channels, and spam throttling before persisting data. It leverages a scoped database context to create the channel and automatically adds the creator as a member, ensuring the creator has immediate access. The reserved log room name is enforced regardless of feature toggles, preventing accidental conflicts with system channels. + +## Notes +- The channel name is normalized to lowercase and trimmed, which makes channel uniqueness effectively case-insensitive. +- If an end-to-end envelope is supplied (encryptionSalt and wrappedRoomKey), a password must also be provided; otherwise creation fails with a validation error. +- A race on channel name creation is possible in highly concurrent scenarios; the code checks for existence prior to insert and relies on the database to enforce final uniqueness if necessary. + + +--- + +### DeleteChannelAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task DeleteChannelAsync(Guid callerUserId, string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `callerUserId` | `Guid` | — | +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Deletes a channel by name for a given caller, enforcing that only the channel creator or an administrator can perform the deletion and that protected/default channels cannot be removed. It normalizes the channel name, validates existence and non-system status, removes the channel from the database, saves changes, and returns a ChannelOperationResult containing a ChannelDto with the channel’s identity and metadata; on failure it maps to a corresponding ChannelError with a descriptive message. + +## Remarks +This method encapsulates the channel-deletion policy in a single place, ensuring consistent authorization checks and error signaling across call sites. It delegates data access to EchoHubDbContext via a scoped DI container and returns a ChannelDto representing the deleted channel’s identity and basic attributes, which can be used by clients to refresh UI state or logs. + +## Notes +- The ChannelDto is constructed after the channel row is removed and SaveChangesAsync completes, so the returned DTO serves as a confirmation of what was deleted rather than a live snapshot of a remaining entity. + + +--- + +### EnsureChannelMembershipAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task<(bool Success, string? Error, bool PasswordRequired)> EnsureChannelMembershipAsync( + Guid userId, string channelName, string? [REDACTED:CONNECTION_STRING_PASSWORD] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Success` | `bool` | — | +| `Error` | `string?` | — | +| `PasswordRequired` | `bool` | — | + + +Ensures that a user is granted membership to a named channel, creating or restoring the channel when appropriate, and enforcing access rules including password protection. Call this when a user attempts to join or access a channel so the system can validate eligibility, auto-provision special channels, and persist the membership relationship in the database. The method returns a tuple (Success, Error, PasswordRequired) to indicate whether entry was granted, an error message if any, and whether the caller should prompt for a password. + +## Remarks +Centralizes channel-join semantics within ChannelService, encapsulating rules around default channels, system/log channels, and password gates. It coordinates with the database context, server configuration, and validation utilities to decide whether entry should be granted, a channel recreated, or a password prompt issued. By funneling join logic through a single path, it reduces duplication and ensures consistent behavior across different join entry points (TUI, REST, IRC). + +## Notes +- Automatic channel provisioning: If the requested channel does not exist, the method may recreate the default channel or the log channel and logs a warning. Callers should not assume a static channel list. +- Password gate: For channels with a PasswordHash, a password is required on first-time joins and validated with BCrypt. The method returns PasswordRequired = true in those cases and updates membership only after successful verification. +- Database scope and side effects: The operation creates a short-lived DI scope to access EchoHubDbContext and persists changes (new ChannelMembership, and possibly a newly created Channel). Callers should be mindful of potential race conditions if multiple concurrent joins occur for the same channel. + +--- + +### EnsureDefaultChannelAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +private static async Task EnsureDefaultChannelAsync(EchoHubDbContext db) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `db` | [`EchoHubDbContext`](../Data/EchoHubDbContext.cs.md) | — | + +**Returns:** `Task` + + +Ensures the application has a canonical default channel in the EchoHub database by checking the Channels collection for a channel named HubConstants.DefaultChannel and seeding one if it does not exist. This bootstrapping helper is intended to be invoked during initialization to guarantee a general discussion channel is present without duplicating the initialization logic elsewhere. + +## Remarks +By centralizing the default-channel bootstrapping in EnsureDefaultChannelAsync, callers avoid duplicating the existence check and channel-creation code across startup paths. It ties together the Channel entity, the HubConstants default channel name, and the database context, so changes to the default channel semantics propagate from this single place. The method is private and static, reinforcing that it is an internal bootstrap concern rather than a reusable operation for callers. + +## Notes +- Potential race condition under concurrent invocations: the existence check followed by insertion is not atomic, which could raise a constraint violation if two callers run at the same time. +- CreatedByUserId = Guid.Empty marks system-generated creation; auditing considerations may require handling. + +--- + +### EnsureSystemChannelAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task EnsureSystemChannelAsync(string channelName, string? topic = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `topic` | `string?` | `null` | + +**Returns:** `Task` + + +Ensures there is a system-owned channel with the specified name by normalizing the name and either creating a new system channel or converting an existing non-system channel into a system channel. It then returns a ChannelDto describing the channel’s identity, topic, visibility, and system status. + +## Remarks +Guarantees a canonical system channel identity for internal communications and server content streaming. It encapsulates the create-or-claim logic behind a single API and logs whether a channel was created or claimed. If the target channel already exists and is already marked as system, the method is effectively a no-op and simply returns its ChannelDto. + +## Notes +- There is a potential race condition when two concurrent invocations try to create the same system channel; relying on database constraints or proper isolation is recommended to avoid duplicates. +- If a non-system channel exists with the same name, the code will convert it to a system channel by setting IsSystem = true, IsPublic = false, and clearing PasswordHash; CreatedAt remains the original timestamp. +- The channel name is lower-cased and trimmed before the lookup, so callers should not rely on case-sensitive or whitespace-sensitive channel naming. + +--- + +### GetChannelByNameAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task GetChannelByNameAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +GetChannelByNameAsync fetches a channel by its name after normalizing the input to lowercase and trimming whitespace. It creates a new DI scope to obtain EchoHubDbContext, queries the Channels set for a channel whose Name matches the normalized input, and, if found, counts the number of Messages belonging to that channel. If no matching channel exists, it returns null. The returned ChannelDto includes the channel’s Id, Name, Topic, visibility (IsPublic), the total MessageCount, CreatedAt timestamp, and two boolean flags indicating whether a password hash exists and whether a WrappedRoomKey is present, plus whether the channel is a system channel. This method centralizes the data-shaping of channel metadata for consumers (e.g., channel listings or details) and hides direct EF queries behind a concise API. + +## Remarks +This abstraction centralizes channel metadata retrieval for UI and API surfaces, ensuring consistent ChannelDto shaping and hiding data-access details behind a single, strongly-typed API. It also clarifies that a null return indicates a non-existent channel. + +## Notes +- Returns null when no channel matches the provided name; callers should handle the nullable result. +- Performs two database queries (FirstOrDefaultAsync for the channel, then CountAsync for its messages) when a channel exists; this is straightforward but has a potential perf cost. +- Relies on input normalization to lowercase; if stored channel names are not stored in a comparable form, the lookup could miss matches. + +--- + +### GetChannelCryptoAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task GetChannelCryptoAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Retrieves the ChannelCryptoDto describing the cryptographic state of a channel. The method normalizes the input channel name to lowercase and trims whitespace, then queries the EchoHubDbContext for a Channel with the matching name. If no channel is found, it returns null. If a channel exists, it returns a ChannelCryptoDto where the first value indicates whether a WrappedRoomKey is present (WrappedRoomKey != null) and includes the channel's EncryptionSalt. Data access occurs within a short-lived DI scope created from _scopeFactory, resolving EchoHubDbContext for the lookup. + +--- + +### GetChannelListAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task> GetChannelListAsync() +``` + +**Returns:** `Task>` + + +Fetches and returns a list of channel summaries. The method creates a scoped DI container, reads the EchoHubDbContext, loads all channels ordered by name, and maps each channel to a ChannelListItem that includes the channel's name, topic, the number of online users in that channel (via the presence tracker), whether the channel is public, and whether a password is set. This is typically used to populate a channel directory or lobby UI with up-to-date channel metadata and presence information. + +--- + +### GetChannelMetaAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task GetChannelMetaAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +Fetches channel-level metadata for a given channel name without returning the messages themselves. It normalizes the input by lowercasing and trimming, resolves the channel via a scoped DI context, and if the channel exists returns a ChannelMetaDto containing the channel's Id, normalized Name, Topic, flags indicating whether a WrappedRoomKey or PasswordHash exists, the total MessageCount, the distinct count of Senders, an estimated storage footprint for the channel (attachments plus text), and the channel's CreatedAt timestamp. If no channel matches the provided name, the method returns null. The operation executes within a scoped DI context to ensure proper disposal of the database context. + +--- + +### GetChannelsAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task> GetChannelsAsync(Guid userId, int offset, int limit) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `userId` | `Guid` | — | +| `offset` | `int` | — | +| `limit` | `int` | — | + +**Returns:** `Task>` + + +Fetches a paginated list of channels visible to the specified user, ensuring a default channel exists and applying system-channel visibility rules. It builds a Page of ChannelDto items by filtering channels based on whether they are system channels (only visible if the caller has the appropriate server role) or non-system channels (visible if public or if the user is a member). The method returns a PaginatedResponse containing the channels and the total count, ordered with system channels first and then by name. Per-channel metadata includes the number of messages, creation time, and security flags such as whether a password is set or a wrapped room key is present. + +## Remarks +This method centralizes channel discovery and visibility logic used by API surfaces and the UI. By enforcing system-channel visibility through server-side role checks and by materializing concise per-channel data into ChannelDto, callers receive a consistent, paged view of channels while preserving the default channel guarantee. The use of a scoped DbContext and a two-phase query (total count, then page fetch) encapsulates the data-access concerns behind a single, well-defined operation. + +## Notes +- EnsureDefaultChannelAsync(db) may create the default channel if it is missing; this side effect occurs on every call. callers should be aware of potential writes on read-like operations. +- The total and page fetch are executed as separate queries; data may change between these calls, affecting the reported total and the returned page. +- The channel's Messages.Count is computed in the projection, yielding a per-channel count without loading full message collections. + + +--- + +### RekeyChannelAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task RekeyChannelAsync(Guid callerUserId, string channelName, + string oldPassword, string newPassword, string newEncryptionSalt, string newWrappedRoomKey) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `callerUserId` | `Guid` | — | +| `channelName` | `string` | — | +| `oldPassword` | `string` | — | +| `newPassword` | `string` | — | +| `newEncryptionSalt` | `string` | — | +| `newWrappedRoomKey` | `string` | — | + +**Returns:** `Task` + + +RekeyChannelAsync rotates the passphrase for an end-to-end encrypted channel by swapping the join-gate hash and the wrapped room key, while the actual content key remains unchanged so the history stays readable. The client then re-wraps the content key under the new passphrase-derived key. This operation is restricted to the channel creator; administrators who do not know the current passphrase cannot perform a rekey. + +## Remarks +This method encapsulates a security-sensitive transition that updates credential material without discarding encrypted content. By validating the new passphrase (via ValidateChannelPassword) and requiring non-empty new salt and wrapped key before touching the database, it preserves both confidentiality and integrity. The operation executes in a scoped data context to ensure the channel state is read and persisted atomically, reflecting the latest creator-approved configuration while keeping history intact. + +## Notes +- New password, salt, and wrapped key are validated before any changes are persisted; if validation fails, the operation aborts with a ValidationFailed result. +- Rekeying is restricted to the channel creator; the method enforces this by verifying the caller's user ID and the correctness of the current passphrase before applying changes. + + +--- + +### SetChannelPasswordAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task SetChannelPasswordAsync(Guid callerUserId, string channelName, string? password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `callerUserId` | `Guid` | — | +| `channelName` | `string` | — | +| `password` | `string?` | — | + +**Returns:** `Task` + + +Sets, changes, or clears (null) a channel's join password. This operation is allowed only for the channel's creator or an administrator. End-to-end encrypted channels do not accept password changes here; such channels must use RekeyChannelAsync to rotate the passphrase, preserving the room key envelope. + +## Remarks + +By centralizing password management in this method, the system enforces consistent authorization, validation, and persistence rules for channel passphrases. It guards against modifying system channels and avoids altering encryption state for end-to-end encrypted channels at this layer, delegating that concern to RekeyChannelAsync when appropriate. The method returns a ChannelDto describing the updated channel, including whether a password is set and whether the channel remains end-to-end encrypted. + +## Notes + +- Passwords are stored as BCrypt hashes; if a null password is provided, the password is cleared (PasswordHash becomes null). +- The channel name is normalized to lowercase and trimmed before lookup to ensure stable, case-insensitive matching. +- If the channel does not exist, is a system channel, or the caller lacks sufficient privileges (not the creator or an admin), the operation fails with NotFound, Protected, or Forbidden respectively. +- After a successful change, the returned ChannelDto includes the current message count and flags indicating HasPassword and HasWrappedKey, reflecting the channel's encryption state. + +--- + +### UpdateTopicAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task UpdateTopicAsync( + Guid callerUserId, string channelName, string? topic) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `callerUserId` | `Guid` | — | +| `channelName` | `string` | — | +| `topic` | `string?` | — | + +**Returns:** `Task` + + +Updates the topic of a channel, performing authorization, validation, and persistence in one operation. Given the caller's user ID and the channel name, it normalizes the name, enforces topic length (when provided), ensures only the channel creator can update, persists the topic change, and returns a ChannelOperationResult containing a ChannelDto with the channel's identity, current topic, visibility, message count, creation time, and indicators for password protection and wrapped room key. + +## Remarks +This method centralizes the domain logic for updating a channel topic behind a service boundary. It enforces the business rule that only the channel creator may modify the topic, and it uses a scoped DbContext to apply the change, ensuring consistency with the data-access layer. The returned ChannelDto exposes a compact snapshot of the channel, including whether the channel is password-protected and whether a wrapped room key exists, which informs UI decisions without leaking internal state. + +## Notes +- Topic can be null to clear the current topic (the code stores topic?.Trim()). +- Channel name normalization is applied so lookups are case-insensitive and consistent. +- The operation yields concrete failure codes (NotFound, Forbidden, ValidationFailed) to guide callers in handling user feedback. + +--- + +### ValidateChannelPassword +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +private static string? ValidateChannelPassword(ref string? password) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `password` | `string?` | — | + +**Returns:** `string?` + + +Normalizes and validates a channel password. If the input password is null or consists only of whitespace, it is treated as no password (the value is effectively normalized to null) and no error is produced. For non-empty input, the method enforces length constraints defined by ValidationConstants and returns an error message when the password is too short or too long; otherwise, it returns null to indicate a valid password. The password is passed by reference, allowing the caller to observe and adopt the normalized value in place. + +## Remarks + +Centralizes the channel password policy so all call sites apply the same minimum and maximum length rules and the same interpretation of an empty password. The implementation defers to ValidationConstants for policy values, ensuring changes to password requirements propagate consistently. The use of a ref parameter enables in-place normalization, so the normalized password (or its absence) is visible to the caller without requiring a separate assignment. + +## Notes + +- The caller must pass a mutable variable by ref; passing a constant or read-only expression will not compile. +- The method returns null when the password is valid (or when treated as no password), or a non-null string containing the user-facing validation message when invalid. + +--- + +## GetChannelKeyEnvelopeAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task<(string? EncryptionSalt, string? WrappedRoomKey)> GetChannelKeyEnvelopeAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `EncryptionSalt` | `string?` | — | +| `WrappedRoomKey` | `string?` | — | + + +Gets the encryption envelope for a given channel by name by querying the Channels table via a scoped EchoHubDbContext; it returns the channel's EncryptionSalt and WrappedRoomKey as a tuple, or (null, null) if the channel cannot be found. This method is intended for scenarios where callers need to access per-channel cryptographic parameters to decrypt or initialize channel data, without surfacing the data-access details to higher layers. + +## Remarks +Encapsulates a small, cohesive data-access operation and hides EF Core/DI plumbing from callers. By creating a scoped scope and resolving EchoHubDbContext per call, it avoids leaking a long-lived DbContext into consumer code and makes the envelope retrieval occur in a single boundary. It relies on the Channels table's Name field to identify a channel and returns two optional values, allowing callers to decide how to handle missing encryption data. This placement fits ChannelService as a dedicated place to retrieve channel-related metadata used by encryption/decryption flows. + +## Notes +- Caller must handle possible nulls in both EncryptionSalt and WrappedRoomKey; if the channel isn't found, both will be null. +- Since the input channelName is lowercased before querying, ensure channel.Name storage is consistent (lowercase) to guarantee matches; otherwise, the lookup could miss existing channels. + +--- + +## GetChannelTopicAsync +> **File:** `src/EchoHub.Server/Services/ChannelService.cs` +> **Kind:** method + +```csharp +public async Task<(string? Topic, bool Exists)> GetChannelTopicAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Topic` | `string?` | — | +| `Exists` | `bool` | — | + + +Retrieves the topic for a named channel from the EchoHub database. The method normalizes the input (lowercases and trims), opens a scoped DI context to resolve EchoHubDbContext, and queries the Channels set for a channel with the matching name. If no channel is found, it returns (null, false); otherwise it returns the channel's Topic along with true, indicating the channel exists. The operation is asynchronous, allowing callers to await the database query without blocking. + +## Remarks +This method encapsulates a small, focused data-access concern: turning a channel name into its topic, while also signaling whether the channel exists. Returning a value tuple (Topic, Exists) makes it straightforward for call sites to branch logic without null checks against the channel entity. The DI-scoped DbContext use ensures clean disposal per call and aligns with standard EF Core usage in a DI-driven application. + +## Example +```csharp +var (topic, exists) = await GetChannelTopicAsync("general"); +if (exists) +{ + Console.WriteLine(topic); +} +else +{ + Console.WriteLine("Channel not found."); +} +``` + +## Notes +- The lookup lowercases the channel name; ensure stored channel names are normalized the same way to guarantee matches. +- Topic can still be null even when Exists is true; callers should handle null topics gracefully. +- If multiple channels share the same name (data integrity issue), FirstOrDefaultAsync returns the first match. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ChatService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ChatService.cs.md new file mode 100644 index 0000000..ac6db24 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ChatService.cs.md @@ -0,0 +1,674 @@ +# ChatService.cs + +> **Source:** `src/EchoHub.Server/Services/ChatService.cs` + +## Contents + +- [ChatService](#chatservice) + - [ChatService (constructor)](#chatservice-constructor) + - [BroadcastChannelDeletedAsync](#broadcastchanneldeletedasync) + - [BroadcastChannelUpdatedAsync](#broadcastchannelupdatedasync) + - [BroadcastMessageAsync](#broadcastmessageasync) + - [BroadcastToAllAsync](#broadcasttoallasync) + - [BuildReplyRef](#buildreplyref) + - [FileIdFromUrl](#fileidfromurl) + - [GetChannelHistoryAsync](#getchannelhistoryasync) + - [GetChannelHistoryInternalAsync](#getchannelhistoryinternalasync) + - [GetChannelsForUserAsync](#getchannelsforuserasync) + - [GetOnlineUsersAsync](#getonlineusersasync) + - [LeaveChannelAsync](#leavechannelasync) + - [SendMessageAsync](#sendmessageasync) + - [UpdateStatusAsync](#updatestatusasync) + - [UserConnectedAsync](#userconnectedasync) + - [UserDisconnectedAsync](#userdisconnectedasync) +- [BuildLogBacklog](#buildlogbacklog) +- [JoinChannelAsync](#joinchannelasync) +- [SanitizeNewlines](#sanitizenewlines) + +--- + +## ChatService +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** class + +```csharp +public class ChatService : IChatService +``` + + +Coordinates the server-side chat workflow: presence tracking, channel membership and validation, message handling (decryption, sanitization, spam checks, reply validation, optional link embeds), persistence, and broadcasting to configured IChatBroadcaster implementations. Reach for ChatService when you need the complete, policy-enforced chat behavior used by the hub (connect/disconnect, join/leave, send message, history, status and broadcasts) rather than calling lower-level pieces like the channel store, encryption, or broadcasters individually. + +## Remarks +ChatService is an orchestration façade that centralizes chat policies and cross-cutting concerns so the rest of the system sees a single, consistent chat surface. It delegates channel validation and membership (including password checks) to the channel service, uses PresenceTracker for online lists, defers spam decisions to the SpamGuard, asks LinkEmbedService for embeds, and relies on IMessageEncryptionService for decrypt/encrypt logic. It also records runtime telemetry and logs through ServerStatsCollector and ServerLogsService, and persists or reads backlog data via FileStorageService for special channels (for example, the rolling log room). Finally, it shields broadcasters from internal policies by converting and routing messages appropriately (e.g., encrypted payloads for some clients, plaintext for legacy/IRC broadcasters). + +## Notes +- Join throttle: only first-time joins (where the user is not already a member) count toward the join throttle to avoid falsely flagging reconnect/auto-join bursts. +- Live log room is treated as read-only; attempts to write to it are rejected early and its backlog is sourced from a rolling log file — only the first history page returns a backlog. +- SpamGuard operates on the stored content (ciphertext when end-to-end encryption is used) and never requires or performs decryption; muting and escalation are handled through the service's moderation workflow. + +--- + +### ChatService (constructor) +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** constructor + +```csharp +public ChatService( + IServiceScopeFactory scopeFactory, + PresenceTracker presenceTracker, + IEnumerable broadcasters, + LinkEmbedService embedService, + IMessageEncryptionService encryption, + IChannelService channelService, + FileStorageService fileStorage, + SpamGuard spamGuard, + ServerLogsService serverLogs, + ServerStatsCollector statsCollector, + ILogger logger) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `scopeFactory` | `IServiceScopeFactory` | — | +| `presenceTracker` | [`PresenceTracker`](PresenceTracker.cs.md) | — | +| `broadcasters` | `IEnumerable` | — | +| `embedService` | [`LinkEmbedService`](LinkEmbedService.cs.md) | — | +| `encryption` | [`IMessageEncryptionService`](../../EchoHub.Core/Contracts/IMessageEncryptionService.cs.md) | — | +| `channelService` | [`IChannelService`](../../EchoHub.Core/Contracts/IChannelService.cs.md) | — | +| `fileStorage` | [`FileStorageService`](FileStorageService.cs.md) | — | +| `spamGuard` | [`SpamGuard`](SpamGuard.cs.md) | — | +| `serverLogs` | [`ServerLogsService`](ServerLogs/ServerLogsService.cs.md) | — | +| `statsCollector` | [`ServerStatsCollector`](Stats/ServerStatsCollector.cs.md) | — | +| `logger` | `ILogger` | — | + + +Constructs a ChatService by injecting its required collaborators and wiring them to private fields. This constructor is invoked by the dependency injection container when a ChatService is created, supplying services for scope management, presence tracking, message broadcasting, content embedding, encryption, channel operations, file storage, spam protection, server logging, and statistics collection. The use of `IEnumerable` indicates that multiple broadcasters can participate in delivering messages and events, allowing pluggable delivery strategies without changing ChatService code. + +## Remarks +ChatService acts as an orchestration hub for chat functionality. By depending on interfaces rather than concrete implementations, it remains highly testable and extensible: you can substitute mocks or fakes for broadcasters, presence tracking, or encryption in tests or different environments. The broadcaster collection enables evolving notification strategies by simply registering new IChatBroadcaster implementations, aligning with the open/closed principle. + +## Notes +- No null-checks are performed in the constructor; rely on the DI container to provide non-null dependencies. If ChatService might be created outside the DI pipeline, consider adding guards. +- When using `IEnumerable`, all registered broadcasters will be resolved and invoked; behavior depends on the concrete broadcaster implementations. + +--- + +### BroadcastChannelDeletedAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public Task BroadcastChannelDeletedAsync(string channelName) + => BroadcastToAllAsync(b => b.SendChannelDeletedAsync(channelName)) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task` + + +BroadcastChannelDeletedAsync publishes a channel-deletion event to all connected clients by delegating to the shared broadcasting pipeline. It forwards the channelName to each subscriber through SendChannelDeletedAsync, coordinated by BroadcastToAllAsync to ensure every participant receives the notification. + +## Remarks +Provides a domain-friendly API that hides the broadcasting details behind a simple, expressive method name. By delegating to BroadcastToAllAsync, it centralizes how channel-deletion notifications are distributed, reducing duplication and ensuring consistent behavior across all subscribers. + +## Notes +- No input validation is performed on channelName; callers should ensure the value is non-null and meaningful before invocation. +- Exceptions raised during per-subscriber delivery will propagate via the returned Task; callers should decide whether to await and handle failures. + +--- + +### BroadcastChannelUpdatedAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public Task BroadcastChannelUpdatedAsync(ChannelDto channel, string? channelName = null) + => BroadcastToAllAsync(b => b.SendChannelUpdatedAsync(channel, channelName)) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channel` | [`ChannelDto`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | +| `channelName` | `string?` | `null` | + +**Returns:** `Task` + + +BroadcastChannelUpdatedAsync is a thin wrapper that notifies all connected clients that the specified channel has been updated. It accepts the ChannelDto describing the channel and an optional new channelName. The method delegates to the shared broadcast mechanism (BroadcastToAllAsync) by applying a function that calls SendChannelUpdatedAsync on each client with the provided payload. Use this when you want real-time client UIs to reflect changes to a channel, such as a rename or updated metadata, without having to push updates individually to each client. + +## Remarks +BroadcastChannelUpdatedAsync centralizes the channel-update notification path in ChatService. By encapsulating the broadcast call behind this single method, callers don't need to know about how clients are iterated or how the payload is delivered; tests can mock this entry point, and future changes to the broadcasting strategy stay confined here. + +## Notes +- This method only notifies clients; it does not modify the channel data in storage. +- If channelName is non-null, it will be included as part of the payload and may be used by clients to display the new name. + +--- + +### BroadcastMessageAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public Task BroadcastMessageAsync(string channelName, MessageDto message) + => BroadcastToAllAsync(b => b.SendMessageToChannelAsync(channelName, message)) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `message` | [`MessageDto`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) | — | + +**Returns:** `Task` + + +BroadcastMessageAsync asynchronously broadcasts the provided MessageDto to all clients subscribed to the specified channel by delegating to BroadcastToAllAsync. This method serves as a focused helper for channel-scoped messages, insulating callers from the details of iterating over recipients and invoking SendMessageToChannelAsync on each. + +## Remarks +This wrapper consolidates the channel-based dispatch pattern into a single, discoverable API on the chat service. It centralizes the broadcasting contract so callers do not need to know how broadcasting is implemented (per-subscriber dispatch vs. transport specifics), and it supports testing and mocking of channel messages by providing a stable entry point. + +## Notes +- The visible code does not show input validation; consider validating channelName and message upstream to avoid potential ArgumentNullException during broadcasting. +- The method returns a Task; await it to observe completion and to surface any exceptions from the underlying broadcast pipeline (e.g., failures in SendMessageToChannelAsync). + +--- + +### BroadcastToAllAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private async Task BroadcastToAllAsync(Func action) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `action` | `Func` | — | + +**Returns:** `Task` + + +BroadcastToAllAsync is a private helper that sequentially applies an asynchronous action to every broadcaster in the _broadcasters collection. By awaiting the provided `Func` for each broadcaster, it ensures ordered, per-broadcaster execution. If an individual broadcaster throws, the exception is caught and logged with the broadcaster’s runtime type name, allowing the remaining broadcasters to continue without interrupting the overall broadcast flow. + +## Remarks +This helper centralizes the common pattern of broadcasting to multiple chat broadcasters while isolating failures. It provides a small orchestration layer that coordinates across the _broadcasters collection and ensures one faulty broadcaster does not derail the entire operation. Because it is private, this logic remains an implementation detail of the class rather than part of its public API. + +## Notes +- The method is sequential; broadcasting happens one broadcaster after another, not in parallel. If you need parallel broadcasting, use a different approach. +- Exceptions from action are swallowed per-broadcaster; if you need different error handling, handle it inside the action or upstream. +- Logging uses broadcaster.GetType().Name to identify failures; if multiple broadcasters share a type, the log may not distinguish instances. + +--- + +### BuildReplyRef +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private ReplyRefDto BuildReplyRef(Message target) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `target` | [`Message`](../../EchoHub.Core/Models/Message.cs.md) | — | + +**Returns:** [`ReplyRefDto`](../../EchoHub.Core/DTOs/ChatDtos.cs.md) + + +BuildReplyRef constructs the wire reference for a reply target by decrypting the target’s content to obtain a plaintext snippet, conditionally truncating it, and then re-encrypting the result into a ReplyRefDto that carries the target’s ID, sender, and the encrypted snippet. Specifically, it decrypts target.Content; if the decrypted text is not recognized as E2E room ciphertext and exceeds 120 characters, it truncates to 120 characters and appends an ellipsis; finally, it encrypts the possibly shortened plaintext and returns a ReplyRefDto. + +## Remarks +Encapsulates the logic for producing a secure, compact teaser of the original message for a reply. It ensures that non-E2E content is truncated to a sane length while guaranteeing that E2E content remains intact (and thus decryptable) by avoiding truncation. It delegates the actual encryption to the central _encryption service and uses RoomCrypto.IsRoomCiphertext to decide when truncation is safe. + +## Notes +- Truncation only occurs when the decrypted content does not look like room ciphertext; this prevents corrupting E2E data. +- The returned snippet is encrypted before being included in ReplyRefDto. +- The 120-character limit is a fixed server-side threshold governing the preview length. + +--- + +### FileIdFromUrl +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private static string FileIdFromUrl(string url) => url.Split('/')[^1] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `url` | `string` | — | + +**Returns:** `string` + + +Extracts the storage file id from an attachment URL by taking the last path segment after the final '/'. It is intended for URLs that look like '/api/files/{id}' and is used in scenarios where the code needs to derive the identifier from a URL without performing a full URL parser. + +## Remarks +Because this helper relies on a simple string.Split and the C# index-from-end operator [^1], it assumes the input is a plain path that ends with the id and does not end with a trailing slash. If the URL ends with '/', the result will be an empty string. It also does not guard against null inputs, which would raise an exception at runtime. In practice this method is a tiny, in-class utility that centralizes the id extraction so callers don't duplicate the split logic. + +## Notes +- Trailing slash in the URL yields an empty id; normalize the URL or trim the trailing slash before calling. +- Null or empty input is not handled; ensure a non-null, non-empty URL is passed. + +--- + +### GetChannelHistoryAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task> GetChannelHistoryAsync(string channelName, int count, int offset = 0) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | +| `count` | `int` | — | +| `offset` | `int` | `0` | + +**Returns:** `Task>` + + +GetChannelHistoryAsync retrieves a paged history of messages for a given channel. It normalizes the channel name to lowercase and trims it, clamps the requested count to the range [1, ValidationConstants.MaxHistoryCount], and ensures offset is non-negative. If the channel is a logs channel (no DB messages), the backlog is read from the rolling log file: the first page is populated via BuildLogBacklog, while older pages are empty (files are archives). For regular channels, a short-lived DI scope is created to resolve EchoHubDbContext, and the method delegates to GetChannelHistoryInternalAsync to fetch the requested slice from the database. The call is asynchronous and returns a `List`. + +## Remarks +Serves as a unified history retrieval entry point that abstracts away the storage details behind a paging API. It centralizes channel-history concerns so callers don't need to know whether messages come from the rolling log or the database, while preserving the expected paging semantics across both sources. + +## Notes +- Be aware that for log channels, only the first page contains backlog data; requesting subsequent pages returns an empty list. + +--- + +### GetChannelHistoryInternalAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private async Task> GetChannelHistoryInternalAsync(EchoHubDbContext db, string channelName, int count, int offset = 0) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `db` | [`EchoHubDbContext`](../Data/EchoHubDbContext.cs.md) | — | +| `channelName` | `string` | — | +| `count` | `int` | — | +| `offset` | `int` | `0` | + +**Returns:** `Task>` + + +Retrieves a page of messages for a named channel, enriching each entry with sender metadata, attachment data, and embed information, so the client can render a historical view of the chat. Call this when you need to assemble a channel's message history in a transport-ready form, with tombstoned accounts preserved and content decrypted for display. + +## Remarks +Conceptually, this method centralizes history construction: it loads messages for a channel, preserves messages from deleted accounts by left-joining with users, collects reply targets for quote rendering, and hydrates attachments while pruning entries that no longer have valid files. It decrypts message content and any embed metadata, reconstructs attachments for transport (including per-attachment previews that are re-encrypted), and translates raw data into the client-facing DTOs (MessageDto, AttachmentDto, EmbedDto). This batching approach minimizes round-trips by prefetching related data (replies, attachments, embeds) in a single operation. + +## Notes +- If a channel is not found, the method returns an empty list rather than throwing. Callers should handle an empty history gracefully. +- Messages associated with deleted users are preserved in history, but their display name and nickname color may be null; UI code should account for missing metadata. +- Attachments are shown only if their underlying files still exist on disk; messages with only vanished attachments and no plaintext content are pruned from the result. +- The method decrypts content and embed JSON, and it re-encrypts payloads for transport; the exact transport-encryption details are handled deeper in the pipeline and may depend on the caller's context. + +--- + +### GetChannelsForUserAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public Task> GetChannelsForUserAsync(string username) + => Task.FromResult(_presenceTracker.GetChannelsForUser(username)) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `username` | `string` | — | + +**Returns:** `Task>` + + +Retrieves the list of channel names that a specific user participates in, exposed as an asynchronous method. It delegates to the presence tracker via _presenceTracker.GetChannelsForUser(username) and wraps the result in Task.FromResult, which means the call completes synchronously and simply presents an async surface to callers. Use this when you require an async API surface (e.g., to be consistent with other async members) even though the underlying operation is synchronous. + +## Remarks + +It provides an asynchronous API surface for retrieving a user's channel list by delegating to the presence tracker. This keeps ChatService methods consistent in an async context and avoids exposing a synchronous API directly to callers that expect Task-returning methods. The actual retrieval is synchronous, so this wrapper does not introduce true asynchrony. + +## Notes + +- Completes synchronously; no actual I/O is awaited here. +- Any exception from _presenceTracker.GetChannelsForUser will be thrown at call time (not surfaced as a faulted Task). +- If you anticipate long blocking work, prefer an actual asynchronous implementation or an asynchronous presence tracker. + +--- + +### GetOnlineUsersAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task> GetOnlineUsersAsync(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `Task>` + + +Retrieves the list of online users for a given chat channel by joining the in-memory presence tracker with the database-stored user records. It normalizes the channel name to lowercase and trims whitespace, fetches the set of online usernames from the tracker, queries EchoHubDbContext.Users for those usernames that are not Invisible, and then maps each user to a UserPresenceDto that includes the in-memory IRC-only flag. This method is typically used when you need to present the current participants of a channel, excluding hidden users, with their display metadata. + +## Remarks +Acts as a bridge between transient presence state and the persistent user store, ensuring that the live list respects visibility rules while enriching with profile data. The conversion to UserPresenceDto happens after the EF query to allow the IRC-only flag to be derived from the presence tracker, not stored in the database. The use of a scoped DbContext keeps the data access isolated and safe for concurrent calls. + +## Example +```csharp +// Example usage +var online = await chatService.GetOnlineUsersAsync("general"); +Console.WriteLine($"Online in #general: {online.Count}"); +``` + +## Notes +- If a username is online according to the tracker but missing from the database, it will be ignored. +- Channel name normalization means calls with different casing or surrounding whitespace map to the same channel. +- The IsIrcOnly flag is determined by the presence tracker and is included in each UserPresenceDto. + +--- + +### LeaveChannelAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task LeaveChannelAsync(string connectionId, string username, string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connectionId` | `string` | — | +| `username` | `string` | — | +| `channelName` | `string` | — | + +**Returns:** `Task` + + +LeaveChannelAsync handles the workflow for when a user leaves a chat channel. It normalizes the channel name to lowercase, updates the presence tracker to reflect that the user has left, broadcasts a user-left notification to all connected clients in that channel, and logs the action at the debug level. + +Developers call this when a user intentionally exits a channel; the method encapsulates the coordinated state change, notification, and observability so callers don't have to orchestrate these steps separately. + +## Remarks + +It centralizes the leave workflow into a single, reusable operation that updates presence, notifies clients, and records the event for debugging. Normalizing the channel name here prevents case-sensitivity inconsistencies when tracking presence or delivering notifications. Notification is performed asynchronously by the broadcasting layer, which preserves responsiveness and allows the caller to await completion. + +## Example + +```csharp +// Most common usage: user "alice" leaves the "General" channel +await chatService.LeaveChannelAsync("conn-123", "alice", "General"); +``` + +## Notes + +- ToLowerInvariant is called on channelName without a null-check; passing null will throw. Ensure channelName is non-null before calling, or upstream validation. +- The connectionId parameter is unused in this implementation; it may be present for correlation or future use. +- Exceptions from _presenceTracker.LeaveChannel or BroadcastToAllAsync propagate to the caller; no internal retry is performed. + +--- + +### SendMessageAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task SendMessageAsync(Guid userId, string username, string channelName, string content, string? originConnectionId = null, Guid? replyToMessageId = null) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `userId` | `Guid` | — | +| `username` | `string` | — | +| `channelName` | `string` | — | +| `content` | `string` | — | +| `originConnectionId` | `string?` | `null` | +| `replyToMessageId` | `Guid?` | `null` | + +**Returns:** `Task` + + +SendMessageAsync coordinates the end-to-end process of posting a chat message to a named channel. It normalizes the channel name, validates it against allowed patterns, blocks writes to read-only channels (including the logs room and system channels), decrypts incoming content, strips a literal encryption prefix if present to prevent spoofing, and enforces non-empty content and a maximum length. It then looks up the target channel and the sender from the database, enforces mute state (including automatic unmute when a mute has expired), runs a spam guard that can auto-mute or reject messages, validates an optional reply target, and resolves link embeds before persisting the message. The method returns a user-facing string on error or when action is blocked, and returns null on a successful send; side effects include database updates, saving changes, and a moderation log entry when auto-muting occurs. + +## Remarks +The method centralizes chat message submission, ensuring consistent enforcement of security, moderation, and content rules across all channels. It encapsulates cross-cutting concerns (validation, decryption, sanitization, moderation, and embed resolution) behind a single entry point, reducing duplication and potential inconsistencies in callers. By using a scoped DbContext and explicit read-only checks, it mitigates the risk of unintended writes and keeps transactional boundaries clear. The combination of encryption-aware processing, a programmable spam guard, and read-only channel protection reveals a deliberate design to balance user privacy, abuse prevention, and system integrity. + +## Notes +- The method mutates and persists mute state (sender.IsMuted/MutedUntil) in response to spam protection or mute expiry. +- Returning strings for error/status means callers must handle UI messaging; on success it returns null. +- Be aware of early returns for read-only channels and non-existent channels; ensure the consumer handles user feedback. + +--- + +### UpdateStatusAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task UpdateStatusAsync(Guid userId, string username, UserStatus status, string? statusMessage) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `userId` | `Guid` | — | +| `username` | `string` | — | +| `status` | [`UserStatus`](../../EchoHub.Core/Models/UserStatus.cs.md) | — | +| `statusMessage` | `string?` | — | + +**Returns:** `Task` + + +Updates a user's presence status for the specified userId and username, performing validation, persisting changes to the database, and broadcasting the new presence to connected clients. When the input is invalid or the user cannot be found, it returns a user-facing error string; on success it returns null. + +## Remarks +The method creates a short-lived DI scope to obtain EchoHubDbContext, updates the user entity (Status, StatusMessage trimmed, and LastSeenAt set to UTC now), and saves changes. It then builds a UserPresenceDto and uses the presence tracker to determine the target channels, broadcasting the updated presence to all relevant clients via BroadcastToAllAsync. The return value encodes success (null) or failure (a user-facing string) without throwing exceptions. + +## Notes +- If a value outside the defined UserStatus enum is supplied, the method immediately returns "Invalid status. Use online, away, dnd, or invisible." due to the enum validation check. +- The status message is length-validated against ValidationConstants.MaxStatusMessageLength and is trimmed before storage; overly long messages produce a descriptive error. + + +--- + +### UserConnectedAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task UserConnectedAsync(string connectionId, Guid userId, string username) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connectionId` | `string` | — | +| `userId` | `Guid` | — | +| `username` | `string` | — | + +**Returns:** `Task` + + +Upon a client connection, this method coordinates in-memory presence tracking, connection-count telemetry, and optional persistence of the user's online state. It updates the in-memory presence tracker and stats collector with the new connection, then resolves a scoped EchoHubDbContext to locate the user by userId. If the user exists, it updates LastSeenAt to the current UTC time and sets Status to Online, persisting the change via SaveChangesAsync. A debug-level log records the connection event for troubleshooting. The inline comment notes that churn aggregation is performed in the periodic stats report rather than in this hot path. + +## Remarks + +This method glues together presence, persistence, and telemetry for a user connection. It relies on a scoped DbContext to keep database changes isolated per connection, avoiding long-lived contexts and potential contention. By updating both the in-memory trackers and the persisted user state when a user connects, it helps ensure a consistent view of online users across in-memory data and storage, while gracefully handling the case where a user record may be absent. + +## Notes + +- If the user record cannot be found in EchoHubDbContext.Users, no database write occurs; the method still updates presence and stats. +- The LastSeenAt timestamp uses DateTimeOffset.UtcNow to avoid timezone inconsistencies across servers. + + +--- + +### UserDisconnectedAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task UserDisconnectedAsync(string connectionId) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connectionId` | `string` | — | + +**Returns:** `Task` + + +Handles the disconnection lifecycle for a user in the chat service. Given a connectionId, it resolves the associated username, collects the channels the user was in, updates presence statistics, and if the user is no longer online, persists LastSeenAt and marks the user as Invisible in the database. It also constructs a UserPresenceDto and broadcasts a status-change to the user's previously tracked channels. The method returns the username that disconnected (or null if no user could be resolved from the connectionId). + +## Remarks + +By isolating persistence and presence updates behind a scoped database context, this method coordinates ephemeral connection state with durable user data. It serves as the boundary between connection lifecycle management and user presence broadcasting, ensuring that changes are persisted and that clients are notified consistently. The pattern of resolving the user from the connection, updating LastSeenAt and Visibility, and broadcasting a UserPresenceDto helps keep the client UIs in sync with accurate user status. + +## Notes + +- If the connectionId cannot be mapped to a username, the method still records the disconnection count via the stats collector, but skips the database update and user-broadcast. +- LastSeenAt is updated to DateTimeOffset.UtcNow and Status is set to Invisible only when a valid username is found and the user is no longer online. +- A scoped EchoHubDbContext is used to persist changes; the DbContext instance is disposed as part of the scope lifecycle. The broadcast is sent to the channels the user was connected to before disconnect; if there were no such channels, there is no targeted broadcast. + +--- + +## BuildLogBacklog +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private List BuildLogBacklog(string channelName) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `channelName` | `string` | — | + +**Returns:** `List` + + +Turns the log-file backlog into transport-encrypted MessageDto objects so clients render past log lines exactly like streamed ones. It reads the backlog via the server logs store, encrypts each backlog entry’s content with the encryption service, and wraps it in a new MessageDto using a freshly generated GUID, the SenderName from ServerLogsService, the provided channelName, and the backlog entry’s timestamp. This method never touches the database and serves solely as a transform to replay historical log lines in the same MessageDto format as live messages. + +## Remarks +Acts as a translator between persisted log backlog and the live message stream. By centralizing encryption and formatting, it ensures backlog replay matches live streams and isolates storage concerns from presentation. The use of a new GUID per backlog item also avoids depending on database identifiers for UI rendering. + +## Notes +- The MessageDto payload sent for backlog entries is encrypted; clients must decrypt to display the original content. +- IDs for backlog items are generated per call (Guid.NewGuid) and are not tied to persisted database IDs. + +--- + +## JoinChannelAsync +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +public async Task<(List History, string? Error, bool PasswordRequired)> JoinChannelAsync( + string connectionId, Guid userId, string username, string channelName, string? [REDACTED:CONNECTION_STRING_PASSWORD] +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `History` | `List` | — | +| `Error` | `string?` | — | +| `PasswordRequired` | `bool` | — | + + +Joins a user to a chat channel, performing gating, membership validation, presence tracking, and history retrieval. It first enforces a join throttle via a spam guard, then delegates the channel membership check (including any password gate) to ChannelService. If the gate fails, it returns an empty history with the reason. On a successful gate, it records the join in the presence tracker, fetches a lightweight presence snapshot for broadcasting, broadcasts the join to all connected clients (except when the user is invisible), and finally returns the channel history along with an indication that no error occurred and that no password is required. + +## Remarks +This method encapsulates the end-to-end join workflow in a single, reusable operation, ensuring consistent enforcement of anti-spam, permission, and presence semantics across the chat surface. By obtaining presence information in a scoped, guarded manner, it keeps side effects localized to the join flow while enabling clients to incrementally update their views. The implementation gracefully handles failures when fetching presence data (logging at debug level) without interrupting the primary join path, and it respects user visibility by avoiding broadcasts for invisible users. + +## Example +```csharp +// Example usage: a user joining a publicly accessible channel without a password +var (history, error, passwordRequired) = await chatService.JoinChannelAsync( + connectionId: "conn-123", + userId: userId, + username: "Alice", + channelName: "general", + password: null); +``` + +## Notes +- If the spam guard rejects the join, the method returns immediately with an empty history and a non-null error reason; no membership or presence side effects occur. +- Invisible users will not trigger a broadcast of the join to other clients, though their history is still returned to them. +- Presence data is a best-effort fetch; failures are logged at debug level and do not prevent the join from completing or the history from being returned. + +--- + +## SanitizeNewlines +> **File:** `src/EchoHub.Server/Services/ChatService.cs` +> **Kind:** method + +```csharp +private static string SanitizeNewlines(string content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `content` | `string` | — | + +**Returns:** `string` + + +SanitizeNewlines normalizes line endings to a single newline form, collapses consecutive blank lines to at most HubConstants.MaxConsecutiveNewlines, and truncates the total line count to HubConstants.MaxMessageNewlines. This private helper should be invoked when preparing user-provided content for transmission so that messages stay readable and within size limits, rather than letting users push uncontrolled newline spam through the chat pipeline. + +## Remarks + +SanitizeNewlines centralizes newline handling to ensure consistent formatting across the chat pipeline. It is driven by HubConstants thresholds, avoiding hard-coded limits and enabling consistent behavior wherever message sanitization occurs. As a pure transformation of the input with no external state, it has no side effects beyond returning a sanitized string. + +## Notes + +- Collapses consecutive whitespace-only lines, which can alter intended spacing in user messages. +- Truncates lines beyond MaxMessageNewlines, so content beyond the limit is dropped from the end. +- The function is private and intended for internal use within the ChatService; external callers cannot rely on it. + + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md new file mode 100644 index 0000000..8b4cf14 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/DirectoryClaimStore.cs.md @@ -0,0 +1,90 @@ +# DirectoryClaimStore.cs + +> **Source:** `src/EchoHub.Server/Services/DirectoryClaimStore.cs` + +## Contents + +- [DirectoryClaimStore](#directoryclaimstore) +- [RegistrationStatus](#registrationstatus) + +--- + +## DirectoryClaimStore +> **File:** `src/EchoHub.Server/Services/DirectoryClaimStore.cs` +> **Kind:** class + +```csharp +public sealed class DirectoryClaimStore +``` + + +Persists the directory claim token (an opaque secret issued on first registration) together with the server's stable ServerId, and exposes a short-lived RegistrationStatus used by operator-facing endpoints. Use this type when you need a simple on-disk, atomic store for the initial claim token and ServerId and also want to surface the most recent registration outcome (success or failure) for diagnostics or UI. + +## Remarks +This class centralises two responsibilities: durable storage of the claim token + ServerId and an in-memory, ephemeral view of registration status. The file write uses an atomic temporary-write-then-rename strategy (so partial writes are avoided) and callers should treat the stored contents as a secret. Concurrency is handled with a SemaphoreSlim for writes and Volatile reads/writes for the in-memory references: SaveClaimAsync and UpdateServerIdAsync serialize on-disk updates while ClaimToken, ServerId and Status are safe to read without taking the write lock. + +## Example +```csharp +// resolve IConfiguration and ILogger from your DI container +var store = new DirectoryClaimStore(configuration, logger); + +// Persist the one-time claim token and server id (called once when first claimed) +await store.SaveClaimAsync(claimToken, serverId); + +// Read back the persisted values later +var token = store.ClaimToken; // may be null until saved +var id = store.ServerId; // may be null until saved + +// Update only the ServerId when re-registering with the same token +await store.UpdateServerIdAsync(newServerId); + +// Report ephemeral registration outcomes for operator UI +store.SetSuccess(serverId); +// or on failure: +store.SetFailure("ConflictError", new[] { "host-a", "host-b" }); + +// Inspect the last registration status +var status = store.Status; +``` + +## Notes +- The on-disk file is treated as a secret; protect filesystem permissions and backups accordingly. +- Status is ephemeral and kept only in memory; SetSuccess/SetFailure do not persist to disk. +- SaveClaimAsync is intended to be called once per row's lifetime (first claim). UpdateServerIdAsync is a no-op when the ServerId is unchanged. +- ClaimToken and ServerId properties may be null until a persisted value is loaded or saved. + +--- + +## RegistrationStatus +> **File:** `src/EchoHub.Server/Services/DirectoryClaimStore.cs` +> **Kind:** record + +```csharp +public sealed record RegistrationStatus( + bool IsRegistered, + Guid? ServerId, + DateTimeOffset? LastRegisteredAt, + string? LastError, + string[]? ConflictingHosts) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `IsRegistered` | `bool` | — | +| `ServerId` | `Guid?` | — | +| `LastRegisteredAt` | `DateTimeOffset?` | — | +| `LastError` | `string?` | — | +| `ConflictingHosts` | `string[]?` | — | + + +RegistrationStatus is a small, immutable data container that captures the outcome of attempting to register a directory claim in the EchoHub server. It indicates whether the registration succeeded and optionally conveys the server identity, timestamp, error details, and any conflicting hosts so higher-level logic can react accordingly. + +## Remarks +RegistrationStatus models a single, transportable result from a registration process. As a record, it benefits from value-based equality, making it easy to compare results across layers or to cache and reuse them. The nullable fields reflect real-world outcomes: a registration attempt may not yield a ServerId or LastRegisteredAt, and LastError plus ConflictingHosts carry additional context when registration fails or is disputed. This abstraction isolates the surface area of registration outcomes from the rest of the directory claim store, enabling consistent handling without sprinkling primitive flags throughout the codebase. + +## Notes +- Nullable fields indicate optional context; always guard before accessing ServerId, LastRegisteredAt, LastError, and ConflictingHosts to avoid NullReferenceException. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/FileCleanupService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/FileCleanupService.cs.md new file mode 100644 index 0000000..5bf09fb --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/FileCleanupService.cs.md @@ -0,0 +1,18 @@ +# FileCleanupService + +> **File:** `src/EchoHub.Server/Services/FileCleanupService.cs` +> **Kind:** class + +```csharp +public sealed class FileCleanupService : BackgroundService +``` + + +FileCleanupService is a hosted background service that periodically deletes files in a configured storage directory that are older than a configured retention period. It reads settings from configuration, chooses the target path, and logs progress while running until cancellation. + +## Remarks +The cleanup logic is encapsulated in a dedicated BackgroundService to centralize disk-space hygiene and keep it decoupled from request-driven code. It relies on dependency-injected IConfiguration and ILogger to determine interval, retention, and storage path, and to report status and errors. Cleanup runs in a cancellation-friendly loop and uses UTC timestamps to compare age, making behavior predictable across servers. + +## Notes +- It only considers files directly within storagePath; subdirectories are not scanned. If you need recursive cleanup, switch to Directory.GetFiles(storagePath, "*", SearchOption.AllDirectories) and adjust the cutoff logic accordingly. +- File age is determined by GetCreationTimeUtc; if your deployment uses different semantics (e.g., files moved or uploaded), consider using GetLastWriteTimeUtc or metadata-based age checks. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/FileStorageService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/FileStorageService.cs.md new file mode 100644 index 0000000..93f32b9 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/FileStorageService.cs.md @@ -0,0 +1,21 @@ +# FileStorageService + +> **File:** `src/EchoHub.Server/Services/FileStorageService.cs` +> **Kind:** class + +```csharp +public class FileStorageService +``` + + +FileStorageService persists uploaded data to a local disk storage location, creating the directory if it does not exist and selecting the path from configuration (Storage:Path) or defaulting to an uploads folder beside the application. Each saved file is assigned a GUID-based fileId and stored with its original extension; the API supports SaveFileAsync, GetFilePath, GetStoredFileIds, and DeleteFile for common lifecycle operations. + +## Remarks + +By centralizing disk interactions, this service hides filesystem details from callers and provides a single, testable abstraction for storing attachments. It guarantees the storage directory exists and maps between a stable fileId and the corresponding on-disk file (preserving the extension). The GetStoredFileIds method performs a single directory scan to facilitate bulk checks across many files without per-file I/O. + +## Notes + +- The storage path is captured at construction time; changes to configuration after construction won't affect this instance. +- No validation of the incoming stream’s content type or size is performed here; enforce validation at call sites if needed. +- DeleteFile uses GetFilePath to locate the file before deleting and becomes a no-op if the file does not exist. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md new file mode 100644 index 0000000..f8b3125 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md @@ -0,0 +1,124 @@ +# LinkEmbedService + +> **File:** `src/EchoHub.Server/Services/LinkEmbedService.cs` +> **Kind:** class + +*Figure: How LinkEmbedService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +Start["Start"] +Extract["ExtractUrls(content) -> urls"] +CheckUrls["urls.Count == 0?"] +ReturnNullNoUrls["Return null (no URLs found)"] +InitEmbeds["Create empty List#60;EmbedDto#62; embeds"] +ForEach["For each url in urls"] +CallFetch["Call FetchEmbedForUrlAsync(url)"] +ReturnNullFromFetch["Returned null -> continue"] +AddEmbed["Add EmbedDto to embeds"] +CatchLog["Catch Exception -> LogDebug and continue"] +AfterLoop["All URLs processed"] +ReturnDecision["embeds.Count > 0?"] +ReturnEmbeds["Return embeds"] +ReturnNullAll["Return null (no successful embeds)"] + +subgraph FetchEmbedForUrlAsync + F1["Try Uri.TryCreate(url, Absolute)"] + F1_no["Return null (invalid uri)"] + F2["Check scheme is http or https"] + F2_no["Return null (unsupported scheme)"] + F3["IsPrivateHost(uri)?"] + F3_no["Return null (private host)"] + F4["Create CTS with HubConstants.EmbedFetchTimeoutSeconds"] + F5["Create HTTP client 'OgFetch'"] + F6["Send GET request, get response"] + F7["response.IsSuccessStatusCode?"] + F7_no["Return null (unsuccessful status)"] + F8["Content-Type starts with #quot;text/html#quot;?"] + F8_no["Return null (non-html content)"] + F9["Read limited HTML (HubConstants.EmbedMaxHtmlBytes)"] + F9_empty["Return null (empty or whitespace html)"] + F10["Parse OG tags, get title or fall back to #60;title#62;"] + F10_no["Return null (no title)"] + F11["Build EmbedDto and return"] +end + +Start --> Extract +Extract --> CheckUrls +CheckUrls -->|"yes"| ReturnNullNoUrls +CheckUrls -->|"no"| InitEmbeds +InitEmbeds --> ForEach +ForEach --> CallFetch +CallFetch -->|"throws"| CatchLog +CallFetch -->|"null"| ReturnNullFromFetch +CallFetch -->|"EmbedDto"| AddEmbed +ReturnNullFromFetch --> ForEach +AddEmbed --> ForEach +CatchLog --> ForEach +ForEach -->|"done"| AfterLoop +AfterLoop --> ReturnDecision +ReturnDecision -->|"yes"| ReturnEmbeds +ReturnDecision -->|"no"| ReturnNullAll + +CallFetch --> F1 +F1 -->|"no"| F1_no +F1 -->|"yes"| F2 +F2 -->|"no"| F2_no +F2 -->|"yes"| F3 +F3 -->|"true"| F3_no +F3 -->|"false"| F4 +F4 --> F5 +F5 --> F6 +F6 --> F7 +F7 -->|"no"| F7_no +F7 -->|"yes"| F8 +F8 -->|"no"| F8_no +F8 -->|"yes"| F9 +F9 -->|"empty"| F9_empty +F9 -->|"has html"| F10 +F10 -->|"no"| F10_no +F10 -->|"yes"| F11 + +F1_no --> ReturnNullFromFetch +F2_no --> ReturnNullFromFetch +F3_no --> ReturnNullFromFetch +F7_no --> ReturnNullFromFetch +F8_no --> ReturnNullFromFetch +F9_empty --> ReturnNullFromFetch +F10_no --> ReturnNullFromFetch +F11 --> AddEmbed +``` + +```csharp +public partial class LinkEmbedService +``` + + +Scans a piece of message text for URLs and attempts to produce lightweight link preview data (EmbedDto) by fetching and parsing Open Graph and common HTML metadata. Use TryGetEmbedsAsync when you need server-side link previews for chat messages and want a defensive, timeout- and size-limited fetch that never throws (it logs failures and returns null when no usable embeds are found). + +## Remarks +LinkEmbedService centralizes the logic for discovering URLs in a message and converting remote HTML metadata into EmbedDto instances suitable for display. It is intentionally defensive: only absolute http/https URLs are considered, private hosts are skipped, fetches are limited by a cancellation timeout and a maximum HTML byte count (HubConstants), and only text/html responses are parsed. Errors during individual fetches are caught and logged at debug level so the caller observes either a list of successful embeds or null (no useful embeds). + +## Example +```csharp +// Given an instance of LinkEmbedService (typically from DI): +var embeds = await linkEmbedService.TryGetEmbedsAsync(messageContent); +if (embeds is null) +{ + // No embeds found or all fetch attempts failed. +} +else +{ + Console.WriteLine($"Found {embeds.Count} embeds"); + foreach (var embed in embeds) + { + // render embed in UI or pass to presentation layer + } +} +``` + +## Notes +- TryGetEmbedsAsync returns null when no URLs are present or when all fetches fail; it does not return an empty list in those cases—check for null before iterating. +- The service expects an IHttpClientFactory and creates a client with the name "OgFetch"; ensure your HttpClient configuration (handlers, DNS/timeout policies) is appropriate for remote HTML fetches. +- HTML metadata extraction is heuristic: it uses Open Graph tags, falls back to a regex, reads only the first N bytes of HTML, and truncates long descriptions per HubConstants. Consumers should treat returned fields as untrusted display content and apply any necessary sanitization in the UI layer. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/MessageEncryptionService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/MessageEncryptionService.cs.md new file mode 100644 index 0000000..04f392e --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/MessageEncryptionService.cs.md @@ -0,0 +1,19 @@ +# MessageEncryptionService + +> **File:** `src/EchoHub.Server/Services/MessageEncryptionService.cs` +> **Kind:** class + +```csharp +public class MessageEncryptionService : IMessageEncryptionService +``` + + +MessageEncryptionService provides AES-GCM-based encryption and decryption for strings using a 256-bit key loaded from configuration, returning ciphertexts in a standardized prefixed, base64-encoded format. Callers use it when they need authenticated encryption with a consistent storage format and null-safety helpers. + +## Remarks +By centralizing the encryption logic, this class ensures all encrypted messages share the same nonce handling, tag size, and output format, which simplifies storage and auditing across clients and servers. It also enforces key validation upfront and uses dependency-injected logging to surface decryption problems and protect the caller from exceptions. The EncryptNullable/DecryptNullable helpers make it convenient to encode optional values without duplicating boilerplate. + +## Notes +- Key retrieval and validation: the constructor reads Encryption:Key from configuration as a Base64 string and requires exactly 32 bytes; otherwise it throws InvalidOperationException. +- Decryption safety and error handling: if content doesn't start with the CiphertextPrefix, it is treated as legacy plaintext; malformed payloads log a warning and yield "[encrypted message — decryption failed]"; any exception results in a logged error and the same sentinel output. +- Null handling convenience: EncryptNullable and DecryptNullable gracefully handle null inputs without throwing. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/MuteExpirationService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/MuteExpirationService.cs.md new file mode 100644 index 0000000..19984b0 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/MuteExpirationService.cs.md @@ -0,0 +1,21 @@ +# MuteExpirationService + +> **File:** `src/EchoHub.Server/Services/MuteExpirationService.cs` +> **Kind:** class + +```csharp +public sealed class MuteExpirationService : BackgroundService +``` + + +Automatically unmutes users when their timed mute period has expired. + +This is a background hosted service that periodically scans for users who are currently muted and whose MutedUntil timestamp has passed, then clears the mute state and logs the action. It uses a scoped DbContext instance per iteration (via IServiceScopeFactory) to perform a safe, isolated database update, and it runs on a fixed cadence (15 seconds) until the host is stopped. The service catches non-cancellation exceptions to avoid leaking the loop and continues monitoring uninterrupted. + +## Remarks +The MuteExpirationService centralizes the expiry-based state transition for user mutes, decoupling this concern from user actions or other services. By resolving EchoHubDbContext within a scope for each cycle, it ensures proper disposal of the context and its resources while keeping the background loop lightweight. This pattern keeps mute state consistent across the system and reduces the chance of missed expirations if a user’s timed mute expires while the application is running. + +## Notes +- The query materializes expired mutes with ToListAsync before processing; for environments with a very large backlog of expirations, consider batching to reduce memory usage. +- The cadence (CheckInterval) is 15 seconds; adjust if you need tighter or looser alignment with mute expiration semantics. +- Time comparisons use UTC (DateTimeOffset.UtcNow) to avoid timezone-related drift; ensure MutedUntil is stored as a UTC timestamp to preserve correctness. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/PresenceTracker.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/PresenceTracker.cs.md new file mode 100644 index 0000000..28ed761 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/PresenceTracker.cs.md @@ -0,0 +1,39 @@ +# PresenceTracker + +> **File:** `src/EchoHub.Server/Services/PresenceTracker.cs` +> **Kind:** class + +```csharp +public class PresenceTracker +``` + + +Tracks active connections and per-user channel membership for a server-side hub/service. Use this when you need to know which usernames are currently connected (counting a user with multiple connections only once), map individual connection IDs to their user, and query which users are in which chat channels. + +## Remarks +PresenceTracker centralizes presence state in three concurrent dictionaries: a connectionId → (userId, username) map, a username → set-of-connectionIds map, and a username → set-of-channelNames map. It uses a single private lock to make operations on the HashSet values atomic because ConcurrentDictionary only protects access to individual slots, not the mutable collections stored as values. The UserCountChanged event is raised only when the distinct online user count changes (for example, when a user's first connection is added or their last connection is removed); the implementation invokes the event outside the lock to avoid holding the lock while user code runs. + +## Example +```csharp +var tracker = new PresenceTracker(); +tracker.UserCountChanged += count => Console.WriteLine($"Online users: {count}"); + +// user connects from two clients (only the first connection should trigger the count change) +tracker.UserConnected("conn-1", Guid.NewGuid(), "alice"); // triggers UserCountChanged -> 1 +tracker.UserConnected("conn-2", Guid.NewGuid(), "alice"); // no count change + +// join a channel and query who is in it +tracker.JoinChannel("alice", "general"); +var usersInGeneral = tracker.GetOnlineUsersInChannel("general"); // contains "alice" + +// disconnect one connection; user still online because another connection remains +tracker.UserDisconnected("conn-1"); // returns "alice"; no UserCountChanged + +// final disconnect removes the user and triggers UserCountChanged +tracker.UserDisconnected("conn-2"); // returns "alice"; triggers UserCountChanged -> 0 +``` + +## Notes +- The class treats usernames as dictionary keys using the string's default equality (case-sensitive by default). Normalize or use a consistent casing strategy before calling if your application expects case-insensitive behavior. +- The lock protects the HashSet instances stored in the dictionaries; callers do not need to synchronize when calling the public methods, but should avoid long-running work inside UserCountChanged handlers because the event is invoked from the presence-tracking flow (the implementation intentionally invokes the event outside the lock, but handlers that re-enter tracker methods could still affect ordering). +- The provided source appears truncated / contains a small syntax issue near GetChannelsForUser and GetConnectionsInChannels; verify the final implementation of those methods before relying on their exact return behavior. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md new file mode 100644 index 0000000..79d7dfe --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md @@ -0,0 +1,820 @@ +# ServerDirectoryService.cs + +> **Source:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` + +## Contents + +- [ServerDirectoryService](#serverdirectoryservice) + - [InfiniteRetryPolicy](#infiniteretrypolicy) + - [BuildConnection](#buildconnection) + - [ConnectWithRetryAsync](#connectwithretryasync) + - [DisposeConnectionAsync](#disposeconnectionasync) + - [ExecuteAsync](#executeasync) + - [ExtractConflictingHosts](#extractconflictinghosts) + - [GetBackoffDelay](#getbackoffdelay) + - [HandleRegistrationErrorAsync](#handleregistrationerrorasync) + - [HandleRegistrationResponseAsync](#handleregistrationresponseasync) + - [OnUserCountChanged](#onusercountchanged) + - [ProcessUserCountUpdatesAsync](#processusercountupdatesasync) + - [RegisterAsync](#registerasync) + - [ResolveVersion](#resolveversion) + - [RunConnectionLoopAsync](#runconnectionloopasync) + - [StopAsync](#stopasync) + - [DirectoryHubUrl](#directoryhuburl) + - [ReconnectBaseDelay](#reconnectbasedelay) + - [ReconnectMaxDelay](#reconnectmaxdelay) +- [DirectoryProtocol](#directoryprotocol) +- [DirectoryRegistrationErrors](#directoryregistrationerrors) +- [ErrorDetail](#errordetail) +- [RegisterServerDto](#registerserverdto) +- [RegisterServerResult](#registerserverresult) +- [Response](#response) +- [ServerDirectoryService (constructor)](#serverdirectoryservice-constructor) +- [UserCountMinInterval](#usercountmininterval) + +--- + +## ServerDirectoryService +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** class + +```csharp +public sealed class ServerDirectoryService : BackgroundService +``` + + +Maintains a durable, resilient registration of this process in the central server directory and continuously reports presence (user counts) to that directory. Run as a hosted BackgroundService, it opens and manages a SignalR HubConnection to the directory, performs server registration/claiming, publishes metadata (name, description, hosts, version, tags) and incremental presence updates, and automatically reconnects with backoff when the connection drops. + +## Remarks +This service sits between the local PresenceTracker, a persistent DirectoryClaimStore (which holds claim tokens and server IDs), and the remote directory hub. It coalesces frequent presence changes into a single "latest wins" update using a single-slot bounded channel to avoid flooding the directory, and applies an exponential backoff on reconnect attempts to avoid tight retry loops. Certain registration failures (for example: host already claimed, invalid token, or host conflict) are treated as permanent for the lifetime of the process — once that permanent-failure state is observed the service stops attempting to register on that connection and any subsequent reconnects, leaving operator intervention required to correct configuration and restart. + +## Notes +- Permanent registration failures stop further register attempts even across reconnections; the operator must fix configuration and restart the service to recover. +- Presence updates are coalesced and throttled: the single-slot channel drops intermediate values (latest wins) and sends no more often than the configured UserCountMinInterval, so short-lived fluctuations may be suppressed. +- Reconnect attempts use a backoff between ReconnectBaseDelay and ReconnectMaxDelay; expect progressively longer wait times on repeated failures. +- The service relies on configuration and on DirectoryClaimStore to persist claim tokens; ensure those dependencies are available and correctly configured or registration will fail. + +--- + +### InfiniteRetryPolicy +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** class + +```csharp +private sealed class InfiniteRetryPolicy : IRetryPolicy +``` + + +Retrieves indefinitely with exponential backoff capped at a maximum delay for reconnect attempts. This private sealed class implements IRetryPolicy and provides a retry strategy that increases the wait time between attempts rather than failing fast, enabling resilient reconnection to the server directory service. + +NextRetryDelay yields delays based on an exponential progression: the first retry occurs after 1 second, followed by 2 seconds, 4 seconds, 8 seconds, and 16 seconds. After that, the delay is capped by ReconnectMaxDelay (30 seconds), so all subsequent retries use that maximum delay. This approach balances persistence in the face of transient failures with a bound on retry timing to avoid excessive load. + +## Remarks +This policy encapsulates a specific retry strategy behind the IRetryPolicy interface, isolating timing logic from the rest of the reconnection code. Marked private and sealed, it signals an internal, non-extendable implementation used solely by the server directory service's retry mechanism. The cap on delay helps prevent runaway retry intervals while still ensuring the system makes progress toward recovery. + +## Notes +- The first retry delay is 1 second, not immediate. +- Delays progress as 1s, 2s, 4s, 8s, 16s, and then 30s for all subsequent retries due to the cap. +- If many clients share the same cap, consider introducing jitter at the call site to avoid synchronized retries (this policy does not include jitter by default). + + +--- + +### BuildConnection +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private HubConnection BuildConnection() +``` + +**Returns:** `HubConnection` + + +BuildConnection constructs and returns a HubConnection configured to connect to the directory hub. It encapsulates the boilerplate of wiring the hub URL and an infinite automatic-reconnect policy, so callers can obtain a ready-to-configure connection without duplicating setup code. + +## Remarks +BuildConnection centralizes the creation of the SignalR client used by the directory service, ensuring a consistent URL and reconnect policy across all call sites. By wrapping the builder steps, it reduces boilerplate and makes it easy to adjust the underlying connection strategy in one place. Note that the returned HubConnection is configured but not started; callers should invoke StartAsync (and manage its lifecycle) when ready. The attached InfiniteRetryPolicy governs how the client attempts to reconnect after a disconnect, providing resilience against transient network issues. + +## Notes +- The connection is not started by BuildConnection; you must call StartAsync and later dispose of the connection to avoid leaks. Ensure DirectoryHubUrl is properly configured before using this method. + +--- + +### ConnectWithRetryAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private async Task<bool> ConnectWithRetryAsync(HubConnection connection, CancellationToken ct) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connection` | `HubConnection` | — | +| `ct` | `CancellationToken` | — | + +**Returns:** `Task<bool>` + + +ConnectWithRetryAsync establishes a SignalR hub connection by repeatedly invoking StartAsync on the supplied HubConnection until the operation succeeds or the provided CancellationToken is triggered. When StartAsync completes successfully, the method returns true. If an exception occurs, the method increments its retry counter, computes a backoff delay via GetBackoffDelay(attempt), logs a warning including the delay, and awaits Task.Delay(delay, ct) before retrying. If the CancellationToken is canceled before a successful connection, the loop exits and the method returns false. This encapsulates transient-connection retry logic so callers do not have to implement their own retry loop. + +## Remarks +Centralizes retry/backoff semantics for establishing the directory connection, so callers don't implement their own loop. It respects the cancellation token to avoid hanging and uses logging to surface transient failures for operators. + +## Notes +- All exceptions from StartAsync are treated as retryable; there is no distinction between transient and permanent errors. +- CancellationToken is observed during both StartAsync and the subsequent Task.Delay, so cancellation is respected promptly. +- The backoff duration is determined by GetBackoffDelay(attempt); ensure this aligns with the desired backoff strategy to avoid excessively long waits or too-aggressive retries. + +--- + +### DisposeConnectionAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private static async Task DisposeConnectionAsync(HubConnection connection) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connection` | `HubConnection` | — | + +**Returns:** `Task` + + +Disposes the given HubConnection asynchronously with a hard 3-second timeout and suppresses any errors, ensuring shutdown proceeds without being blocked by a slow disposal. Use this during teardown when you want to promptly release the connection without surfacing disposal failures. + +## Remarks +This pattern encapsulates a best-effort disposal strategy: it waits up to three seconds for disposal to complete, then continues regardless of the outcome. By catching all exceptions, callers cannot rely on successful disposal being reported; if you need visibility into disposal failures, handle the disposal outside this helper. It is intended for shutdown scenarios where the connection must be released promptly and further operations on the connection are no longer needed. + +## Example +```csharp +// Example usage within the same class +await DisposeConnectionAsync(connection); +``` + +## Notes +- Empty catch hides disposal failures; only use this when shutdown must not be delayed by disposal issues. +- The 3-second timeout is hard-coded; adjust if your application's shutdown window requires a different bound. + +--- + +### ExecuteAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +protected override async Task ExecuteAsync(CancellationToken stoppingToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `stoppingToken` | `CancellationToken` | — | + +**Returns:** `async Task` + + +Executes the host’s startup lifecycle for registering the server with the EchoHubSpace directory when configured to be public. It yields to the host to finish starting, validates the configuration, collects hosts and metadata from configuration, resolves the server version, and then delegates to the connection loop that maintains the directory registration. It also subscribes to user-count changes so presence updates can be propagated while the registration is active, and guarantees cleanup of the event subscription when the operation completes or fails. + +--- + +### ExtractConflictingHosts +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private static string[]? ExtractConflictingHosts(ErrorDetail? error) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `error` | `ErrorDetail?` | — | + +**Returns:** `string[]?` + + +ExtractConflictingHosts reads a JSON payload from an ErrorDetail's Data field and returns the list of host names described under the ConflictingHosts property. It tolerates both PascalCase (ConflictingHosts) and camelCase (conflictingHosts) keys because SignalR's wire casing depends on the hub's serializer configuration, and the field is typed object?. + +It returns null when the payload is missing or not a JSON object, when neither property is present, when the property isn't an array, or when the array contains no string entries. Otherwise, it returns a string[] of the host names extracted from the array. + +## Remarks +The helper centralizes resilient parsing of optional error metadata, shielding callers from variations in payload shape and casing. By returning null for absent or empty data, it lets higher-level error handling distinguish between "no information" and an explicit list of conflicting hosts. + +## Notes +- Returns null rather than an empty array when no hosts are present or the data is malformed. +- Non-string elements inside the host list are ignored. +- The method is private and static, indicating it is an internal helper for extracting just this piece of information from a larger error payload. + +--- + +### GetBackoffDelay +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private static TimeSpan GetBackoffDelay(int attempt) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `attempt` | `int` | — | + +**Returns:** `TimeSpan` + + +Calculates the exponential backoff delay for a reconnect attempt. Given the retry attempt index, it computes 2^min(attempt, 10) seconds, then clamps the result to ReconnectMaxDelay. The returned TimeSpan is used by the reconnect logic to wait before the next attempt, ensuring that retries are spaced out but never exceed a configured maximum delay. + +## Remarks +Isolates the backoff policy in a small helper, keeping the retry loop simple and readable. The exponential ramp-up helps avoid overwhelming the remote endpoint while still providing progressively longer waits as failures persist; the cap guarantees a bound on wait times. This method is private to the class and intended for internal use by the directory service's reconnect flow. + +## Notes +- Ensure 'attempt' is non-negative; negative values yield sub-second delays due to 2^negative, which may be surprising. +- The delay is clamped to ReconnectMaxDelay; even very large attempts cannot produce longer waits. + +--- + +### HandleRegistrationErrorAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private Task HandleRegistrationErrorAsync(ErrorDetail[]? errors) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `errors` | `ErrorDetail[]?` | — | + +**Returns:** `Task` + + +HandleRegistrationErrorAsync interprets the errors returned by the directory registration attempt, logs a code-specific message, and marks the registration as permanently failed to stop automatic retries until a restart. + +## Remarks + +This method centralizes the directory registration failure handling, consolidating how various error codes are surfaced to operators and how the failure state is recorded. It relies on ExtractConflictingHosts to surface any conflicting hosts and on the claim store to persist the failure details so that diagnostics and recovery decisions can reason about what happened. + +## Notes + +- It forces the server into a permanently failed state for registration, with log messages indicating that the server will not retry until restarted. This ensures long-running processes do not silently retry under inconsistent directory state. +- It returns a completed Task and performs its side effects synchronously (logging and state mutation) without throwing, so callers can await the result safely without handling exceptions. + + +--- + +### HandleRegistrationResponseAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private async Task HandleRegistrationResponseAsync(Response<RegisterServerResult>? envelope, int userCount, string name, string[] hosts) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `envelope` | `Response<RegisterServerResult>?` | — | +| `userCount` | `int` | — | +| `name` | `string` | — | +| `hosts` | `string[]` | — | + +**Returns:** `Task` + + +Handles the directory registration response by validating the envelope, enforcing protocol compatibility, and performing the appropriate follow-up depending on success or failure. It ensures a durability guarantee by saving a fresh claim token before acknowledging success, otherwise updating the ServerId to keep internal state in sync, and it logs the outcome for observability. + +--- + +### OnUserCountChanged +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private void OnUserCountChanged(int newCount) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `newCount` | `int` | — | + +**Returns:** `void` + + +OnUserCountChanged is an internal callback invoked whenever the server detects a change in the user count. It publishes the new value by writing to a single-slot channel via _userCountUpdates.Writer.TryWrite(newCount). The single-slot channel semantics coalesce bursts of updates so that only the most recent count is propagated downstream, reducing churn and avoiding repeated handling for rapid presence changes. + +## Remarks +By delegating to a dedicated Writer, this method decouples the act of detecting changes from the consumers that react to them. The single-slot channel pattern ensures downstream work is debounced; observers observe the latest value after a change cycle, which is ideal for presence-aware UI updates or telemetry. + +## Notes +- The call does not inspect the result of TryWrite; if the channel is full or readers slow, an update may be dropped, so downstream consumers should be able to tolerate occasional missed updates. +- This method is private to its containing type; external code should not rely on direct invocation. + +--- + +### ProcessUserCountUpdatesAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private async Task ProcessUserCountUpdatesAsync(HubConnection connection, Task connectionClosed, CancellationToken ct) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `connection` | `HubConnection` | — | +| `connectionClosed` | `Task` | — | +| `ct` | `CancellationToken` | — | + +**Returns:** `Task` + + +ProcessUserCountUpdatesAsync continuously consumes user-count updates from a buffered channel and, when appropriate, reports the latest count to the directory via a HubConnection. It throttles emissions to respect a minimum interval, draining newer values during the wait so the hub receives the most up-to-date count rather than a stale snapshot, and it exits gracefully on cancellation or connection closure; updates are only sent when the hub is connected and the local registration is valid. + +## Remarks +This method decouples producers of user-count data from the actual update path by reading from a channel and emitting to the directory hub only when ownership conditions are met. The drain-on-wait policy ensures the directory reflects the latest state under bursty updates without flooding the hub, and the preconditions (connected hub and valid registration) guard presence reporting within the lifecycle of the system. + +## Notes +- Updates may be dropped under bursty traffic due to throttling and the drain loop; callers should not rely on every intermediate update being observed by the hub. +- If the hub is temporarily unavailable or registration is not established, updates are skipped until conditions are met; there is no automatic backoff beyond the local catch logging. +- Cancellation via the provided CancellationToken causes an immediate exit from the loop; ensure callers signal cancellation during shutdown to avoid lingering tasks. + +--- + +### RegisterAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private async Task RegisterAsync(string name, string? description, string[] hosts, string version, string[] tags) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `name` | `string` | — | +| `description` | `string?` | — | +| `hosts` | `string[]` | — | +| `version` | `string` | — | +| `tags` | `string[]` | — | + +**Returns:** `Task` + + +Registers the current server with the directory service over a live hub connection. If connected and not permanently failed, it collects the online user count, builds a RegisterServerDto containing the server's name, description, hosts, user count, version, tags, and the current claim token, and sends it to the directory via the hub's RegisterServer method. The response is processed by HandleRegistrationResponseAsync to apply the result locally. Any exceptions are caught and logged as warnings with no propagation to the caller. + +## Remarks +Encapsulates the server-registration handshake behind a private method, so callers don't have to manage DTO construction or hub invocation directly. It coordinates with _presenceTracker for live user counts and with _claimStore to carry the persisted claim token across registrations. The guard checks against the hub's connection state and a permanent-failure flag reflect the intended lifecycle: registration only runs when viable, preventing noisy or duplicate attempts. + +## Notes +- Exceptions are swallowed; the method logs a warning and does not rethrow, so callers cannot rely on exceptions for control flow and may need separate retry logic. +- On the first-ever registration, ClaimToken is null; after the first successful claim it is persisted and reused on subsequent registrations. +- If not connected or if a permanent failure has been recorded, the method returns immediately without attempting registration. + +--- + +### ResolveVersion +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private static string ResolveVersion() +``` + +**Returns:** `string` + + +Resolves the version string used to identify the running ServerDirectoryService assembly. It prefers AssemblyInformationalVersionAttribute.InformationalVersion, but strips any SourceLink git SHA suffix (for example '0.2.10+abc123') before returning; if that attribute isn't present, it falls back to the assembly version, and finally to '0.0.0' if neither is available. + +## Remarks +This centralizes version resolution for the ServerDirectoryService, ensuring a consistent, human-friendly version string for diagnostics, logging, and server identity without leaking VCS details. It prefers source-controlled metadata when possible, but gracefully degrades to a stable default when it's not. + +## Notes +- Strips the SourceLink git SHA suffix by locating the '+' and returning the prefix portion only. +- If neither informational version nor assembly version is available, the method returns '0.0.0'. +- Uses a private static helper scope; ensure tests align with the private context and the assembly hosting the symbol remains ServerDirectoryService's assembly. + +--- + +### RunConnectionLoopAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +private async Task RunConnectionLoopAsync( + string serverName, + string? description, + string[] hosts, + string version, + string[] tags, + CancellationToken stoppingToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `serverName` | `string` | — | +| `description` | `string?` | — | +| `hosts` | `string[]` | — | +| `version` | `string` | — | +| `tags` | `string[]` | — | +| `stoppingToken` | `CancellationToken` | — | + +**Returns:** `Task` + + +## Source Code +Runs a resilient, long-running loop that manages the lifecycle of a connection to a directory service. It repeatedly builds a connection, wires in heartbeat and re-registration logic, and, when the connection is permanently closed or cancellation is requested, cleanly tears down and rebuilds the connection to maintain availability. + +## Remarks +This method centralizes the connection lifecycle management, coordinating connection establishment, heartbeat handling, re-registration on reconnect, and clean disposal. It relies on a cancellation token and a TaskCompletionSource to synchronize asynchronous events across the loop, enabling robust recovery paths while preserving a consistent registration state. + +## Notes +- If ConnectWithRetryAsync(connection, stoppingToken) returns false, the method exits, causing the outer loop to terminate and the service to stop attempting a reconnect. +- The On("Ping") handler sends a heartbeat back to the directory and safely logs any heartbeat failures without crashing the loop. +- When the connection is permanently closed, the Closed event signals completion via the TaskCompletionSource and the outer loop proceeds to rebuild after a short delay, unless cancellation has been requested. + +## Dependencies +- TaskCompletionSource +- TaskCreationOptions +- Task + +## Dependency APIs +- TaskCompletionSource (non-generic) + - Constructor: TaskCompletionSource(TaskCreationOptions options) + - Property: Task Task { get; } +- TaskCreationOptions (enum) + - Member used: RunContinuationsAsynchronously +- Task (System.Threading.Tasks.Task) + - Represents an asynchronous operation; used for awaiting and coordinating async work + +## Symbol To Document +- Name: RunConnectionLoopAsync +- Kind: method +- File: src/EchoHub.Server/Services/ServerDirectoryService.cs +- Language: csharp +- ID: a28a6f2b-23c7-4de0-bb5e-3da24401feb3 + +--- + +### StopAsync +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** method + +```csharp +public override async Task StopAsync(CancellationToken cancellationToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `cancellationToken` | `CancellationToken` | — | + +**Returns:** `async Task` + + +Override of StopAsync performs the base shutdown logic and then clears the internal _connection to release the resource and reflect that the service is disconnected. + +## Remarks +Ensures the derived service participates in the lifecycle by letting the base stop routine complete before releasing its own resources. Clearing _connection after the base stop prevents reuse of an active connection during shutdown and marks the service as disconnected for the rest of the system. + +## Notes +- If base.StopAsync throws, _connection will not be cleared; consider wrapping the cleanup in a finally block to guarantee cleanup. + +--- + +### DirectoryHubUrl +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** field + +```csharp +private const string DirectoryHubUrl = "https://echohub.voidcube.cloud/hubs/servers" +``` + + +This private constant string DirectoryHubUrl holds the base URL for the servers directory hub used by ServerDirectoryService. It is initialized to https://echohub.voidcube.cloud/hubs/servers and should be referenced wherever the directory hub endpoint is needed, ensuring a single source of truth and avoiding string duplication. + +## Remarks +By centralizing the hub URL in a single private constant, the class avoids scattering the endpoint string across multiple methods. This reduces the risk of inconsistent paths and simplifies maintenance if the hub address changes; it also makes the code more testable by isolating the configuration-like value in one place. + +## Notes +- The value is baked into the assembly as a private const; it cannot be overridden at runtime. For environment-specific endpoints, consider configuration-driven access and testing hooks to swap or mock the value. + +--- + +### ReconnectBaseDelay +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** field + +```csharp +private static readonly TimeSpan ReconnectBaseDelay = TimeSpan.FromSeconds(2) +``` + + +ReconnectBaseDelay is a private static readonly TimeSpan that defines the base wait time used by ServerDirectoryService when retrying a failed connection. By centralizing this 2-second base delay, the code avoids magic numbers and provides a single point to tune the retry cadence across all reconnection attempts. + +## Remarks +Centralizing the base delay enforces a uniform retry cadence and simplifies tuning during incidents or tests. Being static and readonly ensures the value is shared across all instances and cannot be changed at runtime, which preserves predictable timing in concurrent reconnection scenarios. If you later introduce a more sophisticated backoff strategy (for example, exponential backoff with jitter), this base delay would typically feed that mechanism rather than replace it. + +## Notes +- Changing this value affects all reconnection retries across the service; it's a global constant for the directory service. +- Because it is private, external code or tests cannot override it directly; consider configuration or making it injectable if runtime tunability is required. + +--- + +### ReconnectMaxDelay +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** field + +```csharp +private static readonly TimeSpan ReconnectMaxDelay = TimeSpan.FromSeconds(30) +``` + + +Defines the upper bound for the delay between reconnection attempts. The field is private, static, and readonly, initialized as TimeSpan.FromSeconds(30). It is used by the server’s internal reconnection logic to cap backoff durations, ensuring retry intervals remain bounded even under transient network issues. + +## Remarks +Centralizes reconnection policy within ServerDirectoryService to ensure consistent retry timing across all attempts. Being private and readonly, this value is not exposed to external components and cannot be modified at runtime, promoting predictable behavior and easier maintenance. The 30-second cap prevents excessively long delays during outages while avoiding overly aggressive retry loops. + +## Notes +- The maximum delay is fixed after class initialization; changing it requires code edits and a recompilation. +- Private scope ensures external code cannot depend on or bypass this policy. + +--- + +## DirectoryProtocol +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** class + +```csharp +internal static class DirectoryProtocol +``` + + +DirectoryProtocol is a small, internal helper that exposes the current envelope protocol version used by the server's directory communications. The Version constant holds the protocol version as a string ("1.0"), and serves as a single source of truth for compatibility checks. Bumps to this version are coordinated across both repositories to keep envelope formats aligned during client/server exchanges. + +## Remarks +By centralizing the protocol version, this type makes explicit when envelope formats may evolve and prevents drift between the two sides. It also clarifies where to pull the version for any envelope construction or validation, reducing the risk of duplicating literals across the codebase. + +## Notes +- Do not hard-code '1.0' in multiple places; reference DirectoryProtocol.Version instead. +- This class is internal; its Version member is only accessible to code within the same assembly, so cross-repo coordination relies on the shared build/packaging process. + +--- + +## DirectoryRegistrationErrors +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** class + +```csharp +internal static class DirectoryRegistrationErrors +``` + + +This internal static class DirectoryRegistrationErrors serves as a centralized collection of string constants that represent the standard error codes used during the EchoHub server's directory registration workflow. It helps avoid hard-coded literals spread across the codebase and provides a single source of truth for the messages the hub uses to classify and surface registration failures. The constants cover common causes like invalid input, invalid token, host state conflicts, as well as client-side synthetic codes used for status reporting (ProtocolVersionMismatch, MalformedResponse) which are not emitted by the hub. + +## Remarks +The class is internal to the server assembly and centralizes canonical error codes for the directory registration subsystem to promote consistent error handling across components. Keeping these strings in one place reduces typos and mismatches in error reporting and mapping. Note that ProtocolVersionMismatch and MalformedResponse are client-side synthetic codes documented here for parity; they are never emitted by the hub. + +## Notes +- Not accessible from outside the server assembly; if you need client-visible error codes, expose a separate contract instead. + +--- + +## ErrorDetail +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** record + +```csharp +internal record ErrorDetail(string Code, string? Message, JsonElement? Data) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Code` | `string` | — | +| [`Message`](../../EchoHub.Core/Models/Message.cs.md) | `string?` | — | +| `Data` | `JsonElement?` | — | + + +ErrorDetail represents a single error entry that can appear inside a `Response<T>` as part of an API error payload. It carries an error code (Code), an optional human-readable message (Message), and an optional Data payload for error-specific details. The Data field is typed as JsonElement to keep the payload shape flexible, accommodating different errors with varying detail structures (for example, a host-related error might include a ConflictingHosts array). As a record, ErrorDetail benefits from value-based equality and immutability, which makes it a stable, serializable unit for error reporting across API boundaries. + +## Remarks +ErrorDetail's design separates the error signaling (via Code) from the optional payload (Message and Data), enabling clients to react to known codes while optionally surfacing human-readable context or structured details. It works alongside the surrounding `Response<T>` wrapper to assemble a consistent error surface while preserving flexibility in the Data payload. The JsonElement Data keeps the detail shape decoupled from the type system, at the cost of requiring clients to inspect Code before interpreting Data. + +## Example +```csharp +using System.Text.Json; + +var json = "{\"ConflictingHosts\":[\"host1\",\"host2\"]}"; +JsonElement data = JsonSerializer.Deserialize<JsonElement>(json); + +var error = new ErrorDetail( + Code: "ConflictingHosts", + Message: "One or more hosts conflict with existing entries.", + Data: data +); +``` + +## Notes +- Data is loosely-typed by design; clients should first inspect Code to determine how to interpret Data. +- If Data is null, the consumer should rely on Code and optional Message for context. + +--- + +## RegisterServerDto +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** record + +```csharp +internal record RegisterServerDto( + string Name, + string? Description, + string[] Hosts, + int UserCount, + string Version, + string[] Tags, + string? ClaimToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Name` | `string` | — | +| `Description` | `string?` | — | +| `Hosts` | `string[]` | — | +| `UserCount` | `int` | — | +| `Version` | `string` | — | +| `Tags` | `string[]` | — | +| `ClaimToken` | `string?` | — | + + +RegisterServerDto is a compact, immutable data transfer object (record) that carries all the information required to register a server in the EchoHub server directory. It groups identity data (Name, Version), optional metadata (Description), network endpoints (Hosts), current user load (UserCount), and classification tags (Tags) into a single value object so callers supply a single payload to the directory service rather than wiring multiple fields through separate calls. The optional ClaimToken supports claim-based authorization when needed. + +## Remarks +RegisterServerDto exists to encapsulate the registration data in a single cohesive unit, decoupling the producer from the directory service and enabling consistent validation and persistence. As a record, it provides value-based equality, which helps determine duplicates or idempotent operations across registration attempts. + +## Example +```csharp +var dto = new RegisterServerDto( + Name: "EchoServer-01", + Description: "Primary gateway for region A", + Hosts: new[] { "https://host1.example.com", "https://host2.example.com" }, + UserCount: 128, + Version: "2.3.1", + Tags: new[] { "production", "gateway" }, + ClaimToken: null +); +``` + +## Notes +- The Hosts and Tags properties are string[] arrays; their contents can be mutated after construction since arrays are mutable. If you need true immutability, consider defensive copies or using a read-only collection type in a different design. + +--- + +## RegisterServerResult +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** record + +```csharp +internal record RegisterServerResult(Guid ServerId, string? ClaimToken) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `ServerId` | `Guid` | — | +| `ClaimToken` | `string?` | — | + + +An internal, immutable data carrier that represents the outcome of registering a server in EchoHub's directory service. It holds the assigned ServerId and an optional ClaimToken returned alongside the registration result. Callers construct this type at the end of a registration flow to pass both pieces of information together, rather than returning them separately. + +## Remarks +Designed to decouple the registration outcome from the service logic and to expose a stable, immutable snapshot of the operation. By using a record, it gains value-based equality and built-in deconstruction, which makes testing and wiring across layers straightforward. The optional ClaimToken acknowledges scenarios where a token is not issued; consumers should handle its absence gracefully. + +## Example +```csharp +var serverId = Guid.NewGuid(); +var result = new RegisterServerResult(serverId, "token-abc"); +// result.ServerId == serverId +// result.ClaimToken == "token-abc" +``` + +## Notes +- ClaimToken is nullable; callers should guard against null before use. +- The type is internal, so it is not part of the public API surface outside its assembly. +- Being a record, it supports deconstruction (e.g., `var (id, token) = result;`) and value-based equality, which aids comparisons and pattern-based usage. + +--- + +## Response +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** record + +```csharp +internal record Response<T>(bool IsSuccess, T? Data, ErrorDetail[]? Errors, string? Version) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `IsSuccess` | `bool` | — | +| `Data` | `T?` | — | +| `Errors` | `ErrorDetail[]?` | — | +| `Version` | `string?` | — | + + +Generic envelope wrapper for directory hub responses. It mirrors the EchoHubSpace contract by wrapping a success indicator, an optional payload, optional errors, and an optional version string into a single, transport-safe object. + +## Remarks +This envelope isolates transport concerns from business logic by providing a uniform surface for responses. Callers should always check IsSuccess before using Data, and rely on Errors for details when it is false. Data and Version are nullable, so consumers must guard for nulls and treat Version as optional metadata rather than a payload. The generic T makes this wrapper reusable for any payload. + +## Example +```csharp +var response = new Response<string>(true, "directory listing", null, "1.2"); +``` + +## Notes +- When IsSuccess is false, Data may be null; always inspect the Errors collection for failure details. +- The symbol is internal to its assembly; to share the envelope across boundaries, you may need a public abstraction or converter on your side. + +--- + +## ServerDirectoryService (constructor) +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** constructor + +```csharp +public ServerDirectoryService( + IConfiguration configuration, + PresenceTracker presenceTracker, + DirectoryClaimStore claimStore, + ILogger<ServerDirectoryService> logger) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `configuration` | `IConfiguration` | — | +| `presenceTracker` | [`PresenceTracker`](PresenceTracker.cs.md) | — | +| `claimStore` | [`DirectoryClaimStore`](DirectoryClaimStore.cs.md) | — | +| `logger` | `ILogger<ServerDirectoryService>` | — | + + +This constructor wires ServerDirectoryService by receiving four dependencies through dependency injection and storing them in private fields. It prepares the service for directory-related operations by providing access to configuration, presence tracking, claim storage, and logging. + +## Remarks +The constructor enforces that ServerDirectoryService cannot operate without configuration, presence tracking, claim storage, and a logger, making its dependencies explicit and testable. It sits at the boundary between configuration and domain logic, coordinating the infrastructure pieces that support directory management. + +## Notes +- Ensure all dependencies are registered in the application's DI container; missing registrations will cause the service resolution to fail at runtime. +- If any dependency requires specific lifetimes (e.g., scoped vs singleton), align them with the composition root to avoid disposal issues or lifetime mismatches. + +--- + +## UserCountMinInterval +> **File:** `src/EchoHub.Server/Services/ServerDirectoryService.cs` +> **Kind:** field + +```csharp +private static readonly TimeSpan UserCountMinInterval = TimeSpan.FromSeconds(1) +``` + + +Defines a shared, immutable throttling interval used by ServerDirectoryService to regulate how often user-count related work runs. The field is private, static, and readonly, initialized to TimeSpan.FromSeconds(1). This ensures a consistent cadence and avoids magic numbers scattered through the class; it's consulted wherever the service needs to debounce or rate-limit user-count updates. + +## Remarks +By centralizing the timing policy in this single member, the class achieves consistent behavior across all usages and simplifies future adjustments. The static readonly combination guarantees that the interval is computed once at type initialization and remains the same for the lifetime of the application, minimizing race-condition risk when read from multiple threads. Because it is private, external callers cannot bypass or alter the cadence; any changes must go through the class logic and a rebuild. + +## Notes +- This is not a compile-time constant; it is evaluated at type initialization and cannot be reassigned afterwards. +- External configuration at runtime is not possible unless the class provides a mechanism to override it. +- If cadence needs to vary by environment or load, consider externalizing to configuration or making the interval configurable instead of editing code. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md new file mode 100644 index 0000000..514d01b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs.md @@ -0,0 +1,99 @@ +# ServerLogsService.cs + +> **Source:** `src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs` + +*Figure: How ServerLogsService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +A[ServerLogsService ReadBacklog] +A --> B[Resolve ServerLogsOptions LogDirectory] +B --> Dir{Directory exists} +Dir -->|Yes| C[Find newest file matching LogFilePattern] +Dir -->|No| E[Return empty list] +C --> F{Newest file found} +F -->|No| E +F -->|Yes| G[Open newest file with FileShare ReadWrite Delete then seek to tail when stream longer than TailReadBytes] +G --> H[Read to end and split by newline into lines] +H --> I[Group lines into LogBacklogEntry with skipLeadingContinuations if seeked and limit from ServerLogsOptions BacklogLines] +I --> J[Return list of LogBacklogEntry] +A -.-> E +``` + +## Contents + +- [ServerLogsService](#serverlogsservice) +- [LogBacklogEntry](#logbacklogentry) + +--- + +## ServerLogsService +> **File:** `src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs` +> **Kind:** class + +```csharp +public sealed class ServerLogsService +``` + + +Provides the logic needed to present a read-only "live logs" room: it exposes the room identity, the role-based gate for who may join, and a best-effort reader that returns the most recent log entries from the active rolling Serilog file. Use this service when you need to show a live, read-only backlog of server log entries (rather than storing log lines as chat messages). + +## Remarks +This class centralizes the concerns required for a live log room: determining the configured room name and sender, enforcing the minimum role required to view logs, and extracting a focused backlog from the current log file on disk. It treats the file sink as the single source of truth (Serilog keeps the file open and rolls it), reads only the tail of the newest file up to a bounded byte size, and groups raw lines into logical entries by detecting timestamp-prefixed lines. ReadBacklog is resilient: any I/O or parsing problem yields an empty backlog rather than propagating an error. + +## Example +```csharp +// 'options' is an existing ServerLogsOptions instance configured for the server. +var service = new ServerLogsService(options); + +// Check whether a user role may view/join the live logs room +if (service.CanView(userRole)) +{ + // Read the most recent backlog entries (best-effort; may be empty on error) + var backlog = service.ReadBacklog(); + foreach (var entry in backlog) + { + // LogBacklogEntry exposes a timestamp and the concatenated content + Console.WriteLine($"{entry.Timestamp:O} {entry.Content}"); + } +} + +// Room identity helpers +var isLogs = service.IsLogsChannel("logs"); +var sender = ServerLogsService.SenderName; // "server" +``` + +## Notes +- ReadBacklog swallows all exceptions and returns an empty list on any I/O problem; callers must tolerate an empty backlog as a sign of transient failure or missing files. +- To avoid reading an arbitrarily large file, the reader seeks to the last TailReadBytes bytes; that can start the scan mid-entry, so the grouping logic optionally drops leading continuation lines when the tail was seeked. +- The FileStream is opened with FileShare.ReadWrite | FileShare.Delete because the Serilog file sink typically keeps the file open for writing and may roll it; the service reads concurrently without taking exclusive locks. + +--- + +## LogBacklogEntry +> **File:** `src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs` +> **Kind:** record + +```csharp +public record LogBacklogEntry(DateTimeOffset Timestamp, string Content) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Timestamp` | `DateTimeOffset` | — | +| `Content` | `string` | — | + + +LogBacklogEntry is a tiny, immutable data container that models a single backlog item read from the server log file. It captures the timestamp of the original log line via Timestamp and the associated log text in Content, which may include the initial line plus any continuation lines (such as exception stack traces) that followed it. Use this type when you need to treat a complete backlog segment as a unit, instead of handling raw lines individually; it’s especially helpful for grouping, displaying, or analyzing backlog entries after parsing. + +## Remarks +Because LogBacklogEntry is a record, it benefits from value-based equality and concise deconstruction, making it easy to compare backlog entries or to extract the fields in pattern-matching. The Content field holds a multi-line string that includes the initial line and any continuation text that followed it; consumers should be aware that the entry may span multiple lines. This type is commonly produced by the server log reader (e.g., ServerLogsService) when assembling backlog entries from the log file, serving as a stable data carrier between parsing and presentation layers. + +## Notes +- When collecting backlog lines, ensure that each entry groups the initial timestamped line with its subsequent continuation lines exactly once; splitting or merging entries incorrectly can corrupt the log's temporal grouping. + + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs.md new file mode 100644 index 0000000..92297a6 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs.md @@ -0,0 +1,19 @@ +# ServerLogsSink + +> **File:** `src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs` +> **Kind:** class + +```csharp +public sealed class ServerLogsSink : ILogEventSink +``` + + +ServerLogsSink is a Serilog sink that feeds the live log room by buffering log events in a bounded channel and exposing them to the streaming pipeline without persisting them. It enforces a minimum log level, filters out internal sources to avoid feedback loops, and writes accepted events into a single-reader queue consumed by the live broadcast path. This sink thus serves as a lightweight, non-persistent conduit for real-time visibility of logging activity. + +## Remarks +The sink decouples log emission from the live broadcast pathway, providing backpressure via a bounded channel (capacity 512) with drop-oldest semantics to prevent unbounded memory growth. Internal pipeline events are culled by inspecting the SourceContext and excluding known internal prefixes, which prevents the log → broadcast → log feedback loop. By not writing to a database, the component prioritizes timely visibility for operators and clients over long-term auditing. + +## Notes +- When the channel is full, TryWrite may return false and the log event will be dropped, ensuring the application does not stall due to logging backpressure. +- The channel is configured with SingleReader = true, so there is a single consumer in the streaming path; additional readers would not receive the full event sequence. +- Only events that pass the MinLevel filter and do not originate from excluded internal sources are enqueued for broadcast. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs.md new file mode 100644 index 0000000..7ffa2b7 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs.md @@ -0,0 +1,48 @@ +# ServerLogsStreamService + +> **File:** `src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs` +> **Kind:** class + +```csharp +public sealed class ServerLogsStreamService : BackgroundService +``` + + +Streams queued log events to the live log room as ephemeral SignalR messages, never persisting them to the IRC gateway or a database, and with a guard against introducing new logging from the streaming path itself. It runs as a background service, ensuring the destination room exists before sending each event and recreating it if needed, so live viewers can always join the stream without manual intervention. + +## Remarks +This symbol acts as a thin, resilient bridge between the server-side log sink and the real-time chat hub. It separates the streaming path from log persistence, enforcing a no-log-from-stream policy to avoid feedback loops where streaming would itself generate more log lines. By lazily resolving the hub context, it avoids tight coupling during service construction and ensures the ChatHub context is available when streaming begins. The class also enforces room existence in a lightweight, interval-bounded way to tolerate transient room removal without blocking the live stream. + +## Notes +- The streaming path must never emit logs of its own activity; per-event logging is explicitly suppressed to prevent cascading streams. +- TryEnsureRoomAsync re-checks the room at most once per EnsureInterval (15 seconds) to balance responsiveness with avoiding repeated recreation attempts. +- Messages are formatted and then encrypted before sending; the client receives an encrypted payload and is responsible for decrypting it, mirroring the design that prioritizes privacy and transport safety. The public Format method is exposed for tests, reflecting a desire to validate formatting behavior in isolation. +- If room recreation fails, events are streamed to a group with no members until the next interval, ensuring that the streaming pipeline remains non-blocking and resilient to transient failures. + +## Example +- Not included: non-obvious usage from the signature; the behavior is exercised through the background streaming loop and the TryEnsureRoomAsync room-recovery logic. See the source for exact flow and state transitions. + +## Dependency APIs (verified signatures) +The REAL, parser-verified API surface of this symbol's collaborators: + +- MessageDto (src/EchoHub.Core/DTOs/ChatDtos.cs) +- Reader (src/EchoHub.Server/Services/ServerLogs/ServerLogsSink.cs) +- ServerLogsService (src/EchoHub.Server/Services/ServerLogs/ServerLogsService.cs) + - SenderName, RoomTopic, TimestampFormat, TailReadBytes + - ServerLogsService(ServerLogsOptions options) + - Options, IsLogsChannel, CanView(ServerRole) + - ReadBacklog(), GroupIntoEntries(`IReadOnlyList<string>`, bool, int) + - TryParseTimestamp(string, out DateTimeOffset, out string) +- HubContext (src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs) +- HubConstants (src/EchoHub.Core/Constants/HubConstants.cs) + - ChatHubPath, DefaultChannel, IrcConnectionIdPrefix, DefaultHistoryCount, MaxMessageLength + - MaxImageSizeBytes, MaxAudioFileSizeBytes, MaxFileSizeBytes, MaxAvatarSizeBytes + - MaxMessageNewlines, MaxAttachmentsPerMessage, MaxConsecutiveNewlines + - …and 7 more member(s) not shown + +## Symbol To Document +- Name: ServerLogsStreamService +- Kind: class +- File: src/EchoHub.Server/Services/ServerLogs/ServerLogsStreamService.cs +- Language: csharp +- ID: fe54ac96-642e-4dbe-af25-3d2559e01299 \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/SignalRBroadcaster.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/SignalRBroadcaster.cs.md new file mode 100644 index 0000000..998a5e9 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/SignalRBroadcaster.cs.md @@ -0,0 +1,20 @@ +# SignalRBroadcaster + +> **File:** `src/EchoHub.Server/Services/SignalRBroadcaster.cs` +> **Kind:** class + +```csharp +public class SignalRBroadcaster : IChatBroadcaster +``` + + +Implements IChatBroadcaster to deliver chat events to SignalR-connected clients (via an `IHubContext<ChatHub, IEchoHubClient>`). Use this implementation when the application should push messages, presence updates, channel changes and moderation events to SignalR clients; it routes events to groups, specific clients, or all connected SignalR clients as appropriate. + +## Remarks +This class adapts the generic chat-broadcasting contract to SignalR: it resolves an IHubContext lazily from an IServiceProvider and uses the ChatHub/IEchoHubClient surface to send notifications. It cooperates with a PresenceTracker to map channel lists to active SignalR connection ids and intentionally filters out connections belonging to the IRC gateway. The implementation keeps broadcasting logic simple (group vs. all vs. specific clients) and relies on SignalR's client invocation Tasks for async behavior. + +## Notes +- The implementation treats connection IDs prefixed with "irc-" as non-SignalR (IRC gateway) and excludes or ignores those ids in several methods; callers must follow that convention if mixing IRC and SignalR connections. +- SendMessageToChannelAsync intentionally ignores the excludeConnectionId parameter (comment: SignalR clients render their own message echo). For selective exclusion of a SignalR connection use SendUserJoinedAsync (which excludes non-IRC ids) or other targeted methods that call GroupExcept/Clients. +- SendUserStatusChangedAsync will return Task.CompletedTask when no SignalR connections are found for the provided channels — callers should expect no-op behavior in that case. +- HubContext is cached in a private field after first resolution from IServiceProvider; the lazy resolution avoids constructor-time resolution (useful to prevent dependency cycles) and subsequent accesses reuse the same IHubContext instance. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/SpamGuard.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/SpamGuard.cs.md new file mode 100644 index 0000000..afdb799 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/SpamGuard.cs.md @@ -0,0 +1,99 @@ +# SpamGuard.cs + +> **Source:** `src/EchoHub.Server/Services/SpamGuard.cs` + +## Contents + +- [SpamGuard](#spamguard) +- [SpamVerdict](#spamverdict) +- [SpamVerdictKind](#spamverdictkind) + +--- + +## SpamGuard +> **File:** `src/EchoHub.Server/Services/SpamGuard.cs` +> **Kind:** class + +```csharp +public sealed class SpamGuard +``` + + +An in-memory, per-user spam protection component used by the server to enforce rate limits and duplicate-content rules across all ingress protocols (SignalR, IRC, etc.). SpamGuard centralizes checks for message sends, channel joins and channel creations so the same limits apply regardless of how a user interacts with the system. Its state is process-local (not persisted) and it delegates configuration to the supplied SpamOptions; the Enabled property exposes whether checks are active. + +## Remarks +SpamGuard exists to provide a single place for applying and counting spam-related events so different services (for example ChatService for messages/joins and ChannelService for channel creation) share the same view of a user's recent activity and violations. It keeps compact per-user state (queues of timestamps and a small duplicate-detection cache) and prunes stale entries lazily to avoid unbounded memory growth on busy servers. The class performs all checks under a private lock, so callers do not need to synchronize access; moderators (role >= ServerRole.Mod) are exempted from checks. + +## Notes +- State is process-local and not persisted: restarts or multi-process deployments will reset per-user counters; auto-mutes are recorded in the normal mute store (outside this class). +- Time sources default to DateTimeOffset.UtcNow but can be overridden via the optional nowOverride parameter (useful for deterministic testing). +- Flood detection counts every attempt (including retries), and uses a sliding window configured via SpamOptions (Prune before enqueueing and compare against MaxMessagesPerWindow). +- Duplicate detection compares trimmed, case-insensitive content to the immediately previous message only (back-to-back duplicates); RepeatCount is incremented for consecutive repeats and compared to MaxDuplicateMessages. +- Only rejected actions are recorded as violations for escalation; a non-rejected (clean) message cannot by itself trigger an auto-mute. The escalation logic (violations -> SpamVerdictKind.AutoMute) is evaluated only on rejected messages. + +--- + +## SpamVerdict +> **File:** `src/EchoHub.Server/Services/SpamGuard.cs` +> **Kind:** record + +```csharp +public readonly record struct SpamVerdict(SpamVerdictKind Kind, string? Reason = null, TimeSpan MuteDuration = default) +{ + public static readonly SpamVerdict Allowed = new(SpamVerdictKind.Allowed); +} +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Kind` | `SpamVerdictKind` | — | +| `Reason` | `string?` | `null` | +| `MuteDuration` | `TimeSpan` | `default` | + + +SpamVerdict is an immutable value-type that conveys the outcome of a spam check. It carries a Kind from SpamVerdictKind to describe the verdict, an optional Reason for explaining the result, and a MuteDuration indicating how long to suppress further messages when applicable. Defined as a readonly record struct, it benefits from value-based equality and guarantees immutability across boundaries. A convenient static instance, SpamVerdict.Allowed, represents the common case where a message passes spam checks without penalty. + +## Remarks +Because the verdict is packaged as a single object, this abstraction lets the rest of the system reason about spam results without ad-hoc boolean flags scattered through the code. It fits into the SpamGuard workflow by serving as a single, transportable payload that downstream components can inspect via Kind and optionally read the Reason or respect the MuteDuration. The immutability of the type helps prevent accidental mutations once a verdict has been created. + +## Example +```csharp +// Common usage: treat messages as allowed by the spam guard +var verdict = SpamVerdict.Allowed; +``` + +## Notes +- Reason is nullable; when present, it should be used for diagnostics or logs rather than for control flow. If you need extra context, supply Reason; otherwise leave it null. +- MuteDuration defaults to TimeSpan.Zero. To mute a user or channel for a period, provide a non-zero duration. +- SpamVerdict.Allowed is a convenient singleton for the common allowed case, but it does not encode a Reason or a non-zero MuteDuration. If you need those metadata, construct a new SpamVerdict explicitly. + +--- + +## SpamVerdictKind +> **File:** `src/EchoHub.Server/Services/SpamGuard.cs` +> **Kind:** enum + +```csharp +public enum SpamVerdictKind +{ + Allowed, + Rejected, + + AutoMute, +} +``` + + +SpamVerdictKind enumerates the possible outcomes of a spam evaluation. It is used by enforcement logic to decide whether to allow, reject, or mute a user based on the spam check; AutoMute indicates the caller should apply a timed mute. + +## Remarks +By centralizing these verdicts, the codebase can route enforcement consistently without scattering string literals or magic numbers. The AutoMute value communicates a specific consequence (a timed mute) that callers should implement, decoupling the decision from the actual enforcement mechanism. This abstraction helps evolve spam-policy over time while keeping evaluation and enforcement loosely coupled. + +## Notes +- AutoMute carries no duration or scope; the enforcement layer must supply the mute length and target(s). +- There is no payload attached to the verdict; if more context is needed (e.g., risk score, user ID), pass it separately alongside the verdict. +- Be mindful when updating this enum; adding values requires updating all readers to handle new cases. + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md new file mode 100644 index 0000000..f3b83a4 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs.md @@ -0,0 +1,75 @@ +# ServerStatsCollector.cs + +> **Source:** `src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs` + +## Contents + +- [ServerStatsCollector](#serverstatscollector) +- [StatsCounters](#statscounters) + +--- + +## ServerStatsCollector +> **File:** `src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs` +> **Kind:** class + +```csharp +public sealed class ServerStatsCollector +``` + + +ServerStatsCollector is a thread-safe, in-memory accumulator for server activity counters that have no natural database timestamp (connections, disconnections, kicks, bans, and peak concurrency). It updates counters via lock-free increments and uses a periodic SnapshotAndReset to emit a windowed StatsCounters and prepare the next window, including resetting the peak to the current online count. + +## Remarks + +Because it is registered as a singleton, multiple threads can record events without blocking. The class uses Interlocked and Volatile to implement a lock-free maximum-tracking algorithm for PeakOnline; SnapshotAndReset atomically drains all counters and resets PeakOnline to the provided onlineNow, which defines the starting point for the next window. This design favors low-latency updates in hot paths while deferring aggregation to the reporting window. + +## Notes + +- The next window's PeakOnline baseline is reset to the supplied onlineNow; if that baseline is lower than the actual concurrency at snapshot time, the subsequent peak may undercount. +- SnapshotAndReset resets the per-window counters to zero (except PeakOnline, which is reset to onlineNow); ensure you call it on the cadence that matches your reporting window to align with dashboards. + +--- + +## StatsCounters +> **File:** `src/EchoHub.Server/Services/Stats/ServerStatsCollector.cs` +> **Kind:** record + +```csharp +public readonly record struct StatsCounters( + long Connections, + long Disconnections, + long Kicks, + long Bans, + int PeakOnline) +``` + +**Parameters:** + +| Parameter | Type | Default | +|-----------|------|---------| +| `Connections` | `long` | — | +| `Disconnections` | `long` | — | +| `Kicks` | `long` | — | +| `Bans` | `long` | — | +| `PeakOnline` | `int` | — | + + +StatsCounters is an immutable snapshot of the counters held by ServerStatsCollector. It captures the total connections, disconnections, kicks, bans, and the peak online count at a single moment, enabling safe sharing and logging without mutating the underlying counters. + +## Remarks +StatCounters uses a readonly record struct to provide value semantics, meaning two instances with the same values compare equal and it can be passed by value without side effects. It is intended to be produced by the ServerStatsCollector and consumed by telemetry, dashboards, or loggers that need a stable view of current activity. Because it is immutable, readers can snapshot and transport it across threads without additional synchronization concerns. + +## Example +```csharp +// Create a snapshot of current counters +var snapshot = new StatsCounters(Connections: 1024, Disconnections: 64, Kicks: 3, Bans: 0, PeakOnline: 128); + +// Deconstruct to access individual values +var (connections, disconnections, kicks, bans, peakOnline) = snapshot; +``` + +## Dependencies +- ServerStatsCollector + +--- \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs.md new file mode 100644 index 0000000..e82ae0b --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs.md @@ -0,0 +1,19 @@ +# ServerStatsReportService + +> **File:** `src/EchoHub.Server/Services/Stats/ServerStatsReportService.cs` +> **Kind:** class + +```csharp +public sealed class ServerStatsReportService : BackgroundService +``` + + +ServerStatsReportService is a background task that periodically snapshots server activity over the current reporting window, logs the snapshot as pretty-printed JSON (visible in the live server-logs room), and persists a ServerStatsReport to the database for historical trend analysis. The cadence and retention are controlled by StatsOptions; if IntervalHours is non-positive the service uses a 6-hour default. + +## Remarks +To achieve this, the service reads the online user count from PresenceTracker, captures in-memory statistics from ServerStatsCollector, and then opens a scoped EchoHubDbContext to compute metrics such as messages sent, active members, files uploaded, and new users within the reporting window. A fresh DI scope is created per report to ensure proper EF Core lifetimes and isolation between reports. The reporting window is defined by _periodStart and periodEnd to align live counters with database-derived metrics, ensuring the report reflects the same time span across in-memory and persisted data. The pretty-printed JSON log enhances operational visibility by surfacing structured data in the logs. + +## Notes +- The background loop honors cancellation by awaiting Task.Delay with the provided CancellationToken and catching OperationCanceledException to exit promptly. +- IntervalHours is validated: non-positive values fall back to 6 hours, and the interval is floored at 1 second to avoid a spinning loop. +- Each report uses its own DbContext scope (via _scopeFactory.CreateScope()) to query the database and persist the resulting ServerStatsReport, ensuring clean lifetimes and minimal cross-report contention. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Services/UserService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Services/UserService.cs.md new file mode 100644 index 0000000..28ea17d --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Services/UserService.cs.md @@ -0,0 +1,104 @@ +# UserService + +> **File:** `src/EchoHub.Server/Services/UserService.cs` +> **Kind:** class + +*Figure: How UserService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +Start["Start RegisterUserAsync"] +Start --> CheckEmpty +CheckEmpty["Check username and password not empty"] +CheckEmpty -->|"missing"| FailMissing +CheckEmpty -->|"present"| CheckUsernameRegex + +FailMissing["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;Username and password are required.#quot;)"] + +CheckUsernameRegex["Validate username with ValidationConstants.UsernameRegex()"] +CheckUsernameRegex -->|"invalid"| FailUsernameRegex +CheckUsernameRegex -->|"valid"| CheckPwdMin + +FailUsernameRegex["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;Username must be 3-50 characters and contain only letters, digits, underscores, or hyphens.#quot;)"] + +CheckPwdMin["Check password length >= 6"] +CheckPwdMin -->|"too short"| FailPwdShort +CheckPwdMin -->|"ok"| CheckPwdMax + +FailPwdShort["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;Password must be at least 6 characters.#quot;)"] + +CheckPwdMax["Check password length <= ValidationConstants.MaxPasswordLength"] +CheckPwdMax -->|"too long"| FailPwdLong +CheckPwdMax -->|"ok"| Normalize + +FailPwdLong["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;Password must not exceed ValidationConstants.MaxPasswordLength characters.#quot;)"] + +Normalize["Normalize username (ToLowerInvariant and Trim)"] +Normalize --> CheckReserved + +CheckReserved["Compare normalized username to UsersController.DeletedUserName"] +CheckReserved -->|"reserved"| FailReserved +CheckReserved -->|"not reserved"| CreateScope + +FailReserved["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;This username is reserved.#quot;)"] + +CreateScope["Create scope and get EchoHubDbContext from _scopeFactory"] +CreateScope --> CheckExists + +CheckExists["Check if db.Users.AnyAsync(u => u.Username == normalizedUsername)"] +CheckExists -->|"exists"| FailAlreadyExists +CheckExists -->|"not exists"| CheckIsFirstUser + +FailAlreadyExists["Return UserOperationResult.Fail(UserError.AlreadyExists, #quot;Username is already taken.#quot;)"] + +CheckIsFirstUser["Determine isFirstUser = !await db.Users.AnyAsync()"] +CheckIsFirstUser -->|"first user"| CreateUser +CheckIsFirstUser -->|"not first"| RegistrationGate + +RegistrationGate["Check RegistrationMode (open / invite / closed)"] +RegistrationGate -->|"closed"| FailRegistrationClosed +RegistrationGate -->|"invite"| TryInvite +RegistrationGate -->|"open"| CreateUser + +FailRegistrationClosed["Return UserOperationResult.Fail(UserError.ValidationFailed, #quot;Registration is closed on this server.#quot;)"] + +TryInvite["Call TryConsumeInviteAsync(db, inviteCode)"] +TryInvite -->|"invite error"| FailInviteError +TryInvite -->|"ok"| CreateUser + +FailInviteError["Return UserOperationResult.Fail(UserError.ValidationFailed, inviteError)"] + +CreateUser["Create new User instance (Id = Guid.NewGuid(), set fields)"] +``` + +```csharp +public class UserService : IUserService +``` + + +Implements user-account operations for the server, most notably account registration. Use this concrete IUserService implementation when you need the server-backed behavior: configuration-driven registration modes (open / invite / closed), automatic owner bootstrap for the very first account, username/password validation, reserved-name checks, and password hashing before persisting users. + +## Remarks +UserService is the server-side implementation of IUserService and is responsible for safe, policy-driven user creation. It reads the registration policy from IConfiguration (Server:Registration), uses an IServiceScopeFactory to create a scoped EchoHubDbContext per operation (so the service can be used from different DI lifetimes), and enforces validation rules from ValidationConstants. The very first account created on a fresh database is always promoted to ServerRole.Owner to allow bootstrapping an administration account. Invite consumption (when registration is in "invite" mode) is performed via an atomic/guarded update to avoid races when two registrations attempt to use the last invite simultaneously. + +## Example +```csharp +// Typical usage from an async context where `userService` is resolved from DI +var result = await userService.RegisterUserAsync("alice", "s3cretP@ss", displayName: "Alice"); +if (result.IsSuccess) +{ + var profile = result; // UserOperationResult.Success wraps the created UserProfileDto + // proceed with signed-in flow +} +else +{ + // registration failed; map user-visible error to response +} +``` + +## Notes +- Username handling: the service normalizes usernames by trimming and lower-casing; a specific reserved name (UsersController.DeletedUserName) is rejected. +- The first user bypasses the registration gate and becomes ServerRole.Owner — this is intentional so a fresh server can be bootstrapped. +- Passwords are hashed using BCrypt.Net.BCrypt.HashPassword before being stored; there is no exposed mechanism here to change the hash algorithm. +- Invite consumption uses a guarded database update to prevent two concurrent registrations from both consuming the last available use of a code; if invite validation fails, RegisterUserAsync returns a validation failure with the invite error message. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md new file mode 100644 index 0000000..f6262a2 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md @@ -0,0 +1,69 @@ +# DataMigrationService + +> **File:** `src/EchoHub.Server/Setup/DataMigrationService.cs` +> **Kind:** class + +*Figure: How DataMigrationService works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB +Start["Start"] +Scope["Create scope and resolve EchoHubDbContext"] +EnsureDefault["Call EnsureDefaultChannelsPublicAsync(EchoHubDbContext)"] +QueryGeneral["Query Channel where Name == HubConstants.DefaultChannel"] +CheckGeneral{"Channel found and Channel.IsPublic == false?"} +MarkPublic["Set Channel.IsPublic = true and save EchoHubDbContext"] +SkipMark["No change"] +MigrateAnsi["Call MigrateAnsiMessagesAsync(EchoHubDbContext)"] +QueryImages["Load messages where Type == MessageType.Image"] +FilterAnsi["Filter messages where Content contains ESC byte"] +CheckCount{"toMigrate.Count == 0?"} +LogFound["Log found messages and prepare migration"] +ConvertLoop["For each message: convert ANSI to color tags and update Content if changed"] +CheckModified{"modified > 0?"} +SaveModified["Save changes to EchoHubDbContext and log migrated count"] +SkipSave["No modifications to save"] +CallEmbed["Call MigrateEmbedJsonToArrayAsync to migrate EmbedDto JSON to array"] +CallAttach["Call MigrateLegacyAttachmentsAsync to migrate Attachment/AttachmentKind"] +CallAdmins["Call EnsureConfiguredAdminsAsync to ensure ServerRole admins configured"] +End["End"] + +Start --> Scope +Scope --> EnsureDefault +EnsureDefault --> QueryGeneral +QueryGeneral --> CheckGeneral +CheckGeneral -->|"Yes"| MarkPublic +CheckGeneral -->|"No"| SkipMark +MarkPublic --> MigrateAnsi +SkipMark --> MigrateAnsi +MigrateAnsi --> QueryImages +QueryImages --> FilterAnsi +FilterAnsi --> CheckCount +CheckCount -->|"Yes"| CallEmbed +CheckCount -->|"No"| LogFound +LogFound --> ConvertLoop +ConvertLoop --> CheckModified +CheckModified -->|"Yes"| SaveModified +CheckModified -->|"No"| SkipSave +SaveModified --> CallEmbed +SkipSave --> CallEmbed +CallEmbed --> CallAttach +CallAttach --> CallAdmins +CallAdmins --> End +``` + +```csharp +public static partial class DataMigrationService +``` + + +Runs a set of application-level data migrations that update content and small structural pieces of the database when the server starts. Call this during application startup (once) to apply idempotent, content-format migrations such as making the default channel public, converting legacy ANSI art to printable color tags, folding legacy attachment columns into the Attachments table, and other one-off data fixes. + +## Remarks +This class centralizes lightweight, code-driven migrations that operate on row data and content formats rather than schema changes (which belong in EF migrations). Each migration method scopes a DbContext from the provided IServiceProvider and performs targeted, idempotent updates where possible (for example, legacy single-attachment rows are only migrated when no Attachment rows exist). Conversions that change message content (like ANSI→color tags) are deterministic and saved back with SaveChangesAsync. + +## Notes +- AnsiToColorTags only recognizes/reset sequences produced as "\x1b[38;2;R;G;Bm", "\x1b[48;2;R;G;Bm" and the reset "\x1b[0m"; other ANSI sequences are left unchanged. +- MigrateAnsiMessagesAsync only examines messages of type Image and checks for the ESC (0x1B) character before attempting conversion, reducing unnecessary work. +- Each migration method calls SaveChangesAsync only when there are actual modifications; however RunAsync itself is asynchronous and can be long-running depending on DB size—callers should await it during startup and avoid calling concurrently. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Setup/DatabaseSetup.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Setup/DatabaseSetup.cs.md new file mode 100644 index 0000000..bf74d26 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Setup/DatabaseSetup.cs.md @@ -0,0 +1,18 @@ +# DatabaseSetup + +> **File:** `src/EchoHub.Server/Setup/DatabaseSetup.cs` +> **Kind:** class + +```csharp +public static class DatabaseSetup +``` + + +DatabaseSetup is a startup bootstrapper that ensures the EchoHub database is ready by applying migrations, seeding a default channel, and running data migrations. It creates a scoped DbContext and logger, migrates the database, seeds a default channel when missing, and then triggers data migrations; if a legacy SQLite database is detected (no migrations history but legacy tables exist), it backs up the current file and recreates the database to enable the modern migration path. + +## Remarks +DatabaseSetup centralizes the one-time bootstrap concerns for the database, isolating migration, seeding, and legacy-handling logic from the rest of the startup flow. It relies on EF Core’s migration pipeline and coordinates with DataMigrationService to perform data transformations (e.g., ANSI-to-color-tag conversions) and to ensure essential defaults (like the General channel) exist, aligning the persisted state with the application's current expectations. + +## Notes +- Legacy-path destructive behavior: when a legacy database is detected, the code creates a timestamped backup and then deletes the database so migrations can proceed against a fresh schema. This trade-off is intentional to enable a safe migration path from older schemas. +- Startup-time invocation: the initialization runs at application startup and establishes its own service scope; avoid multiple concurrent invocations to prevent duplicate work or conflicting migrations during a single process lifecycle. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Server/Setup/FirstRunSetup.cs.md b/docs/auriondocs/Code/src/EchoHub.Server/Setup/FirstRunSetup.cs.md new file mode 100644 index 0000000..2460196 --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Server/Setup/FirstRunSetup.cs.md @@ -0,0 +1,25 @@ +# FirstRunSetup + +> **File:** `src/EchoHub.Server/Setup/FirstRunSetup.cs` +> **Kind:** class + +```csharp +public static class FirstRunSetup +``` + + +FirstRunSetup is a small bootstrap utility that guarantees a usable appsettings.json and seeds it with cryptographic secrets on first run. On startup, it copies appsettings.example.json to appsettings.json if the destination is missing, then ensures a valid JWT secret and an encryption key exist by generating them when needed. + +## Remarks +Centralizing this bootstrap logic keeps startup concerns cohesive and makes the secrets generation deterministic and auditable. It relies on cryptographically secure RNG and writes back to the configuration file with indentation for human readability, while tolerating JSON comments during read. + +## Example +```csharp +// Typical usage during application startup +FirstRunSetup.EnsureAppSettings(); +``` + +## Notes +- Idempotent: existing Jwt.Secret or Encryption.Key are preserved; new values are generated only if missing or marked as CHANGE_ME. +- Path dependency: relies on the current working directory (the project root). In non-standard deployments, you may need to adjust the working directory or extend the helper to accept explicit paths. +- Silent on parse failure: if the JSON cannot be parsed (root is null), the method returns without writing changes. \ No newline at end of file diff --git a/docs/auriondocs/Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md b/docs/auriondocs/Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md new file mode 100644 index 0000000..0d5627e --- /dev/null +++ b/docs/auriondocs/Code/src/EchoHub.Tests/Irc/TestHelpers.cs.md @@ -0,0 +1,194 @@ +# TestHelpers.cs + +> **Source:** `src/EchoHub.Tests/Irc/TestHelpers.cs` + +## Contents + +- [FakeChannelService](#fakechannelservice) +- [FakeChatService](#fakechatservice) +- [FakeEncryptionService](#fakeencryptionservice) +- [FakeUserService](#fakeuserservice) +- [TestDuplexStream](#testduplexstream) +- [TestIrcConnectionFactory](#testircconnectionfactory) + +--- + +## FakeChannelService +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal sealed class FakeChannelService : IChannelService +``` + + +A lightweight test double that implements IChannelService by returning pre-configured results for each operation. Use this in unit tests to simulate success, failure, or specific payloads from channel-related operations without wiring up real storage or network dependencies. + +## Remarks +The fake exposes properties you set from tests (for example CreateResult, TopicResult, ChannelListToReturn, MembershipResult, CryptoToReturn, KeyEnvelopeToReturn, ChannelMetaToReturn, SystemChannelToReturn and others). Most methods return Task.FromResult(...) of those properties or a default failure (ChannelOperationResult.Fail(ChannelError.ValidationFailed, "Not configured")) when a result property has not been provided. EnsureSystemChannelAsync returns the configured SystemChannelToReturn or a minimal default ChannelDto (with a new Guid and IsSystem = true) when not configured. + +## Example +```csharp +// Arrange: create the fake and configure the CreateChannelAsync result +var fake = new FakeChannelService(); +var created = new ChannelDto(Guid.NewGuid(), "my-channel", "topic", false, 0, DateTimeOffset.UnixEpoch, false, false, false); +fake.CreateResult = ChannelOperationResult.Success(created); + +// Act: call the service (synchronously here via Task.Result for brevity in tests) +var result = fake.CreateChannelAsync(Guid.NewGuid(), "my-channel", "topic", isPublic: true).Result; + +// Assert: the configured success is returned +if (!result.IsSuccess) throw new Exception("expected success"); +``` + +## Notes +- The fake uses Task.FromResult and no asynchronous I/O; it's intended only for synchronous-style unit tests and will not reproduce concurrency or latency characteristics of a real implementation. +- If you forget to set a specific "Result" property (e.g. CreateResult, UpdateTopicResult, RekeyResult), the fake returns ChannelOperationResult.Fail(ChannelError.ValidationFailed, "Not configured"). +- EnsureSystemChannelAsync will fabricate a new ChannelDto with a fresh Guid when SystemChannelToReturn is not set; tests that rely on a stable id should explicitly set SystemChannelToReturn. + +--- + +## FakeChatService +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal sealed class FakeChatService : IChatService +``` + + +A test double that implements IChatService for use in unit tests. It records calls (connected users, disconnections, joins/leaves, sent messages, status updates) into public lists and returns configurable, pre-seeded results (history, errors, online users, channels). Reach for this when you need a deterministic, inspectable chat service in tests rather than the real implementation. + +## Remarks +FakeChatService exists solely to make tests observable and controllable: callers can assert that particular chat operations were invoked by inspecting the public lists, and tests can control what operations return by setting the configurable properties (HistoryToReturn, JoinError, SendMessageError, etc.). It does not perform any real validation or I/O and intentionally records inputs (including join passwords) so tests can verify them. + +## Example +```csharp +// Typical usage in a unit test +var svc = new FakeChatService(); + +// Simulate a user connecting +await svc.UserConnectedAsync("conn-1", Guid.NewGuid(), "alice"); +// svc.ConnectedUsers now contains "alice" + +// Simulate joining a channel (password may be null) +var (history, error, passwordRequired) = await svc.JoinChannelAsync("conn-1", Guid.NewGuid(), "alice", "#room", null); +// svc.JoinedChannels contains ("#room", "alice") and svc.JoinKeys contains the password passed + +// Simulate sending a message and configure an error result +svc.SendMessageError = "rate-limited"; +var sendErr = await svc.SendMessageAsync(Guid.NewGuid(), "alice", "#room", "hello world"); +// sendErr == "rate-limited" and svc.SentMessages contains ("#room", "hello world") +``` + +## Notes +- The public list properties are mutable and intended for test inspection; tests should reset or recreate the FakeChatService between cases to avoid cross-test contamination. +- JoinChannelAsync records the supplied password into JoinKeys — this test double intentionally captures sensitive inputs for verification, so treat recorded passwords carefully in test logs. +- This implementation makes no concurrency guarantees; if tests exercise the fake from multiple threads you may encounter race conditions. + +--- + +## FakeEncryptionService +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal sealed class FakeEncryptionService : IMessageEncryptionService +``` + + +It is a test double that mimics encrypted content by prefixing plaintext with a fixed marker, allowing tests to verify code paths that handle encrypted data without introducing real cryptography. + +## Remarks +This internal, sealed class provides a deterministic, reversible "encryption" scheme for testing scenarios that depend on encrypted strings. By implementing IMessageEncryptionService, it enables tests to validate integration points that consume or produce ciphertext without relying on real cryptographic routines. The EncryptDatabaseEnabled property being true signals that encryption should be considered active in the test database layer. Use this class when you need predictable, fast behavior in unit tests that exercise encryption-related code paths. + +## Example +```csharp +var service = new FakeEncryptionService(); +string ciphertext = service.Encrypt("hello"); // "$ENC$hello" +string plaintext = service.Decrypt(ciphertext); // "hello" + +string? nullCipher = service.EncryptNullable(null); // null +string? nullPlain = service.DecryptNullable(null); // null +string? recovered = service.DecryptNullable(ciphertext); // "hello" +``` + +## Notes +- This is a fake encryption shim for tests; it is not cryptographically secure. +- Decrypt only removes the prefix if present; non-prefixed content is returned unchanged. +- EncryptNullable/DecryptNullable are null-safe helpers that simplify test code. + +--- + +## FakeUserService +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal sealed class FakeUserService : IUserService +``` + + +A lightweight test double of IUserService that records calls and returns pre-configured results. Use this in unit or integration tests when you need to simulate authentication, registration, and profile lookups without exercising the real user backend. + +## Remarks +This class exposes mutable properties (AuthResult, RegisterResult, ProfileToReturn) that callers set to control the behavior of the corresponding IUserService methods. It also records invite codes passed to RegisterUserAsync in RegisterInviteCodes so tests can assert which invite codes were used. The SuccessResult helper creates a typical successful UserOperationResult with a UserProfileDto for convenience; other operations (UpdateProfileAsync, SetAvatarAsync) are intentionally left to always return a NotFound failure to indicate they are not implemented in this fake. + +## Notes +- The fake is stateful: AuthResult, RegisterResult, ProfileToReturn and RegisterInviteCodes are mutable. Reset or recreate the FakeUserService between tests to avoid cross-test contamination. +- If AuthResult or RegisterResult are left null, AuthenticateUserAsync and RegisterUserAsync return default Fail results (InvalidCredentials and AlreadyExists respectively) with explanatory messages. +- UpdateProfileAsync and SetAvatarAsync always return a NotFound failure ("Not configured"). They are placeholders rather than working implementations. + +--- + +## TestDuplexStream +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal sealed class TestDuplexStream : Stream +``` + + +A lightweight in-memory duplex Stream intended for tests: it supplies readable bytes from a preloaded input buffer and captures all written bytes to a separate output buffer that can be inspected. Use this when you need to simulate a readable/writable stream (for example, feeding input to code that reads a Stream and asserting what that code wrote) without interacting with files or the console. + +## Remarks +This class models a unidirectional read buffer and a separate write buffer so consumers can read a fixed input and concurrently write output without interfering with each other. It intentionally implements only the Stream surface required by simple producers/consumers: reading delegates to an internal MemoryStream created from the provided input string; writing appends to a second MemoryStream. The stream is non-seekable to better emulate pipes or network streams and to discourage tests from relying on seeking behavior. + +## Notes +- The stream does not support seeking: Position, Length, Seek and SetLength all throw NotSupportedException. +- GetOutput trims a UTF-8 BOM from the captured bytes because StreamWriter may emit one; tests that rely on raw bytes should use _writeBuffer directly instead of GetOutput (the internal buffer is disposed on Dispose()). +- GetOutputLines splits on the Windows CRLF sequence ("\r\n") and removes empty entries; inputs using only "\n" will not be split by this helper. +- The class is intended for test use and does not provide synchronization; concurrent access from multiple threads is not guaranteed to be safe. + + +--- + +## TestIrcConnectionFactory +> **File:** `src/EchoHub.Tests/Irc/TestHelpers.cs` +> **Kind:** class + +```csharp +internal static class TestIrcConnectionFactory +``` + + +Creates a convenient factory for constructing IrcClientConnection instances that are wired to an in-memory TestDuplexStream, enabling deterministic unit tests of IRC-related behavior without a real network. Use Create to supply a set of incoming lines that the client will read from; the method returns both the constructed IrcClientConnection and the TestDuplexStream so you can inspect what the client writes. Use CreateAuthenticated to obtain a connection that is already registered and authenticated, with nickname/username and a UserId, so tests can focus on post-auth flow without performing login or handshake. + +## Remarks +TestIrcConnectionFactory centralizes test harness setup, reducing boilerplate in tests that exercise IRC server interaction. It returns both the connection and the stream to let tests feed input and observe output, including greeting lines or protocol messages. The authenticated variant preconfigures identity and flags (IsRegistered and IsAuthenticated) to simulate a fully connected client, enabling tests that assume a ready-to-use session. + +## Example +```csharp +// Example: raw connection with input lines +var (conn, stream) = TestIrcConnectionFactory.Create("PING :server", ":server 001 :Welcome"); + +// Example: authenticated connection +var (authConn, authStream) = TestIrcConnectionFactory.CreateAuthenticated(nickname: "alice"); +``` + +## Notes +- The factory creates a real TcpClient under the hood; the IrcClientConnection uses that client but all I/O is performed via the in-memory TestDuplexStream, so tests must dispose the resources (the stream and client) when finished to avoid leaks. +- CreateAuthenticated defaults nickname to "alice" and generates a new GUID for UserId if none is supplied; pass explicit values for deterministic testing. + +--- \ No newline at end of file diff --git a/docs/auriondocs/README.md b/docs/auriondocs/README.md new file mode 100644 index 0000000..6b11dd0 --- /dev/null +++ b/docs/auriondocs/README.md @@ -0,0 +1,48 @@ +# HueByte/EchoHub — Documentation + +> Continuously generated, source-verified documentation for **HueByte/EchoHub**, built from branch `master` at commit `4dcb480d`. Every page is derived from the code itself and cross-checked against the source before it ships. + +EchoHub is a client/server chat system that exposes an HTTP API implemented by multiple controllers and a realtime messaging surface via a hub (ChatHub), with client-side components for connecting and playback. The server hosts application services and background workers (e.g. file cleanup, data migrations) that implement business logic and maintenance tasks. Persistent state is stored in the Entity Framework DbContext (EchoHubDbContext) which is used by controllers and services. Clients interact with the server through the ApiClient and implement messaging callbacks against the IEchoHubClient contract. + +## Start here + +1. **[Architecture](Synthesis/Architecture.md)** — the system overview: what the components are, how they collaborate, and where to find each one. +2. **[Onboarding](Synthesis/Onboarding.md)** — a curated reading path through the codebase. Start here if you're new to the project. +3. **[Code reference](Code/index.md)** — per-file API documentation mirroring the source tree, one page per documented file. + +## Deep dives + +Cross-file guides on the themes that shape this codebase: + +- [API client and authentication](Synthesis/api-client-authentication.md) — This guide explains how the EchoHub client performs HTTP operations and manages authentication tokens, and it documents the DTOs the client uses when talking to the server. +- [Attachments and file transfers](Synthesis/attachments-transfer.md) — Outgoing attachments are staged in the UI, packaged as transport objects, and then coordinated through the app orchestrator into the live connection for transmission. +- [Clipboard utilities](Synthesis/clipboard-tools.md) — This guide describes the clipboard-focused utilities in the client: one helper that exposes file-list clipboard contents, another that normalizes image clipboard data into PNG bytes, and the UI entry points that call… +- [Command handling](Synthesis/command-handling.md) — This guide explains how user-entered slash commands move from text input into application behavior and network actions. +- [Encryption and room key management](Synthesis/encryption-roomkeys.md) — End-to-end encryption in the client is implemented as a few focused components: a runtime encryptor that mirrors the server format, a protector that encrypts per-channel room keys at rest, a store that binds persisted… +- [Real-time connection management](Synthesis/real-time-connection.md) — This guide explains how the client-side pieces manage a SignalR-based chat connection, surface server events to the UI, and carry message and attachment DTOs across those boundaries. +- [Theming and UI color management](Synthesis/ui-theming.md) — Theming and UI color management +- [Update management](Synthesis/update-management.md) — Update management + +## Recurring workflows + +Step-by-step templates for the patterns this codebase repeats, each grounded in real examples from the source: + +- [Adding a new controller](Synthesis/Workflows/controller.md) +- [Adding a new service](Synthesis/Workflows/service.md) + +## By the numbers + +- **128** documentation pages covering **128** source files +- **598** symbols documented and validated +- **22,133** lines of code analyzed +- Languages: C# (128) + +## How these docs are organized + +- **`Code/`** mirrors the repository's source tree one-to-one — `src/Foo.cs` is documented at `Code/src/Foo.cs.md`. +- **`Synthesis/`** holds knowledge derived *across* files: the architecture overview, onboarding path, topic deep-dives, and workflow templates. +- The set is regenerated as the code changes; drift between code and docs is detected and repaired automatically. + +--- + +*Generated by [AurionDocs](https://auriondocs.com) from `master` at commit `4dcb480d` on 2026-07-23 05:56 UTC.* diff --git a/docs/auriondocs/Synthesis/Architecture.md b/docs/auriondocs/Synthesis/Architecture.md new file mode 100644 index 0000000..41b9c47 --- /dev/null +++ b/docs/auriondocs/Synthesis/Architecture.md @@ -0,0 +1,147 @@ +# Architecture — HueByte/EchoHub + +> *Auto-synthesized from 598 documented symbols across 128 files on `master`.* + +## Topic Guides + +Deep-dives into cross-cutting concerns synthesized from the per-symbol corpus. + +- [API client and authentication](api-client-authentication.md) — How the EchoHub client authenticates with the server, handles tokens, and defines authentication DTOs. +- [Theming and UI color management](ui-theming.md) — Representing themes, color palettes, and runtime theme application. +- [Real-time connection management](real-time-connection.md) — Managing the SignalR hub connection lifecycle and connection state. +- [Encryption and room key management](encryption-roomkeys.md) — End-to-end encryption plumbing and secure handling of per-channel room keys. +- [Command handling](command-handling.md) — Slash-command parsing and dispatching command actions from UI and orchestrator. +- [Attachments and file transfers](attachments-transfer.md) — Staging and sending attachments in chat messages and coordinating outbound attachments. +- [Clipboard utilities](clipboard-tools.md) — Helpers for clipboard interactions: files and images. +- [Update management](update-management.md) — Data and update flow: backup prior to updates and update checks. + +## Architecture Diagram + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +flowchart TB + n0["src/EchoHub.Core/DTOs · ChatService (11 files)"] + n1["src/EchoHub.Client/Services · AppOrchestrator (14 files)"] + n2["src/EchoHub.Client/UI · MainWindow (18 files)"] + n3["src/EchoHub.Core/DTOs · ApiClient (10 files)"] + n4["src/EchoHub.Server · User (12 files)"] + n5["src/EchoHub.Core/DTOs · ChannelService (7 files)"] + n6["src/EchoHub.Server · Program (12 files)"] + n7["src/EchoHub.Client/Config (5 files)"] + n8["src/EchoHub.Client/UI · Channel (4 files)"] + n9["src/EchoHub.Core/DTOs · ChannelsController (2 files)"] + n10["src/EchoHub.Core/Models (5 files)"] + n0 -->|5| n10 + n0 -->|6| n4 + n0 -->|7| n6 + n0 -->|4| n7 + n0 -->|6| n8 + n1 -->|14| n0 + n1 -->|5| n2 + n1 -->|4| n3 + n1 -->|6| n4 + n1 -->|8| n7 + n1 -->|5| n8 + n2 -->|8| n0 + n2 -->|4| n4 + n3 -->|6| n0 + n3 -->|8| n4 + n3 -->|4| n9 + n4 -->|9| n3 + n5 -->|7| n0 + n5 -->|4| n4 + n5 -->|5| n8 + n6 -->|6| n0 + n6 -->|7| n4 + n9 -->|4| n4 + n9 -->|4| n5 +``` + +## System Overview +EchoHub is a client/server chat system that exposes an HTTP API implemented by multiple controllers and a realtime messaging surface via a hub (ChatHub), with client-side components for connecting and playback. The server hosts application services and background workers (e.g. file cleanup, data migrations) that implement business logic and maintenance tasks. Persistent state is stored in the Entity Framework DbContext (EchoHubDbContext) which is used by controllers and services. Clients interact with the server through the ApiClient and implement messaging callbacks against the IEchoHubClient contract. + +## Key Components +**Controllers** — HTTP API surface for client and administrative actions. Implemented by [`AuthController`](../Code/src/EchoHub.Server/Controllers/AuthController.cs.md), [`ChannelsController`](../Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md), [`FilesController`](../Code/src/EchoHub.Server/Controllers/FilesController.cs.md), [`InvitesController`](../Code/src/EchoHub.Server/Controllers/InvitesController.cs.md), [`ModerationController`](../Code/src/EchoHub.Server/Controllers/ModerationController.cs.md), [`ServerController`](../Code/src/EchoHub.Server/Controllers/ServerController.cs.md), [`UsersController`](../Code/src/EchoHub.Server/Controllers/UsersController.cs.md). + +**Services** — Application services implement business logic, file handling, background tasks, and utilities used by controllers and hubs. Implemented by [`ChannelService`](../Code/src/EchoHub.Server/Services/ChannelService.cs.md), [`ChatService`](../Code/src/EchoHub.Server/Services/ChatService.cs.md), [`FileStorageService`](../Code/src/EchoHub.Server/Services/FileStorageService.cs.md), [`FileCleanupService`](../Code/src/EchoHub.Server/Services/FileCleanupService.cs.md), and supporting utilities such as [`AsciiBannerService`](../Code/src/EchoHub.Core/Services/AsciiBannerService.cs.md), [`AudioPlaybackService`](../Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md), [`ClientEncryptionService`](../Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md), and [`DataMigrationService`](../Code/src/EchoHub.Server/Setup/DataMigrationService.cs.md). + +**Workers / Hubs** — Real-time messaging and hosted work are provided by SignalR-style hubs and background services; the primary realtime hub is implemented by [`ChatHub`](../Code/src/EchoHub.Server/Hubs/ChatHub.cs.md). + +**Data Access** — Persistent application state is managed via the Entity Framework DbContext used across services and controllers: [`EchoHubDbContext`](../Code/src/EchoHub.Server/Data/EchoHubDbContext.cs.md). + +**External Clients** — Client-side communication with the server is encapsulated by an HTTP/real-time client and the client contract. Implemented by [`ApiClient`](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) and the client interface [`IEchoHubClient`](../Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md). + +**Configuration** — Server runtime options and feature flags are defined in option classes used by services and integrations. Implemented by [`IrcOptions`](../Code/src/EchoHub.Server.Irc/IrcOptions.cs.md), [`ServerLogsOptions`](../Code/src/EchoHub.Server/Config/ServerLogsOptions.cs.md), [`SpamOptions`](../Code/src/EchoHub.Server/Config/SpamOptions.cs.md), [`StatsOptions`](../Code/src/EchoHub.Server/Config/StatsOptions.cs.md). + +**IRC integration** — IRC-related command handling and service wiring are provided by IRC support classes and extensions. Implemented by [`IrcServiceExtensions`](../Code/src/EchoHub.Server.Irc/IrcServiceExtensions.cs.md) and [`IrcCommandHandler`](../Code/src/EchoHub.Server.Irc/IrcCommandHandler.cs.md). + +**Core Contracts** — Domain and integration interfaces that define service boundaries and encryption abstractions. Implemented by [`IChannelService`](../Code/src/EchoHub.Core/Contracts/IChannelService.cs.md), [`IChatService`](../Code/src/EchoHub.Core/Contracts/IChatService.cs.md), [`IMessageEncryptionService`](../Code/src/EchoHub.Core/Contracts/IMessageEncryptionService.cs.md), and [`IUserService`](../Code/src/EchoHub.Core/Contracts/IUserService.cs.md). + +## Component Map + +*Subsystems below are structural clusters detected from the dependency graph — groups of symbols more densely wired to each other than to the rest of the codebase.* + +- **src/EchoHub.Client/UI · MainWindow** — 18 documented files +- **src/EchoHub.Client/Services · AppOrchestrator** — 14 documented files +- **src/EchoHub.Server · Program** — 12 documented files +- **src/EchoHub.Server · User** — 12 documented files +- **src/EchoHub.Core/DTOs · ChatService** — 11 documented files +- **src/EchoHub.Core/DTOs · ApiClient** — 10 documented files +- **src/EchoHub.Core/DTOs · ChannelService** — 7 documented files +- **src/EchoHub.Client/Config** — 5 documented files +- **src/EchoHub.Core/Models** — 5 documented files +- **src/EchoHub.Client/Themes** — 4 documented files +- **src/EchoHub.Client/UI · Channel** — 4 documented files +- **src/EchoHub.Server · ServerLogsStreamService** — 4 documented files +- *…and 11 more subsystem folders* + +### Components by Role + +**Configuration** +- `IrcOptions` — `src/EchoHub.Server.Irc/IrcOptions.cs` +- `ServerLogsOptions` — `src/EchoHub.Server/Config/ServerLogsOptions.cs` +- `SpamOptions` — `src/EchoHub.Server/Config/SpamOptions.cs` +- `StatsOptions` — `src/EchoHub.Server/Config/StatsOptions.cs` + +**Controllers** +- `AuthController` — `src/EchoHub.Server/Controllers/AuthController.cs` +- `ChannelsController` — `src/EchoHub.Server/Controllers/ChannelsController.cs` +- `FilesController` — `src/EchoHub.Server/Controllers/FilesController.cs` +- `InvitesController` — `src/EchoHub.Server/Controllers/InvitesController.cs` +- `ModerationController` — `src/EchoHub.Server/Controllers/ModerationController.cs` +- `ServerController` — `src/EchoHub.Server/Controllers/ServerController.cs` +- `UsersController` — `src/EchoHub.Server/Controllers/UsersController.cs` + +**Data Access** +- `EchoHubDbContext` — `src/EchoHub.Server/Data/EchoHubDbContext.cs` + +**Extensions** +- `IrcServiceExtensions` — `src/EchoHub.Server.Irc/IrcServiceExtensions.cs` + +**External Clients** +- `ApiClient` — `src/EchoHub.Client/Services/ApiClient.cs` +- `IEchoHubClient` — `src/EchoHub.Core/Contracts/IEchoHubClient.cs` + +**Handlers** +- `CommandHandler` — `src/EchoHub.Client/Commands/CommandHandler.cs` +- `IrcCommandHandler` — `src/EchoHub.Server.Irc/IrcCommandHandler.cs` + +**Realtime Hubs** +- `ChatHub` — `src/EchoHub.Server/Hubs/ChatHub.cs` + +**Services** +- `AsciiBannerService` — `src/EchoHub.Core/Services/AsciiBannerService.cs` +- `AudioPlaybackService` — `src/EchoHub.Client/Services/AudioPlaybackService.cs` +- `ChannelService` — `src/EchoHub.Server/Services/ChannelService.cs` +- `ChatService` — `src/EchoHub.Server/Services/ChatService.cs` +- `ClientEncryptionService` — `src/EchoHub.Client/Services/ClientEncryptionService.cs` +- `DataMigrationService` — `src/EchoHub.Server/Setup/DataMigrationService.cs` +- `FileCleanupService` — `src/EchoHub.Server/Services/FileCleanupService.cs` +- `FileStorageService` — `src/EchoHub.Server/Services/FileStorageService.cs` +- `IChannelService` — `src/EchoHub.Core/Contracts/IChannelService.cs` +- `IChatService` — `src/EchoHub.Core/Contracts/IChatService.cs` +- `IMessageEncryptionService` — `src/EchoHub.Core/Contracts/IMessageEncryptionService.cs` +- `IUserService` — `src/EchoHub.Core/Contracts/IUserService.cs` + +--- +*Generated by Aurion on 2026-07-23 05:56:01 UTC* diff --git a/docs/auriondocs/Synthesis/Onboarding.md b/docs/auriondocs/Synthesis/Onboarding.md new file mode 100644 index 0000000..d425cd3 --- /dev/null +++ b/docs/auriondocs/Synthesis/Onboarding.md @@ -0,0 +1,29 @@ +# Onboarding — HueByte/EchoHub + +> *A curated reading path through this codebase for new contributors. Work through the stops in order.* + +This reading path gets a new team member from zero to a place where they can run the app and make a small contribution. Read the short architecture overview first to understand the system's collaboration pattern, then inspect the entry points to see how the pieces are wired; from there follow a single request through the ingress layer into the services and state so you can start making safe, focused changes. + +## Stop 1: What this project is +At this stop skim the auto-generated system description to learn the overall collaboration pattern and where state is owned; the document also highlights the main components and their responsibilities. Start by opening [Architecture](Architecture.md) to pick up the big-picture boundaries and the primary data stores so later code-level reads map to that conceptual model. + +## Stop 2: Where execution starts +Read the two Program entry points to see how the client and server are bootstrapped, which early runtime concerns are wired, and what cross-cutting services are registered. Inspect the client [Program.cs](../Code/src/EchoHub.Client/Program.cs.md) to see startup tasks like rollback handling, permission checks, configuration provisioning, logging setup, and PATH preparation; then open the server [Program.cs](../Code/src/EchoHub.Server/Program.cs.md) to see how configuration, logging, data access, authentication, service registrations and the ASP.NET Core pipeline are arranged. + +## Stop 3: Where requests come in +Trace a single end-to-end interaction by following the client command entry, the server HTTP controller, and the real-time hub used for chat. Read the client [CommandHandler.cs](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) to learn how user commands are emitted, then the server [UsersController.cs](../Code/src/EchoHub.Server/Controllers/UsersController.cs.md) to see the API surface that handles user-related requests, and finally the SignalR [ChatHub.cs](../Code/src/EchoHub.Server/Hubs/ChatHub.cs.md) to understand real-time message routing and authorization checks. + +## Stop 4: Where the business logic lives +Drill into the substantive services that perform work for the client: network calls, audio, encryption, and backup orchestration. Read the client [ApiClient.cs](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) that manages HTTP requests and disposal, the [AudioPlaybackService.cs](../Code/src/EchoHub.Client/Services/AudioPlaybackService.cs.md) that handles playback concerns, the [ClientEncryptionService.cs](../Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md) which implements IMessageEncryptionService for message protection, the [NotificationSoundService.cs](../Code/src/EchoHub.Client/Services/NotificationSoundService.cs.md) for user-facing alerts, and the [UpdateBackupService.cs](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) which is involved in BackupInfo serialization and backup flows. + +## Stop 5: Where state lives +Look at the code that owns connection state, persisted backups, and the commands that drive application state changes. Revisit [CommandHandler.cs](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) to understand the commands that mutate client state, inspect [ConnectionManager.cs](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) for the lifecycle and disposal of live connections, open [UpdateBackupService.cs](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) to see how BackupInfo is serialized for persistence, and check the UI [ConnectDialog.cs](../Code/src/EchoHub.Client/UI/Dialogs/ConnectDialog.cs.md) to learn where connection information is captured and handed off to the connection manager. + +## Stop 6: Where to put new code +Use the conventional places represented by controllers, server services, and hubs when deciding where to add features or fixes. For HTTP and auth-related endpoints add or update controllers like [AuthController.cs](../Code/src/EchoHub.Server/Controllers/AuthController.cs.md); server-side domain operations belong in services such as [ChannelService.cs](../Code/src/EchoHub.Server/Services/ChannelService.cs.md) (which implements IChannelService); and real-time or cross-connection behavior belongs in the SignalR hub [ChatHub.cs](../Code/src/EchoHub.Server/Hubs/ChatHub.cs.md). + +## Next steps +Run the app locally: read the two [Program.cs](../Code/src/EchoHub.Server/Program.cs.md) and [Program.cs](../Code/src/EchoHub.Client/Program.cs.md) files to learn how to start the server and client, then launch both projects and use the Connect dialog to exercise the [ChatHub](../Code/src/EchoHub.Server/Hubs/ChatHub.cs.md) path. + +--- +*Synthesised by Aurion on 2026-07-23 05:54:49 UTC* diff --git a/docs/auriondocs/Synthesis/Workflows/controller.md b/docs/auriondocs/Synthesis/Workflows/controller.md new file mode 100644 index 0000000..defcb1b --- /dev/null +++ b/docs/auriondocs/Synthesis/Workflows/controller.md @@ -0,0 +1,89 @@ +# Adding a new controller + +> *Workflow template auto-derived from 7 existing exemplar(s).* + +This template describes how to add a new HTTP controller to the server: reach for this pattern when you need a new API surface implemented as an [ApiController] class that exposes routes and actions. Use the reference controller below as the concrete shape to copy (attributes, base class, constructor injection, and action patterns), and consult the existing examples to match naming and placement. + +## Reference implementation + +```csharp +[ApiController] +[Route("api/files")] +[Authorize] +[EnableRateLimiting("general")] +public class FilesController : ControllerBase +{ + private readonly FileStorageService _fileStorage; + + public FilesController(FileStorageService fileStorage) + { + _fileStorage = fileStorage; + } + + /// <summary> + /// Serves an uploaded file. Anonymous by design: the unguessable GUID in the URL is the + /// access token (Discord-CDN-style capability URL), so attachment links can be opened + /// directly in a browser and shared to IRC clients. E2E-encrypted room blobs are + /// ciphertext at rest, so anonymous access reveals nothing for those channels. + /// </summary> + [HttpGet("{fileId}")] + [AllowAnonymous] + public IActionResult GetFile(string fileId) + { + if (!Guid.TryParse(fileId, out _)) + return BadRequest(new ErrorResponse("Invalid file identifier.")); + + var filePath = _fileStorage.GetFilePath(fileId); + + if (filePath is null) + return NotFound(new ErrorResponse("File not found.")); + + var contentType = Path.GetExtension(filePath).ToLowerInvariant() switch + { + ".jpg" or ".jpeg" => "image/jpeg", + ".png" => "image/png", + ".gif" => "image/gif", + ".webp" => "image/webp", + ".mp3" => "audio/mpeg", + ".wav" => "audio/wav", + ".ogg" => "audio/ogg", + ".flac" => "audio/flac", + ".aac" => "audio/aac", + ".m4a" => "audio/mp4", + ".wma" => "audio/x-ms-wma", + ".pdf" => "application/pdf", + ".txt" => "text/plain", + _ => "application/octet-stream" + }; + + // Images and audio render inline so a browser displays them instead of + // downloading; everything else keeps the attachment disposition. + if (contentType.StartsWith("image/") || contentType.StartsWith("audio/")) + return PhysicalFile(filePath, contentType); + + var fileName = Path.GetFileName(filePath); + return PhysicalFile(filePath, contentType, fileName); + } +} +``` + +## Where it lives + +Controllers in this codebase are placed under src/EchoHub.Server/Controllers, and exemplar files use names such as AuthController.cs, ChannelsController.cs, FilesController.cs, InvitesController.cs, ModerationController.cs, ServerController.cs, and UsersController.cs with corresponding public classes named AuthController, ChannelsController, FilesController, InvitesController, ModerationController, ServerController, and UsersController. Use that same folder and naming pattern when adding a new controller file. + +## Wiring + +A specific registration site for controllers was not detected in the symbol graph provided. Inspect the existing controllers listed below to see how they are referenced in the project and to follow the same runtime usage patterns used by the application. + +## Existing examples + +- [`AuthController`](../../Code/src/EchoHub.Server/Controllers/AuthController.cs.md) +- [`ChannelsController`](../../Code/src/EchoHub.Server/Controllers/ChannelsController.cs.md) +- [`FilesController`](../../Code/src/EchoHub.Server/Controllers/FilesController.cs.md) +- [`InvitesController`](../../Code/src/EchoHub.Server/Controllers/InvitesController.cs.md) +- [`ModerationController`](../../Code/src/EchoHub.Server/Controllers/ModerationController.cs.md) +- [`ServerController`](../../Code/src/EchoHub.Server/Controllers/ServerController.cs.md) +- [`UsersController`](../../Code/src/EchoHub.Server/Controllers/UsersController.cs.md) + +--- +*Synthesised by Aurion on 2026-07-23 05:55:15 UTC* diff --git a/docs/auriondocs/Synthesis/Workflows/service.md b/docs/auriondocs/Synthesis/Workflows/service.md new file mode 100644 index 0000000..d822f6a --- /dev/null +++ b/docs/auriondocs/Synthesis/Workflows/service.md @@ -0,0 +1,94 @@ +# Adding a new service + +> *Workflow template auto-derived from 8 existing exemplar(s).* + +Adding a new service + +When you need to encapsulate a piece of server functionality—either a long-lived background job or an application service consumed by controllers and other services—you add a new service type in this codebase. Use the existing service types in src/EchoHub.Server/Services as your models: pick a clear name that ends with "Service", place the source alongside the other services, and wire it up where services are registered. + +## Reference implementation + +Real code from `src/EchoHub.Server/Services/MuteExpirationService.cs` that a new instance can be modelled on: + +```csharp +/// <summary> +/// Background service that periodically unmutes users whose timed mute has expired. +/// </summary> +public sealed class MuteExpirationService : BackgroundService +{ + private static readonly TimeSpan CheckInterval = TimeSpan.FromSeconds(15); + + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger<MuteExpirationService> _logger; + + public MuteExpirationService(IServiceScopeFactory scopeFactory, ILogger<MuteExpirationService> logger) + { + _scopeFactory = scopeFactory; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await Task.Yield(); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + await UnmuteExpiredUsersAsync(stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Error checking mute expirations"); + } + + await Task.Delay(CheckInterval, stoppingToken); + } + } + + private async Task UnmuteExpiredUsersAsync(CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService<EchoHubDbContext>(); + + var now = DateTimeOffset.UtcNow; + var expired = await db.Users + .Where(u => u.IsMuted && u.MutedUntil.HasValue && u.MutedUntil.Value <= now) + .ToListAsync(ct); + + if (expired.Count == 0) + return; + + foreach (var user in expired) + { + user.IsMuted = false; + user.MutedUntil = null; + _logger.LogInformation("Auto-unmuted user {Username} (timed mute expired)", user.Username); + } + + await db.SaveChangesAsync(ct); + } +} +``` + +## Where it lives + +Service source files are placed in src/EchoHub.Server/Services. Existing service types include names such as ChannelService, ChatService, FileCleanupService, FileStorageService, LinkEmbedService, MessageEncryptionService, MuteExpirationService, and ServerDirectoryService; each service file in that folder defines the corresponding type (for example, public class ChannelService : IChannelService and public sealed class FileCleanupService : BackgroundService). Follow the same placement and name your new type with a Service suffix so it sits alongside these exemplars. + +## Wiring + +Detected registration/composition site: src/EchoHub.Server/Program.cs. Inspect that file to see how services from src/EchoHub.Server/Services are registered and how hosted/background services are added to the application; new service types should be wired there consistent with the existing registrations. + +## Existing examples + +- [`ChannelService`](../../Code/src/EchoHub.Server/Services/ChannelService.cs.md) +- [`ChatService`](../../Code/src/EchoHub.Server/Services/ChatService.cs.md) +- [`FileCleanupService`](../../Code/src/EchoHub.Server/Services/FileCleanupService.cs.md) +- [`FileStorageService`](../../Code/src/EchoHub.Server/Services/FileStorageService.cs.md) +- [`LinkEmbedService`](../../Code/src/EchoHub.Server/Services/LinkEmbedService.cs.md) +- [`MessageEncryptionService`](../../Code/src/EchoHub.Server/Services/MessageEncryptionService.cs.md) +- [`MuteExpirationService`](../../Code/src/EchoHub.Server/Services/MuteExpirationService.cs.md) +- [`ServerDirectoryService`](../../Code/src/EchoHub.Server/Services/ServerDirectoryService.cs.md) + +--- +*Synthesised by Aurion on 2026-07-23 05:55:34 UTC* diff --git a/docs/auriondocs/Synthesis/api-client-authentication.md b/docs/auriondocs/Synthesis/api-client-authentication.md new file mode 100644 index 0000000..47d2604 --- /dev/null +++ b/docs/auriondocs/Synthesis/api-client-authentication.md @@ -0,0 +1,54 @@ +# API client and authentication + +> How the EchoHub client authenticates with the server, handles tokens, and defines authentication DTOs. + +This guide explains how the EchoHub client performs HTTP operations and manages authentication tokens, and it documents the DTOs the client uses when talking to the server. It focuses on the client-side [ApiClient](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) as the central point for login/refresh/logout and common API operations, and the small set of DTOs and client callback interface the ApiClient consumes and produces. Read this when you need to understand which types carry credentials and tokens, how attachments and avatar uploads are represented, and where server-initiated events are delivered on the client. + +## ApiClient.cs +Implements token management and API calls to the EchoHub server. + +The [ApiClient](../Code/src/EchoHub.Client/Services/ApiClient.cs.md) class is a high-level HTTP client that centralizes authentication lifecycle (LoginAsync, LoginWithRefreshTokenAsync, RefreshTokenAsync, LogoutAsync, SetTokens) and exposes token state via properties like Token, RefreshToken, and ExpiresAt. It provides helper methods for authenticated requests (AuthenticatedRequestAsync, AuthenticatedGetAsync, EnsureAuthenticated, GetValidTokenAsync) and common server operations surfaced to callers: channel and message management (CreateChannelAsync, DeleteChannelAsync, SendMessageWithAttachmentsAsync, DeleteMessageAsync, RekeyChannelAsync, NukeChannelAsync), moderation actions (AssignRoleAsync, BanUserAsync, KickUserAsync, MuteUserAsync, UnbanUserAsync, UnmuteUserAsync), profile and upload flows (UploadAvatarAsync, DownloadFileToTempAsync, UpdateProfileAsync, ExportMyDataAsync, DeleteMyAccountAsync), and utilities for handling file content types (GetContentType). The ApiClient implements IDisposable (Dispose) and contains response handling helpers (EnsureSuccessAsync) so callers get a single, managed surface for HTTP/authorization concerns. According to its relationships it depends on the DTO definitions in [AuthDtos](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md), [ChatDtos](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md), [ModerationDtos](../Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md), and [ProfileDtos](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md); in practice the ApiClient serializes and deserializes instances of those DTOs when calling corresponding endpoints and when returning structured results to its callers. + +## AuthDtos.cs +Defines login request data structure used to authenticate. + +The [AuthDtos](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) file defines the transport types used by the authentication endpoints: the immutable positional [LoginRequest](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) record carrying Username and Password, the [LoginResponse](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) record that bundles Token, RefreshToken, ExpiresAt and basic user identity fields, plus a [RefreshRequest](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) and [RegisterRequest](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md). These DTOs are pure data containers (no business logic) intended to be serialized over HTTP; the documentation calls out that Password is sensitive and that LoginResponse is what clients consume to establish an authenticated session. The ApiClient uses these DTOs when performing login and token-refresh flows (see relationships: used by ApiClient.cs). + +## AuthDtos.cs (LoginResponse) +Represents server response after authentication including tokens. + +The [LoginResponse](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) record is the structured server reply to a successful authentication, containing the short-lived Token, the RefreshToken, an ExpiresAt timestamp, and identifying fields like Username with optional display personalization. Clients (like the [ApiClient](../Code/src/EchoHub.Client/Services/ApiClient.cs.md)) consume LoginResponse to populate their in-memory token state and to drive expiration/refresh logic; because it contains the expiry moment, consumers can decide when to call RefreshTokenAsync or LoginWithRefreshTokenAsync instead of issuing unauthenticated requests. + +## AuthDtos.cs (RefreshRequest) +Represents refresh token request for renewing authentication. + +The [RefreshRequest](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md) is the DTO used to request new authentication tokens from the server using a refresh token. It is the lightweight, immutable payload the ApiClient will serialize when it invokes its refresh endpoint (RefreshTokenAsync / LoginWithRefreshTokenAsync) so the server can validate the refresh token and return a new [LoginResponse](../Code/src/EchoHub.Core/DTOs/AuthDtos.cs.md). + +## IEchoHubClient.cs +Interface for EchoHub client surface used by ApiClient to perform operations. + +The [IEchoHubClient](../Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md) interface defines the callback surface that a client implementing the real-time hub must provide: methods such as ReceiveMessage(MessageDto), UserJoined(channelName, username, UserPresenceDto?), UserLeft, ChannelUpdated(ChannelDto), UserStatusChanged, UserKicked, UserBanned, MessageDeleted, ChannelDeleted, ChannelNuked, ForceDisconnect, and Error. The doc shows example minimal implementations that log or handle these events quickly and non-blockingly. While the ApiClient handles HTTP and token management, this interface is the typed contract used by any hub/transport layer to deliver server-initiated events to client code; the relationship shows IEchoHubClient depends on DTO types like those in [ChatDtos](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) and [ProfileDtos](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md), which are delivered through these callbacks. + +## ChatDtos.cs +`AttachmentDto` collaborates directly with `ApiClient` and other members of this topic (10 dependency links). + +The [ChatDtos](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) file defines message and channel payloads used across both HTTP API and hub callbacks. In particular, the [AttachmentDto](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) record carries Kind (AttachmentKind), Url, FileName, FileSize, and an optional AsciiPreview; it represents a message attachment's metadata and is the shape ApiClient sends or receives when uploading, downloading, or rendering attachments. Other DTOs in the same file (MessageDto, ChannelDto, ChannelMetaDto, SendMessageRequest, SendUrlRequest, ReplyRefDto, etc.) are the structured inputs and outputs ApiClient uses for channel operations and that appear on the [IEchoHubClient](../Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md) callbacks. The docs note an important detail: in end-to-end encrypted channels the content behind the Url (and previews) may be ciphertext opaque to the server, which affects how clients process the Url returned in AttachmentDto. + +## ModerationDtos.cs +`AssignRoleRequest` collaborates directly with `ApiClient` and other members of this topic (4 dependency links). + +The [ModerationDtos](../Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md) file provides small, immutable payloads for moderation actions; the [AssignRoleRequest](../Code/src/EchoHub.Core/DTOs/ModerationDtos.cs.md) record carries a Username and a ServerRole value and is intended to be sent to moderation endpoints to request a role change. The file also contains BanRequest, KickRequest, and MuteRequest records used for banning, kicking, and muting operations. The ApiClient serializes these DTOs when invoking its moderation methods (AssignRoleAsync, BanUserAsync, KickUserAsync, MuteUserAsync), so moderation actions are expressed as data objects across the HTTP boundary. + +## ProfileDtos.cs +`AvatarUploadResponse` collaborates directly with `ApiClient` and other members of this topic (4 dependency links). + +The [ProfileDtos](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md) file defines small user-profile payloads used by profile/update and avatar upload endpoints. The [AvatarUploadResponse](../Code/src/EchoHub.Core/DTOs/ProfileDtos.cs.md) record holds AvatarAscii, the ASCII-art representation returned after an avatar upload; ApiClient's UploadAvatarAsync returns or deserializes this DTO so callers can display or store the ASCII preview. UpdateProfileRequest and UpdateStatusRequest are optional-field records used for partial profile updates and are the payloads ApiClient will send via UpdateProfileAsync. + +How the pieces fit + +The ApiClient is the HTTP façade: it consumes and produces the DTOs in AuthDtos, ChatDtos, ModerationDtos, and ProfileDtos when calling server endpoints and populating client state. Authentication flows center on the LoginRequest/LoginResponse/RefreshRequest DTOs and ApiClient methods that set and refresh Token/RefreshToken and expose helpers like GetValidTokenAsync and EnsureAuthenticated. Separately, real-time server-to-client events are delivered through the [IEchoHubClient](../Code/src/EchoHub.Core/Contracts/IEchoHubClient.cs.md) callback interface using the same Chat and Profile DTOs, keeping transport and event handling decoupled while the ApiClient handles request/response semantics and token lifecycle. + +--- +*Covers 8 of 8 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:50:51 UTC* diff --git a/docs/auriondocs/Synthesis/attachments-transfer.md b/docs/auriondocs/Synthesis/attachments-transfer.md new file mode 100644 index 0000000..7bb614b --- /dev/null +++ b/docs/auriondocs/Synthesis/attachments-transfer.md @@ -0,0 +1,41 @@ +# Attachments and file transfers + +> Staging and sending attachments in chat messages and coordinating outbound attachments. + +Outgoing attachments are staged in the UI, packaged as transport objects, and then coordinated through the app orchestrator into the live connection for transmission. This topic shows the small set of types and methods that carry file streams and metadata from the MainWindow staging UI through AppOrchestrator into the connection layer so they can be uploaded (optionally encrypted) and surfaced as attachment DTOs in messages. + +## OutgoingAttachment.cs +Represents an attachment queued for sending to a channel or user. + +The [OutgoingAttachment](../Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md) record is the in-process transport object used to carry a single file stream and its filename through the sending pipeline. It declares four properties: the raw Stream and FileName (required), and two optional strings DeclaredKind and EncryptedPreview which are intended for end-to-end encrypted scenarios. As a record it provides value-based equality for tracking/deduplication but notably does not manage the Stream lifetime — callers open and dispose streams around instances of this type. In this topic it is produced/consumed by the orchestrator layer (see [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md)). + +## MainWindow.cs +Provides UI hooks for staging attachments and displaying progress. + +The [MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md) component exposes the user-facing hooks that allow files to be staged and progress or status to be shown. Among its many members are StageFiles (to accept user-selected files) and SetStagedAttachments (to update the UI with the current list of staged items), plus UI update methods such as UpdateSpinner/UpdateInputTitle to reflect in-progress operations. MainWindow depends on the message/attachment DTO types in [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) for rendering metadata and is called by [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) when orchestrated work (prepare/send/clear attachments) must update the UI. + +## AppOrchestrator.cs +Builds outbound attachments and coordinates sending operations. + +The [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) owns the high-level send flow: it implements BuildOutgoingAttachmentAsync to assemble outbound attachment payloads (creating [OutgoingAttachment](../Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md) instances), provides cleanup helpers such as CleanupPastedTempFiles, and contains command handlers like HandleCmdSendFile and HandleCmdClearAttachments that respond to user actions. It depends on the DTO types in [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) when preparing message payloads and coordinates with the UI by reading staged files from and writing status back to [MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md). For transmission the orchestrator delegates connection and delivery responsibilities to the connection layer ([ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md)). + +## ConnectionManager.cs +`ConnectionManager` collaborates directly with `AppOrchestrator` and other members of this topic (4 dependency links). + +The [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) encapsulates the live chat connection lifecycle: authentication, optional end-to-end key fetching, and instantiation/wiring of the SignalR hub connection. It exposes a thin event surface so UI code (principally [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md)) can subscribe to SignalR events without dealing with SignalR details, and it implements IAsyncDisposable so the orchestrator can tear down network resources cleanly. ConnectAsync (documented in the file) reports progress via a provided onStatus callback, treats failure to obtain an E2E key as non-fatal, and returns compound results (the internal [ConnectResult](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) record) that include login, channel list, and histories for the orchestrator to use. + +## ChatDtos.cs +`AttachmentDto` collaborates directly with `AppOrchestrator` and other members of this topic (4 dependency links). + +The [AttachmentDto](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) is the immutable transport representation of an attachment that travels with messages: it records the attachment Kind, a Url where the resource can be retrieved, FileName, FileSize, and an optional AsciiPreview used for character-art rendering. The DTO is the canonical metadata shape used across UI, API, and connection boundaries; the orchestrator uses these DTO types when composing or processing message payloads, and the MainWindow reads them to render attachments in the UI. In end-to-end encrypted channels the DTO’s Url and AsciiPreview may represent ciphertext that the server cannot interpret. + +How the pieces fit + +- UI staging: users pick files via [MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md). MainWindow.StageFiles and SetStagedAttachments hold the files and show progress to the user while AppOrchestrator drives the workflow. +- Packaging: [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) constructs [OutgoingAttachment](../Code/src/EchoHub.Client/Services/OutgoingAttachment.cs.md) records (via BuildOutgoingAttachmentAsync), cleans up temp files, and maps to the DTO shapes from [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) when preparing messages. +- Delivery: the orchestrator delegates network work to [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md), which manages connection/auth/E2E keys and forwards events so the UI and orchestrator can report progress and completion. + +--- +*Covers 5 of 5 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:53:19 UTC* diff --git a/docs/auriondocs/Synthesis/clipboard-tools.md b/docs/auriondocs/Synthesis/clipboard-tools.md new file mode 100644 index 0000000..9425ba1 --- /dev/null +++ b/docs/auriondocs/Synthesis/clipboard-tools.md @@ -0,0 +1,31 @@ +# Clipboard utilities + +> Helpers for clipboard interactions: files and images. + +This guide describes the clipboard-focused utilities in the client: one helper that exposes file-list clipboard contents, another that normalizes image clipboard data into PNG bytes, and the UI entry points that call those helpers to stage attachments or consume images. + +## ClipboardFiles.cs +Clipboard file utilities for handling file lists. + +The [ClipboardFiles](../Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md) static class provides a single, platform-aware API (exposed via TryGetFiles) to read file paths when the OS clipboard contains a file-list. It hides OS-specific handling—on Windows it reads CF_HDROP with a short retry loop to tolerate clipboard contention, on Linux it uses text/uri-list through wl-paste or xclip—and it performs existence checks and filters out non-file entries so callers receive only existing paths. TryGetFiles returns true only when at least one valid file path is found, otherwise false, allowing callers to fall back if no usable file-list is present; this class is consumed by the UI layer ([MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md)). + +## ClipboardImage.cs +Clipboard image utilities for copying images to the clipboard. + +The [ClipboardImage](../Code/src/EchoHub.Client/Services/ClipboardImage.cs.md) static class exposes TryGetPng to extract whatever image is currently on the OS clipboard and return it as PNG-encoded bytes suitable for saving, embedding, or transmitting. It normalizes multiple clipboard image formats: it prefers a native PNG clipboard format to preserve alpha, and falls back to platform bitmaps (CF_DIB on Windows) by wrapping DIB bytes in a minimal BMP header and decoding/re-encoding to PNG via DibToPng; malformed DIB input yields null and TryGetPng surfaces that as a failure (false). TryGetPng routes to OS-specific helpers, logs errors rather than throwing, and returns false on unsupported platforms or on failure; [MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md) depends on this helper to obtain clipboard image bytes. + +## MainWindow.cs +`MainWindow` collaborates directly with `ClipboardFiles` and other members of this topic (2 dependency links). + +The [MainWindow](../Code/src/EchoHub.Client/UI/MainWindow.cs.md) UI class defines a large set of interactive behaviors and a handful of members that interact with the clipboard: notably methods named StageFiles, SetStagedAttachments and GuardedClipboardAction appear in its surface. Per the documented relationships, MainWindow delegates platform specifics to the clipboard helpers: it invokes [ClipboardFiles](../Code/src/EchoHub.Client/Services/ClipboardFiles.cs.md).TryGetFiles to obtain file paths copied by the user and then uses its own staging APIs (SetStagedAttachments/StageFiles) to prepare those paths for attachment. Likewise, MainWindow can call [ClipboardImage](../Code/src/EchoHub.Client/Services/ClipboardImage.cs.md).TryGetPng to obtain a normalized PNG byte array when the user has copied an image, allowing the UI to save, embed, or attach that image without per-OS handling. GuardedClipboardAction provides a place to centralize error handling and UI feedback around those clipboard calls so failures from the helpers (they return false rather than throwing) can be handled gracefully. + +How the pieces fit + +- The two service classes encapsulate platform-specific clipboard concerns: [ClipboardFiles] returns a filtered list of existing file paths or false; [ClipboardImage] returns a PNG byte array or false. +- [MainWindow] orchestrates user-facing clipboard flows: it calls those helpers from StageFiles/SetStagedAttachments and related clipboard actions, then integrates the results into the message-composition and attachment UI. +- The helpers favor returning a simple success/failure result (and normalized data) so the UI can decide whether to stage attachments, embed image bytes, or fall back to alternative input methods. + +--- +*Covers 3 of 3 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:53:51 UTC* diff --git a/docs/auriondocs/Synthesis/command-handling.md b/docs/auriondocs/Synthesis/command-handling.md new file mode 100644 index 0000000..1950154 --- /dev/null +++ b/docs/auriondocs/Synthesis/command-handling.md @@ -0,0 +1,46 @@ +# Command handling + +> Slash-command parsing and dispatching command actions from UI and orchestrator. + +*Figure: How Command handling works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +sequenceDiagram +participant Client +participant ConnectionManager_cs as ConnectionManager.cs +participant AppOrchestrator_cs as AppOrchestrator.cs +participant CommandHandler_cs as CommandHandler.cs +Client->>ConnectionManager_cs: UI sends slash command +ConnectionManager_cs->>AppOrchestrator_cs: forward command to orchestrator +AppOrchestrator_cs->>CommandHandler_cs: invoke command parsing and dispatch +CommandHandler_cs-->>AppOrchestrator_cs: return parsed action/result +AppOrchestrator_cs->>ConnectionManager_cs: dispatch action / send response +ConnectionManager_cs-->>Client: deliver response to UI +``` + +This guide explains how user-entered slash commands move from text input into application behavior and network actions. It describes the parsing and event surface (the command-to-event bridge), the central orchestrator that implements command handlers and coordinates UI-side concerns, and the connection manager that owns the live SignalR connection and performs the network work the orchestrator requests. + +## CommandHandler.cs +Parses and executes chat commands; determines if input is a command. + +The [CommandHandler](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) class is the input-to-event bridge: it recognizes whether a text input is a slash command (via IsCommand) and runs a suite of HandleXxx parsing routines (for example HandleSetStatus, HandleSendAction, HandleCreateInvite, HandleExportData and many others listed in the source). It does not perform side effects itself; instead it exposes one event per supported command (OnSetStatus, OnSendAction, OnCreateInvite, OnExportData, etc.) and raises asynchronous events after parsing. The class also contains parsing helpers and semantics notes (status handling, StripQuotes, IsValidHex, ParsePathAndSizeFlag) so subscribers can depend on a consistent interpretation of user input. According to the topic relationships, this component is consumed by the [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md), which subscribes to those events to implement behavior. + +## AppOrchestrator.cs +Central coordinator handling command-related actions and user commands across the app. + +The [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) wires the command parsing surface into application behavior: it subscribes to the events emitted by the [CommandHandler](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) and implements the concrete handlers named in the source (a large set of HandleCmd* methods such as HandleCmdSetStatus, HandleCmdSendFile, HandleCmdJoinChannel, HandleCmdCreateInvite, HandleCmdExportData, HandleCmdKickUser, HandleCmdNukeChannel, etc.). It also owns UI-side responsibilities like BuildOutgoingAttachmentAsync, EnsureRoomUnlockedForSendAsync, CleanupPastedTempFiles, pending reply management, and resource cleanup (Dispose). Per its relationships the orchestrator depends on both [CommandHandler](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md) for parsing and [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) for performing network operations; the source shows it translating parsed commands into calls and requests that drive the connection layer. The file also documents many small, focused flow steps (ApplyAsciiSize, HandleChannelSelected, HandleEditProfile, etc.) that adapt command intent into concrete application actions. + +## ConnectionManager.cs +`ConnectionManager` collaborates directly with `AppOrchestrator` and other members of this topic (4 dependency links). + +The [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) owns the full lifecycle of a live chat connection: authentication and token handling, attempting to fetch and apply end-to-end encryption keys, instantiating and wiring the EchoHub (SignalR) connection, tracking which channels are joined, and forwarding SignalR callbacks as simple .NET events the UI can subscribe to. It exposes ConnectAsync semantics (reporting progress via an onStatus callback and throwing on authentication failure) and implements IAsyncDisposable so callers can call DisposeAsync to tear down the hub and underlying ApiClient. The file also defines the [ConnectResult](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) record (Login, Channels, Histories) that packages the login response, joined channels list, and message histories returned by ConnectAsync. Notes in the source call out important behaviors: failures to fetch encryption keys are non-fatal, forwarded events may arrive on background threads, and callers (principally the [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md)) must handle marshal-to-UI-thread concerns. + +How the pieces fit + +User input flows into [CommandHandler](../Code/src/EchoHub.Client/Commands/CommandHandler.cs.md), which parses text and emits a focused event per command. [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) subscribes to those events and implements the HandleCmd* methods that translate parsed intent into application actions and requests; when a command requires network interaction, AppOrchestrator delegates to [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md). ConnectionManager manages the SignalR connection and returns results or raises network events back to the orchestrator, while AppOrchestrator handles UI concerns (attachments, pending replies, local state) and coordinates lifecycle and cleanup. + +--- +*Covers 3 of 3 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:52:46 UTC* diff --git a/docs/auriondocs/Synthesis/encryption-roomkeys.md b/docs/auriondocs/Synthesis/encryption-roomkeys.md new file mode 100644 index 0000000..3a46d3a --- /dev/null +++ b/docs/auriondocs/Synthesis/encryption-roomkeys.md @@ -0,0 +1,79 @@ +# Encryption and room key management + +> End-to-end encryption plumbing and secure handling of per-channel room keys. + +*Figure: How Encryption and room key management works.* + +```mermaid +%%{init: {'theme':'base','themeVariables':{'background':'#faf7ef','primaryColor':'#f0e2c2','primaryTextColor':'#1f2840','primaryBorderColor':'#8a7548','secondaryColor':'#d9efec','secondaryBorderColor':'#1d8a80','secondaryTextColor':'#1f2840','tertiaryColor':'#f2ebd8','tertiaryBorderColor':'#8a7548','tertiaryTextColor':'#1f2840','lineColor':'#1d8a80','titleColor':'#1f2840','fontSize':'14px','edgeLabelBackground':'#faf7ef','clusterBkg':'#f2ebd8','clusterBorder':'#8a7548','actorBkg':'#f0e2c2','actorBorder':'#8a7548','actorTextColor':'#1f2840','actorLineColor':'#8a7548','signalColor':'#1d8a80','signalTextColor':'#1f2840','activationBkgColor':'#d9efec','activationBorderColor':'#1d8a80','noteBkgColor':'#f2ebd8','noteBorderColor':'#8a7548','noteTextColor':'#1f2840','labelBoxBkgColor':'#f0e2c2','labelBoxBorderColor':'#8a7548','labelTextColor':'#1f2840','transitionColor':'#1d8a80','transitionLabelColor':'#1f2840','stateLabelColor':'#1f2840','altBackground':'#f2ebd8'}}}%% +sequenceDiagram +participant ConnectionManager +participant ClientConfig +participant RoomKeyProtector +participant RoomKeyStore +participant ClientEncryptionService + +ConnectionManager->>ClientConfig: Load AccountPreset +ClientConfig->>RoomKeyProtector: Initialize/Acquire protector +RoomKeyProtector-->>ClientConfig: Protector instance + +ConnectionManager->>RoomKeyStore: Initialize RoomKeyStore +RoomKeyStore->>ClientConfig: Read AccountPreset/config +ClientConfig-->>RoomKeyStore: Config data + +RoomKeyStore->>RoomKeyProtector: Protect/Unprotect room keys +RoomKeyProtector-->>RoomKeyStore: Protected/Decrypted key + +ConnectionManager->>ClientEncryptionService: Register IMessageEncryptionService +ClientEncryptionService-->>ConnectionManager: Encryption service ready + +ConnectionManager->>RoomKeyStore: Request room key for channel +RoomKeyStore->>RoomKeyProtector: Decrypt room key +RoomKeyProtector-->>RoomKeyStore: Plain room key +RoomKeyStore-->>ConnectionManager: Return room key + +ConnectionManager->>ClientEncryptionService: Encrypt/Decrypt message with room key +ClientEncryptionService-->>ConnectionManager: Encrypted/Decrypted payload +``` + +# Encryption and room key management + +End-to-end encryption in the client is implemented as a few focused components: a runtime encryptor that mirrors the server format, a protector that encrypts per-channel room keys at rest, a store that binds persisted server entries to an in-memory cache, and a connection manager that wires those pieces into the live SignalR connection. This guide explains what each file actually implements, how they call each other, and where responsibilities (in-memory keys, persisted protected keys, and message-level cryptography) are split. + +## ClientEncryptionService.cs +Implements IMessageEncryptionService for encrypting/decrypting messages. + +The [ClientEncryptionService](../Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md) class is the client-side AES-256-GCM encryptor/decryptor that mirrors the server’s encryption format so clients and server exchange the same payload shape. It exposes SetKey to accept a 32-byte, server-provided base64 key, Encrypt to produce a prefixed base64 payload containing nonce and ciphertext+tag, and Decrypt to reverse that encoding; before a key is set Encrypt is intentionally a no-op and returns plaintext, and Decrypt returns a sentinel failure message when decryption fails. Per the documentation, the service isolates cryptography behind a swappable implementation and is used by higher-level connection code to apply message encryption only when a key is loaded; in this topic it is referenced by [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md). + +## RoomKeyProtector.cs +Provides protection around room keys for secure storage/usage. + +The [RoomKeyProtector](../Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md) class is the single API for protecting and unprotecting per-user room content keys before they are written to or read from client configuration. Its Protect method returns a storage-ready string that is prefixed to indicate the protection method ("dp1:" for Windows DPAPI or "k1:" for an AES-GCM-encrypted master key file on other platforms), and TryUnprotect attempts to recover the raw room key while reporting whether the stored value was a legacy plain-base64 entry and whether unprotection succeeded. The class accepts a directory (to locate the master key file) and caches the master key after guarded loading; callers such as [ClientConfig](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) and [RoomKeyStore](../Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md) rely on it to convert between in-memory bytes and protected storage strings without having to deal with platform-specific details. + +## RoomKeyStore.cs +Stores and retrieves room keys securely for channels. + +[RoomKeyStore](../Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md) binds runtime state (a decrypted, in-memory cache of room keys) to persisted per-server entries so users don't re-enter passphrases every launch. You call LoadForServer(serverUrl) to bind the store to a SavedServer in [ClientConfig](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md); the store will read that SavedServer's ChannelKeys, call into [RoomKeyProtector](../Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md) to unprotect them, and populate its thread-safe cache. The class exposes methods to TryGetKey, StoreKey, Replace/Remove keys, and TryStoreFromEnvelope (which unwraps a wrapped key with a KEK) and will upgrade legacy plain/base64 entries to the protected format when possible; changes are persisted back to the SavedServer through ClientConfig and unreadable entries are logged rather than failing hard. Connection-side code (notably [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md)) uses RoomKeyStore to determine which channels are encrypted and to retrieve keys for encrypting/decrypting messages at send/receive time. + +## ClientConfig.cs +`ClientConfig` collaborates directly with `RoomKeyProtector` and other members of this topic (3 dependency links). + +[ClientConfig](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) is the central container for a user's persisted preferences and runtime state, and it holds SavedServer entries that include the persisted, protected ChannelKeys consumed by [RoomKeyStore](../Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md). ClientConfig provides the serialized place where RoomKeyProtector-generated strings live (the protector prefixes such as "dp1:" or "k1:" are stored here), and callers such as RoomKeyStore read and write these SavedServer entries to keep the on-disk picture in sync with the in-memory cache. Because RoomKeyProtector derives its key-file location from a directory you pass to its constructor, ClientConfig’s location and usage patterns determine where the master key file will be stored and how RoomKeyStore persists upgrades from legacy entries. + +## ConnectionManager.cs +`ConnectionManager` collaborates directly with `ClientEncryptionService` and other members of this topic (2 dependency links). + +[ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) is the high-level lifecycle owner for authentication, establishing the EchoHub SignalR connection, and wiring end-to-end encryption into runtime behavior. During ConnectAsync it performs authentication (throwing on auth failure), attempts to fetch and apply an E2E encryption key (failure to fetch is non-fatal and the manager logs a warning), and then uses the [ClientEncryptionService](../Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md) to encrypt outbound messages and decrypt inbound ones when a key is present. It relies on [RoomKeyStore](../Code/src/EchoHub.Client/Services/RoomKeyStore.cs.md) to know which channels are encrypted and to obtain per-channel room keys, and it uses [ClientConfig](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) as the backing persisted configuration for saved servers; ConnectionManager forwards SignalR events as simple .NET events and implements IAsyncDisposable so callers can cleanly tear down network and API resources. + +How the pieces fit + +- ConnectionManager is the orchestrator: it authenticates, attempts to fetch the server-provided E2E key, wires SignalR events to the UI, and delegates message-level cryptography to [ClientEncryptionService](../Code/src/EchoHub.Client/Services/ClientEncryptionService.cs.md) when a key is present. +- RoomKeyStore sits between persisted state and runtime: it loads and persists ChannelKeys via [ClientConfig](../Code/src/EchoHub.Client/Config/ClientConfig.cs.md) and uses [RoomKeyProtector](../Code/src/EchoHub.Client/Services/RoomKeyProtector.cs.md) to unprotect/protect those keys so the on-disk config never contains raw base64 room keys (legacy unprotected values are upgraded when possible). +- RoomKeyProtector implements the platform-specific protection formats (DPAPI or a file-backed AES-GCM master key) and presents a stable Protect/TryUnprotect API so the higher-level store and config code do not need to handle cryptography details. + +Together these components keep plaintext room keys out of persistent storage, keep a decrypted cache for active sessions, and ensure message encryption happens only when a server-supplied key has been loaded and applied by the client encryptor. + +--- +*Covers 5 of 5 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:52:19 UTC* diff --git a/docs/auriondocs/Synthesis/real-time-connection.md b/docs/auriondocs/Synthesis/real-time-connection.md new file mode 100644 index 0000000..1db6744 --- /dev/null +++ b/docs/auriondocs/Synthesis/real-time-connection.md @@ -0,0 +1,34 @@ +# Real-time connection management + +> Managing the SignalR hub connection lifecycle and connection state. + +# Real-time connection management + +This guide explains how the client-side pieces manage a SignalR-based chat connection, surface server events to the UI, and carry message and attachment DTOs across those boundaries. Read it to understand which types own the HubConnection lifecycle, which types represent messages and attachments, and how connection orchestration hands events and histories back to the UI layer. + +## EchoHubConnection.cs + +Encapsulates the SignalR connection to the server and join history with encryption info. + +The [EchoHubConnection](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) type is a thin, SignalR-backed client wrapper that owns a HubConnection and translates server callbacks into plain .NET events (for example OnMessageReceived, OnUserJoined, OnChannelUpdated). It also integrates client-side encryption and room-key lookup: incoming payloads are decrypted before being raised to subscribers, and join history plus encryption metadata is tracked so callers can present past messages. EchoHubConnection declares focused exception types such as ChannelPasswordRequiredException (thrown when a join fails for password reasons) to enable UI-driven retry flows. According to the file relationships, EchoHubConnection consumes message and channel shapes from [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) and is instantiated and used by [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md). + +## ConnectionManager.cs + +Coordinates connection lifecycle and connection events across the client. + +The [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) is the high-level owner of authentication, E2E key retrieval, HubConnection creation, wiring of SignalR callbacks, and tracking of joined channels. It exposes a small event surface that forwards the EchoHubConnection events to the UI (the doc notes AppOrchestrator subscribes), implements IAsyncDisposable to tear down both the hub wrapper and the underlying client, and reports progress from ConnectAsync via an onStatus callback while throwing on authentication failure. ConnectionManager also defines the [ConnectResult](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) record that packages the login response, a list of channel DTOs, and a dictionary of channel histories (the histories contain [MessageDto] entries defined in ChatDtos). Per the relationships, ConnectionManager depends on [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) for payload shapes and on [EchoHubConnection](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) to manage the live SignalR interactions. + +## ChatDtos.cs + +`AttachmentDto` collaborates directly with `ConnectResult` and other members of this topic (9 dependency links). + +[ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) defines the immutable DTOs used across the connection boundary: records such as AttachmentDto, ChannelDto, ChannelMetaDto, MessageDto, JoinChannelResult, and request shapes like SendMessageRequest. The [AttachmentDto](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) record carries metadata for file attachments (kind, URL, filename, filesize, optional ASCII preview) and is explicitly designed to work with end-to-end encrypted channels where the resource behind Url may be ciphertext the server cannot read. These DTOs are the concrete payload shapes that both [EchoHubConnection](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md) and [ConnectionManager](../Code/src/EchoHub.Client/Services/ConnectionManager.cs.md) send, receive, and store in histories. + +How the pieces fit + +ConnectionManager is the orchestration layer: it authenticates, attempts to acquire E2E keys, builds and wires an [EchoHubConnection](../Code/src/EchoHub.Client/Services/EchoHubConnection.cs.md), and exposes forwarded events to the UI while tracking joined channels and histories. EchoHubConnection is the SignalR-focused implementation that manages the HubConnection lifecycle, maps server callbacks to events, performs decryption of incoming payloads, and throws focused exceptions (for example ChannelPasswordRequiredException) so the UI can prompt and retry joins. The DTOs in [ChatDtos.cs](../Code/src/EchoHub.Core/DTOs/ChatDtos.cs.md) are the shared, immutable shapes (messages, channels, attachments) that flow between the manager, the hub wrapper, and the UI; ConnectResult packages those DTOs back to callers after an initial connect sequence. + +--- +*Covers 3 of 3 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:51:44 UTC* diff --git a/docs/auriondocs/Synthesis/ui-theming.md b/docs/auriondocs/Synthesis/ui-theming.md new file mode 100644 index 0000000..ad9123b --- /dev/null +++ b/docs/auriondocs/Synthesis/ui-theming.md @@ -0,0 +1,31 @@ +# Theming and UI color management + +> Representing themes, color palettes, and runtime theme application. + +Theming and UI color management + +The files in this topic define how the EchoHub client represents color themes, exposes a curated set of built-in and user-provided themes, and wires theme selection into the running application. Read these three artifacts to understand the Theme data model, the static ThemeManager API that discovers/applies/persists themes, and the AppOrchestrator entry point that reacts to user commands and delegates theme work to the manager. + +## Theme.cs +Represents a UI theme. + +The [Theme](../Code/src/EchoHub.Client/Themes/Theme.cs.md) class is the data container for a complete UI appearance. It exposes a required Name plus four area-specific palettes—Base, Menu, Dialog, and Status—each typed as a [ThemeColors](../Code/src/EchoHub.Client/Themes/Theme.cs.md) instance, and an optional Border palette that, when set, overrides only frame-border colors while leaving other chrome tied to Base. The writer notes sensible defaults: each palette initializes to a new ThemeColors so a Theme is usable with minimal configuration, and Border accepts hex literals or named colors to let designers tint edges without touching text palettes. This file is the canonical representation of a theme and is consumed by the [ThemeManager](../Code/src/EchoHub.Client/Themes/ThemeManager.cs.md) to build and persist theme choices and by the [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) when the application needs to apply or react to theme changes. + +## ThemeManager.cs +Loads, caches, and applies themes across the app. + +[ThemeManager](../Code/src/EchoHub.Client/Themes/ThemeManager.cs.md) is a static API that bridges theme data and runtime application. It exposes discovery and retrieval functions such as GetAvailableThemes and GetTheme, mutation points like SaveTheme, and the runtime switch ApplyTheme; utility functions include ParseColor and BuildColorScheme, the latter ensuring colors for editable/read-only roles and transparency behave correctly so inputs remain legible under transparent themes. ThemeManager maintains a curated set of built-in theme factory methods (DefaultTheme, DraculaTheme, LightTheme, etc.), attempts to load additional themes from a user directory (ThemeDir), and falls back to built-ins if the directory cannot be read; SaveTheme is implemented best-effort and quietly swallows failures. Because it returns and manipulates [Theme](../Code/src/EchoHub.Client/Themes/Theme.cs.md) instances, ThemeManager is the component the [AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) calls when the app needs to enumerate, choose, or persist a theme and when it needs the computed color scheme to apply to the UI. + +## AppOrchestrator.cs +`AppOrchestrator` collaborates directly with `Theme` and other members of this topic (2 dependency links). + +[AppOrchestrator](../Code/src/EchoHub.Client/AppOrchestrator.cs.md) is the application-level coordinator that owns the MainWindow and a large set of command handlers; among its many responsibilities it includes a handler named HandleCmdSetTheme which responds to theme-change requests. In practice the orchestrator calls into [ThemeManager](../Code/src/EchoHub.Client/Themes/ThemeManager.cs.md) to fetch or apply a [Theme](../Code/src/EchoHub.Client/Themes/Theme.cs.md) (for example via GetTheme and ApplyTheme) and then ensures the active UI reflects the manager-provided color scheme. The doc block lists the constructor and MainWindow property plus the command handlers (including HandleCmdSetTheme) so the intended runtime flow is: user or code issues a theme command to AppOrchestrator, AppOrchestrator delegates theme discovery/load/apply to ThemeManager, and the Theme instance shapes the MainWindow styling. + +How the pieces fit + +Theme is the immutable-ish data model for visual choices; ThemeManager is the static service that discovers, builds, parses, and persists those models and produces a concrete color scheme via BuildColorScheme; AppOrchestrator is the runtime conductor that responds to user commands and uses ThemeManager to fetch and ApplyTheme to the UI. The dependency direction is AppOrchestrator -> ThemeManager -> Theme, with ThemeManager also responsible for supplying built-in Theme instances and reading user themes from disk when available. + +--- +*Covers 3 of 3 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:51:21 UTC* diff --git a/docs/auriondocs/Synthesis/update-management.md b/docs/auriondocs/Synthesis/update-management.md new file mode 100644 index 0000000..20c7c24 --- /dev/null +++ b/docs/auriondocs/Synthesis/update-management.md @@ -0,0 +1,32 @@ +# Update management + +> Data and update flow: backup prior to updates and update checks. + +Update management + +This topic covers the client-side update workflow: detecting available versions from the running Terminal.Gui app, deferring heavy update work until the UI has shut down, and snapshotting the application state so you can roll back if an update goes wrong. The two files coordinate a safe in-place updater by separating user interaction and terminal ownership (in UpdateChecker) from the filesystem snapshot and metadata (in UpdateBackupService). + +## UpdateBackupService.cs +Provides backup of user data before updates. + +The file declares three related symbols that implement pre-update snapshotting. [BackupJsonContext](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) is an internal, source-generated JsonSerializerContext that supplies reflection-free JSON metadata for serializing the on-disk metadata type. The public [UpdateBackupService](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) static class performs the actual backup/rollback responsibilities: it creates a ZIP snapshot of the running application under ~/.echohub/update-backup/ (backup.zip) and writes a companion backup-info.json (the [BackupInfo](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) contract) that records the version, application directory, and UTC timestamp. The service exposes operations to CreateBackup before applying an update, to check presence via BackupExists, and to read metadata with GetBackupInfo; it also exposes an IsPostUpdate flag that lets startup logic detect a recent update backup and react accordingly. Because the JSON context is internal and generated, callers within the assembly configure JsonSerializerOptions with BackupJsonContext when they read or write backup-info.json. + +The file is used by the update coordination logic in [UpdateChecker](../Code/src/EchoHub.Client/Services/UpdateChecker.cs.md): the checker defers the updater work but relies on UpdateBackupService to attempt a pre-update snapshot when the update is actually applied. + +## UpdateChecker.cs +Checks for updates and coordinates update flow. + +[UpdateChecker](../Code/src/EchoHub.Client/Services/UpdateChecker.cs.md) is a disposable helper that runs background polling and supports manual checks, while keeping all user interaction on the provided Terminal.Gui IApplication main loop. Its responsibilities are: poll for newer versions via an internal Updater, present a TUI confirmation dialog by marshalling callbacks with _app.Invoke, and — crucially — avoid performing download/extract/restart while the TUI still owns the terminal. When the user accepts an update, UpdateChecker sets PendingUpdate to an awaitable delegate (the internal ApplyUpdateAsync) and captures the chosen version, then signals the TUI to stop; the host is expected to call PendingUpdate after the main loop exits so the update can run headless and safely restart the process. + +Concrete behaviors documented in the class include: Start() only activates the periodic poller in RELEASE builds; PendingUpdate is intentionally a Task-returning delegate to be invoked by the host after the console is restored; ApplyUpdateAsync attempts to create a pre-update backup by calling [UpdateBackupService.CreateBackup](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) and logs but does not fail the update flow if backup creation fails; ApplyUpdateAsync also sets Console.OutputEncoding = UTF8 while swallowing exceptions for non-interactive stdout; and CurrentVersion reads the assembly version with a fallback of "0.0.0". + +How the pieces fit + +- Update detection and user confirmation happen inside [UpdateChecker](../Code/src/EchoHub.Client/Services/UpdateChecker.cs.md) running on the Terminal.Gui main loop; when the user accepts an update, the checker defers the actual work by setting PendingUpdate and requesting the TUI to stop. +- The deferred update work (ApplyUpdateAsync) calls into [UpdateBackupService](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) to snapshot the application: it writes backup.zip and backup-info.json (the serialized [BackupInfo](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md) using [BackupJsonContext](../Code/src/EchoHub.Client/Services/UpdateBackupService.cs.md)). Backup creation failures are logged but do not block the update. +- The host is responsible for invoking PendingUpdate only after the TUI main loop has fully exited and the console is restored, at which point the update runs headless (and may restart the process). + +--- +*Covers 2 of 2 source files identified for this topic.* + +*Synthesised by Aurion on 2026-07-23 05:54:19 UTC*